Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 2, Topic 9
In Progress

Python: Else Statement

Yasin Cakal 20 Oct 2021
Lesson Progress
0% Complete

When a function contains a large number of if statements, the code becomes a little cluttered and clunky. Fortunately, there are additional tools available for creating control flow. else statements enable us to elegantly specify what our code should do if certain conditions are not met. Otherwise else statements are always associated with if statements. Here is an interactive example:

magic_number = input("Guess what is my favorite number?")

if magic_number == "2":
    print("You guessed correct!")
else:
    print("Better luck next time!")

Output 1:

Guess what is my favorite number?
3
Better luck next time!

Output 2:

Guess what is my favorite number?
2
You guessed correct!

This way, we can create if statements that execute different code depending on whether or not certain conditions are met. This avoids the need to write if statements for each possible condition; instead, we can write a blanket else statement for all possible conditions that are not met. Also, notice that the magic_number is equal to "2" as a String variable. This is because the input is automatically converted into a String. So, if magic_number were to equal 2 as an integer, the if statement would never execute, because the String "2" does not equal the integer 2.

%d bloggers like this: