Course Content
Conditional Statements in Python
Conditional Statements in Python
Syntax of if-else Statement
The if-else
statement is one of the most commonly used constructs in Python, allowing the program to make decisions based on conditions.
The basic syntax of the if
statement is as follows:
The if
statement checks if a condition is true. If it is, the code inside the block will be executed.
In the case of the else
statement, you don't need to explicitly define the condition, as it automatically covers all scenarios where the if
condition is false:
This diagram illustrates the flow of an if-else
statement. It shows that if a condition is true, the program executes the if code block. If the condition is false, the else code block is executed. The process concludes after one of the blocks is executed.
Example: Checking if a User Met Their Step Goal
steps_taken = 9000 step_goal = 10000 if steps_taken >= step_goal: print("Great job, you've reached your step goal!") else: print("Keep going, you're almost there!")
In this example, the program checks if the number of steps taken by the user is greater than or equal to the step goal. If the condition is met (i.e., the user has reached or exceeded their step goal), the program prints a congratulatory message. If the condition is not met, the else
block will execute, encouraging the user to keep going.
1. What is the purpose of the else
block in an if-else
statement?
2. In the following code, which statement is true?
3. In the following code, which statement is true?
Thanks for your feedback!