Conditions within Conditions, Nested Conditionals
In programming, sometimes complex logical flows are required depending on different situations.
For example, consider writing a program to provide a discount based on whether someone is 18 years or older and whether that person is a student.
It may be difficult to implement the desired logical flow with just one conditional statement.
In such cases, nested conditional statements can be used to handle the problem.
What is Nesting?
Nesting means "something inside another", and a nested conditional means placing one conditional statement inside another.
Leveraging nested conditionals allows you to add additional checks only when a specific condition is satisfied, thereby creating a more complex and detailed logical flow.
How to Use Nested Conditionals?
Let's write a program to cover the earlier mentioned conditions where:
-
Someone is 18 years or older, and
-
That person is a student.
The program will provide discounts based on these conditions.
age = 20 is_student = True if age >= 18: if is_student: print("Eligible for student discount") else: print("Adult rate applies")
In this code, the first if conditional checks if the age is 18 or older.
If this condition is true, the nested if conditional inside it is executed.
Here it checks if the is_student variable is true; if it is, it prints "Eligible for student discount", otherwise, it prints "Adult rate applies".
Lessons in this chapter · What are Conditional Statements and Loops?
- 1. The Crossroads of Logical Flow, Conditional Statements
- 2. Using Comparison Operators in Conditional Statements
- 3. Conditions within Conditions, Nested Conditionals
- 4. Combining Conditions for More Powerful Decisions
- 5. Filling in Gaps with the pass Keyword
- 6. Fill-in-the-blank quiz
- 7. Using Loops to Execute Code Multiple Times
- 8. Repeating a Specific Number of Times with a for Loop
- 9. Controlling Loops with the while Statement
- 10. Loop within a Loop, Nested Loops
- 11. Using break to Stop Loops
- 12. Skip Iteration with continue
- 13. Multiple-choice quiz
- 14. Coding Quiz - Python Temperature Converter
A nested conditional statement is a combination of two or more conditional statements used together.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help