If / Else Statements
Why If/Else?
If/else helps your program make decisions based on conditions.
Example:
age = 20
if age >= 18:
print("You are an adult")
2. Basic If Statement
if condition:
# code
Example:
x = 10
if x > 5:
print("x is greater than 5")
3. If-Else
age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
4. If-Elif-Else
Used for multiple conditions.
marks = 75
if marks >= 90:
print("A Grade")
elif marks >= 75:
print("B Grade")
elif marks >= 50:
print("C Grade")
else:
print("Fail")
5. Nested If (If inside If)
age = 20
if age > 18:
print("Adult")
if age >= 60:
print("Senior Citizen")
6. Logical Operators with If
age = 25
if age > 18 and age < 30:
print("Age between 18 and 30")
7. Even or Odd Program
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Loops (for loop & while loop)
Loops are used to repeat actions.
- For Loop Used when you know how many times to repeat.
Example:
for i in range(5):
print("Hello")
(prints Hello 5 times)
2. range() Function
range(5) # 0,1,2,3,4
range(1,6) # 1 to 5
range(2,10,2) # even numbers 2 to 8
3. For Loop with List
fruits = ["apple", "banana", "mango"]
for x in fruits:
print(x)
4. Print 1 to 10
for i in range(1, 11):
print(i)
5. While Loop
Repeats until condition becomes false.
i = 1
while i <= 5:
print(i)
i += 1
6. Break Statement
Stops the loop.
for i in range(10):
if i == 5:
break
print(i)
7. Continue Statement
Skips the current loop value.
for i in range(5):
if i == 2:
continue
print(i)
8. Multiplication Table
n = int(input("Enter number: "))
for i in range(1, 11):
print(n, "x", i, "=", n*i)
9. Sum of N Numbers
n = int(input("Enter n: "))
total = 0
for i in range(1, n+1):
total += i
print("Total =", total)
Top comments (0)