Control flow statements and loops are used in Python to alter the order of program execution and repeat code based on certain conditions. These statements include if
/else
statements for making decisions based on conditions, as well as for
and while
loops for repeating code.
Conditional statements
Conditional statements in Python are used to make decisions based on whether a certain condition is true or false. The basic syntax of a conditional statement is:
if condition:
statement(s)
else:
statement(s)
Here, condition
is a Boolean expression that is evaluated to either True
or False
. If the condition is true, the code block following the if
statement is executed. Otherwise, the code block following the else
statement is executed.
Here’s an example that uses a conditional statement to determine whether a number is even or odd:
num = 7
if num % 2 == 0:
print("The number is even")
else:
print("The number is odd")
In this example, the num
variable is checked for whether it is evenly divisible by 2 using the modulo operator %
. If the result is 0 (i.e., the number is even), the first print statement is executed. Otherwise, the second print statement is executed.
You can also use nested if
statements to make more complex decisions based on multiple conditions. For example:
age = 25
if age < 18:
print("You are a minor")
else:
if age < 65:
print("You are an adult")
else:
print("You are a senior citizen")
In this example, the age variable is checked for whether it falls into one of three categories: minor, adult, or senior citizen. The nested if
statements allow for multiple conditions to be evaluated in a specific order.
Conclusion
Conditional statements are an essential part of programming, and they allow you to create programs that can make decisions based on various conditions. Python’s if
/else
statements provide a straightforward syntax for implementing conditional logic, while nested if
statements allow for more complex decision-making. As you continue to learn Python, you will discover even more ways to use control flow statements and loops to write efficient and effective code.
Practice problem
Pizza Order practice
What is a Leap year? Code solution
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)