Basic Python Examples with Explanations
1. Hello World
This is the most basic program in any language. It prints a simple message.
Code:
print("Hello, World!")
2. Variables and Data Types
Variables store data. Python supports types like string, integer, and boolean.
Code:
name = "Gowthami"
age = 21
is_student = True
print(name, age, is_student)
3. If-Else Condition
Conditions allow decision-making based on values.
Code:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
Basic Python Examples with Explanations
else:
print("Grade: C")
4. For Loop
Loops are used to repeat a block of code a number of times.
Code:
for i in range(1, 6):
print("Number:", i)
5. While Loop
Executes as long as the condition is True.
Code:
i=1
while i <= 5:
print("Count:", i)
i += 1
6. Function Example
Functions help reuse code. They are defined using `def`.
Code:
def greet(name):
Basic Python Examples with Explanations
print("Hello", name)
greet("Gowthami")
7. List and Loop
Lists store multiple values. We can loop through them.
Code:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
8. Simple Calculator
Demonstrates arithmetic operations like add, subtract, multiply, divide.
Code:
a = 10
b=5
print("Add:", a + b)
print("Subtract:", a - b)
print("Multiply:", a * b)
print("Divide:", a / b)
9. Taking Input from User
Basic Python Examples with Explanations
Use `input()` to get user input from keyboard.
Code:
name = input("Enter your name: ")
print("Welcome", name)
10. Check Even or Odd
Checks if a number is even or odd using modulus operator `%`.
Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")