Conditional Statements
The if statement executes a block of code if a specified condition evaluates to true.
if 5 > 1:
print('Condition holds true')
Use elif (else if) to specify a new conidtion to test if the previous condition was false.
user_name = input('Enter your username: ')
years = int(input('Enter your age: '))
if user_name == 'Alice':
print("Username recognized.")
elif years == 25:
print("Age matches the record.")
The else keyword catches anything which isn't caught by the preceding conditions.
final_score = int(input("Enter your score:"))
if final_score > 100:
print("Score exceeds maximum limit.")
elif final_score >= 90:
print("Grade: A")
elif final_score >= 80:
print("Grade: B")
elif final_score >= 60:
print("Grade: C")
elif final_score >= 40:
print("Grade: D")
else:
print("Grade: F - Needs improvement")
While Loops
The while loop executes a set of statements as long as a condition is true.
counter = 1
while counter <= 100:
print(counter)
counter += 1
Alternatively, you can use a sentinel variable to control the loop execution.
num = 1
active = True
while active:
num += 1
print(num)
if num >= 100:
active = False
The break statement terminates the loop completely, and execution moves to the first statement after the loop body.
print(111)
while True:
print(222)
print(333)
break
print(444)
print(555)
index = 1
while True:
index += 1
print(index)
if index >= 99:
break
The continue statement skips the current iteration and continues with the next one, re-evaluating the loop condition.
i = 0
while i <= 9:
i += 1
if i == 7:
continue
print(i)
Python also supports an else block with while loops, which executes if the loop condition becomes false (unless the loop is termianted by break).
x = 0
while x < 5:
print(x)
x += 1
else:
print("Loop finished naturally.")