Control Flow
Control flow in Python allows you to execute specific blocks of code based on certain conditions. This tutorial provides an overview of the control flow structures in Python, including if-else statements, loops, and branching.
If-Else Statements
The if-else statement is used to make decisions in Python. It allows you to execute different blocks of code depending on whether a given condition is true or false.
if condition:
# Code block executed if the condition is true
statement1
statement2
else:
# Code block executed if the condition is false
statement3
statement4
Elif Statement
The elif statement is used to add multiple conditions to
the if-else block.
if condition1: # Code block executed if condition1 is true
statement1
elif condition2: # Code block executed if condition1 is false and condition2 is true
statement2
else: # Code block executed if all conditions are false
statement3
Loops
Loops in Python allow you to execute a block of code repeatedly based on a given condition.
While Loop
The while loop continues to execute as long as the specified condition remains true.
while condition:
# Code block executed as long as the condition is true
statement1
statement2
For Loop
The for loop iterates over a sequence (e.g., list, tuple, string) and executes the code block for each element in the sequence.
for item in sequence:
# Code block executed for each item in the sequence
statement1
statement2
Break and Continue
In loops, you can use the break statement to exit the loop prematurely and the continue statement to skip the current iteration and proceed to the next one.
for item in sequence:
if condition:
# Code block executed when the condition is true
break # Exit the loop immediately
else:
# Code block executed for other iterations
continue # Skip this iteration and proceed to the next one
Branching with Ternary Operator
Python supports a concise way of writing if-else statements in a single line using the ternary operator. This pattern is used in other programming languages like JavaScript and C.
variable = value_if_true if condition else value_if_false