Control Statements
In Python, control statements are used to alter the flow of a program based on certain conditions or to control the execution of loops. The primary control statements in Python include:
- if, elif, else Statements:
Used for conditional execution.if
is used for the main condition,elif
(else if) is used for additional conditions, andelse
is used for code that should be executed when none of the conditions are true.if condition1: # Code to be executed if condition1 is True elif condition2: # Code to be executed if condition2 is True else: # Code to be executed if none of the conditions are True
- for Loop:
Used for iterating over a sequence (e.g., list, tuple, string, range).for variable in sequence: # Code to be executed for each iteration
- while Loop:
Used for repeated execution of a block of code as long as a specified condition is true.while condition: # Code to be executed while the condition is True
- break Statement:
Used to exit a loop prematurely, regardless of whether the loop condition is still true.while True: # Code inside the loop if condition: break # Exit the loop if the condition is True
- continue Statement:
Used to skip the rest of the code inside a loop for the current iteration and move to the next iteration.for variable in sequence: # Code before continue if condition: continue # Skip the rest of the code for this iteration and move to the next # Code after continue (not executed if condition is True)
- pass Statement:
Used as a placeholder when a statement is syntactically required but no action is desired.if condition: pass # Placeholder, no action taken else: # Code to be executed
These control statements provide the essential building blocks for creating flexible and dynamic programs in Python. They allow you to make decisions, repeat actions, and control the flow of your program based on conditions.