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 true
Example:
num =8if num >0:print("The number is positive.")
This code prints "The number is positive" if num is greater than zero.
If-Else Statement
This statement provides an alternative code block that executes when the condition in the if statement evaluates to false.
Syntax:
if condition:# code to execute if condition is trueelse:# code to execute if condition is false
Example:
num =11if num %2==0:print("The number is even.")else:print("The number is odd.")
This code checks if num is even or odd and prints the corresponding message.
Nested If-Else Statement
This allows one if statement to be placed inside another, enabling complex decision-making.
Syntax:
if condition1:if condition2:# code for both conditions being trueelse:# code for condition1 true, condition2 falseelse:# code for condition1 false
Example:
num =3if 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.
x =11if 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-else statements in a single line.
Syntax:
value_if_true if condition else value_if_false
Example:
result ='pass'if grade >=50else'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 while Loop: 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:
Example:
In this example, the loop prints the value of i as long as i is less than 6.
Control Statements in while Loops
break Statement: This statement is used to exit the loop prematurely, even if the condition is still true.
Example:
In this case, the loop will stop when i equals 3.
continue Statement: This statement skips the rest of the current iteration and proceeds to the next iteration of the loop.
Example:
Here, when i is 3, the print(i) statement is skipped, and the loop continues with i = 4.
else Statement: This block of code is executed when the loop condition becomes false. If the loop is terminated by a break statement, the else block is not executed.
Example:
The else block will be executed once i is 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 break statement).
Example:
Nested while Loops: You can place one while loop inside another, allowing for more complex control flow.
One-Line while Loops: If the while loop contains simple statements, it can be written on a single line, with statements separated by semicolons.
Example:
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
Basic for Loop
This loop iterates over a sequence (like a list or string) and executes a block of code for each item.
Syntax:
Example:
This code will print each fruit in the list.
for Loop with range()
The range() function generates a sequence of numbers, which can be used to iterate a specific number of times.
Syntax:
Example:
This will print numbers from 1 to 4.
Nested for Loops
A for loop can be placed inside another for loop, allowing for iteration over multi-dimensional data structures.
Syntax:
Example:
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 for loop.
Syntax:
Example:
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 for loop.
Example:
This will print each key-value pair in the dictionary.
Using break and continue Statements
The break statement can be used to exit the loop prematurely, while the continue statement skips the current iteration and moves to the next one.
Example with break:
This prints numbers from 0 to 4 and then exits the loop when i equals 5.
Example with continue:
This prints numbers from 0 to 4 but skips printing the number 2.