Control Flow and Loops
Conditional Statements & Loops
Conditional statements are used to control the flow of execution in a program based on certain conditions. They allow you to make decisions and execute different blocks of code depending on whether a condition is true or false. This topic covers the basic usage of if-else statements and nested if-else statements in Python.
Examples
Example 1: if-else Statement
Output:
Example 2: Nested if-else Statement
Output:
Example 3: Nested if-else Statement with Multiple Conditions
Output:
Exercises
Exercise 1:
Question: What is the purpose of a conditional statement?
Answer: The purpose of a conditional statement is to make decisions and execute different blocks of code based on certain conditions.
Exercise 2:
Question: How do you write an if-else statement in Python?
Answer: An if-else statement in Python is written using the if keyword, followed by the condition to be checked, a colon, and an indented block of code for the "if" branch. The "else" branch is denoted by the else keyword, followed by a colon and another indented block of code.
Exercise 3:
Question: What is a nested if-else statement?
Answer: A nested if-else statement is an if-else statement that is nested inside another if or else block. It allows for multiple levels of conditions and decisions based on those conditions.
Exercise 4:
Question: How do you write a nested if-else statement in Python?
Answer: A nested if-else statement in Python is written by indenting an if-else statement inside another if or else block.
Exercise 5: Question: What is the output of the following code snippet?
Answer: The output of the code snippet will be "x is not greater than 7".
Last updated