0

23.1 Beginner Python - Elif Statements

My newbie question is: Else/If statements require indentation to separate blocks of code, how come Elifs do not require nested indentations??

9th Nov 2021, 5:32 PM
Stephen Norton
Stephen Norton - avatar
5 Antworten
+ 1
elif requires the same indentation as if or else. Can you give an example to illustrateyour question?
9th Nov 2021, 5:40 PM
Lisa
Lisa - avatar
+ 1
Instead of using nested if-else statements, you can use if-elif-statements. In the later case, elif is on the same indentation level as if – elif simplifies the code and makes it more readable.
9th Nov 2021, 6:33 PM
Lisa
Lisa - avatar
0
This is from the lesson: num = 3 if num == 1: print("One") else: if num == 2: print("Two") else: if num == 3: print("Three") else: print("Something else") This is also from the lesson, same thing except using elif: num = 3 if num == 1: print("One") elif num == 2: print("Two") elif num == 3: print("Three") else: print("Something else")
9th Nov 2021, 5:49 PM
Stephen Norton
Stephen Norton - avatar
0
Thank you much Lisa. If Python wasn't already readable!
9th Nov 2021, 6:44 PM
Stephen Norton
Stephen Norton - avatar
0
elif Statements Fill in the blanks to create valid code that checks the sign of the num variable: num = 42 (num < 0): print(“Negative”) (num > 0): print(“Positive”) else i wamt answer
22nd Nov 2022, 2:54 AM
Samiksha Shirwale