Python - Conditions and Loops
If and Else
In Python, conditional statements are fundamental for controlling the flow of a program based on certain conditions. The primary types of conditional statements include:
Types of Conditional Statements in Python
If Statement
The simplest form of a conditional statement that executes a block of code if a specified condition is true.
Syntax:
if condition: # code to execute if condition is trueExample:
num = 8 if num > 0: print("The number is positive.")This code prints "The number is positive" if
numis greater than zero.
If-Else Statement
This statement provides an alternative code block that executes when the condition in the
ifstatement evaluates to false.Syntax:
if condition: # code to execute if condition is true else: # code to execute if condition is falseExample:
num = 11 if num % 2 == 0: print("The number is even.") else: print("The number is odd.")This code checks if
numis even or odd and prints the corresponding message.
Nested If-Else Statement
This allows one
ifstatement to be placed inside another, enabling complex decision-making.Syntax:
if condition1: if condition2: # code for both conditions being true else: # code for condition1 true, condition2 false else: # code for condition1 falseExample:
num = 3 if num > 0: if num % 2 == 0: print("The number is positive and even.") else: print("The number is positive but odd.") else: print("The number is not positive.")This checks multiple conditions about the variable
num.
If-Elif-Else Ladder
This structure allows checking multiple expressions for truth and executing a block of code as soon as one of the conditions evaluates to true.
Syntax:
if condition1: # code block 1 elif condition2: # code block 2 elif condition3: # code block 3 else: # default code blockExample:
x = 11 if x == 2: print("x is equal to 2") elif x == 3: print("x is equal to 3") elif x == 4: print("x is equal to 4") else: print("x is not equal to 2, 3, or 4")This allows for multiple conditions to be checked sequentially.
Ternary Operator (Conditional Expressions)
A shorthand way to write simple
if-elsestatements in a single line.Syntax:
value_if_true if condition else value_if_falseExample:
result = 'pass' if grade >= 50 else 'fail' print(result)This assigns 'pass' or 'fail' based on the value of
grade.
These various forms of conditional statements allow Python programmers to implement complex logic and control the flow of their programs effectively.
While loop
Python has one primary type of while loop, but it can be used with several control statements to modify its behavior.
Types of while Loops
Basic
whileLoop: This loop executes a block of code as long as a specified condition is true. The condition is checked at the beginning of each iteration.Syntax:
while condition: # Code to executeExample:
i = 1 while i < 6: print(i) i += 1In this example, the loop prints the value of
ias long asiis less than 6.
Control Statements in while Loops
breakStatement: This statement is used to exit the loop prematurely, even if the condition is still true.Example:
i = 1 while i < 6: print(i) if i == 3: break i += 1In this case, the loop will stop when
iequals 3.
continueStatement: This statement skips the rest of the current iteration and proceeds to the next iteration of the loop.Example:
i = 0 while i < 6: i += 1 if i == 3: continue print(i)Here, when
iis 3, theprint(i)statement is skipped, and the loop continues withi = 4.
elseStatement: This block of code is executed when the loop condition becomes false. If the loop is terminated by abreakstatement, theelseblock is not executed.Example:
pythoni = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")The
elseblock will be executed onceiis no longer less than 6.
Other variations
Infinite Loops: These occur when the loop condition never becomes false. They can be useful in certain situations, but it is important to ensure there is a way to exit the loop (e.g., using a
breakstatement).Example:
while True: # Code to execute if some_condition: break
Nested
whileLoops: You can place onewhileloop inside another, allowing for more complex control flow.One-Line
whileLoops: If thewhileloop contains simple statements, it can be written on a single line, with statements separated by semicolons.Example:
n = 5 while n > 0: n -= 1; print(n)
For loop
In Python, the for loop is a versatile control structure used primarily for iterating over sequences such as lists, tuples, sets, dictionaries, and strings. Here are the main types and features of for loops in Python:
Types of for Loops in Python
for Loops in PythonBasic
forLoopThis loop iterates over a sequence (like a list or string) and executes a block of code for each item.
Syntax:
for variable in sequence: # Code to executeExample:
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)This code will print each fruit in the list.
forLoop withrange()The
range()function generates a sequence of numbers, which can be used to iterate a specific number of times.Syntax:
for i in range(start, stop, step): # Code to executeExample:
for i in range(1, 5): print(i)This will print numbers from 1 to 4.
Nested
forLoopsA
forloop can be placed inside anotherforloop, allowing for iteration over multi-dimensional data structures.Syntax:
for outer_variable in outer_sequence: for inner_variable in inner_sequence: # Code to executeExample:
matrix = [[1, 2, 3], [4, 5, 6]] for row in matrix: for item in row: print(item)This code will print each item in the two-dimensional list.
List Comprehensions
A concise way to create lists using a single line of code that includes a
forloop.Syntax:
new_list = [expression for item in iterable]Example:
squares = [x**2 for x in range(10)] print(squares)This creates a list of squares from 0 to 9.
Iterating Over Dictionaries
You can iterate through keys, values, or key-value pairs in a dictionary using a
forloop.Example:
my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(key, value)This will print each key-value pair in the dictionary.
Using
breakandcontinueStatementsThe
breakstatement can be used to exit the loop prematurely, while thecontinuestatement skips the current iteration and moves to the next one.Example with
break:for i in range(10): if i == 5: break print(i)This prints numbers from 0 to 4 and then exits the loop when
iequals 5.Example with
continue:for i in range(5): if i == 2: continue print(i)This prints numbers from 0 to 4 but skips printing the number 2.
Last updated