Python Basics: Conditionals and Loops
1. Conditional Statements in Python
Conditional statements allow you to execute code based on certain conditions.
Example 1: Simple if statement
x = 10
if x > 5:
print("x is greater than 5")
Example 2: if-else statement
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Example 3: if-elif-else statement
x=7
if x < 5:
print("x is less than 5")
elif x == 7:
print("x is exactly 7")
else:
print("x is greater than 5")
2. Loops in Python
Loops are used to repeat a block of code multiple times.
Example 1: for loop
for i in range(5):
print(i) # prints numbers from 0 to 4
Python Basics: Conditionals and Loops
Example 2: while loop
x=0
while x < 5:
print(x)
x += 1
Example 3: Using break and continue
for i in range(10):
if i == 5:
break # stops the loop when i is 5
print(i)
for i in range(10):
if i % 2 == 0:
continue # skips even numbers
print(i)