0% found this document useful (0 votes)
49 views6 pages

PYCS 05 - Else and Elif - Colaboratory

This document discusses Python's else and elif statements. It provides examples of using else after an if statement to execute code if the if condition is False. Elif can be used to evaluate multiple conditions and execute the block for the first True condition. The document also demonstrates using nested if, else, and elif statements to perform complex decision making and control program flow based on different inputs.

Uploaded by

godspower bruno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views6 pages

PYCS 05 - Else and Elif - Colaboratory

This document discusses Python's else and elif statements. It provides examples of using else after an if statement to execute code if the if condition is False. Elif can be used to evaluate multiple conditions and execute the block for the first True condition. The document also demonstrates using nested if, else, and elif statements to perform complex decision making and control program flow based on different inputs.

Uploaded by

godspower bruno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory

A Python Introduction for New (and not-so-new)


Programmers
Part 05: Else and Elif

This Python Notebook is part of a sequence authored by Timothy R James - feel free to modify, copy,
share, or use for your own purposes.

In this Notebook file, we will add new capabilities to our decision making in code - the else
statement and the elif statement.

Else Statements

In the previous lesson, we saw this code:

num = int(input('Enter a number.'))

if num % 2 == 0:

    print('That number is even.')

if num % 2 != 0:

    print('That number is odd.')

This can be prone to errors - what if you accidentally enter numbers that don't match? What if later
you change one of these, but forget to change the other? As programmers, we usually want to
avoid problems like this.

A better way to perform the either / or above is to use the else statement. We use else along with
if - you just make sure your indentation lines up. If the if condition is True , then the block
following the if executes; if the condition is False , then the block following the else executes.

If we rewrite the last example to use else instead of two if statements, it's simpler and easier to
follow.

num = int(input('Enter a number.'))

https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 1/6
1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory

if num % 2 == 0:
    print('That number is even.')
else:
    print('That number is odd.')

It's pretty common to do one action when something is True and another when something is
False .

food = input('Guess my favorite food.')

if food == 'pizza':
    print("That's right!")
else:
    print("That's wrong.")

We can also embed if and else statements in other statements, and combine them to perform
more and more complex operations.

num = int(input('Enter a number.'))

if num == 0:
    print('That number is zero; it is not negative or positive.')
else:
    if num > 0:
        print('That number is positive.')
    else:
        print('That number is negative.')

We can create more and more complex decision making by using multiple if and else
statements.

value = input('What is your age?')
age = int(value)

if age < 21:
    print('In the United States, you can\'t by alcohol.')
    if age < 16:
        print('In the United States, you can\'t drive a car.')
    else:
        print('You can drive a car in the United States.')
else:
    if age > 65:
        print('Congratulations! You can get senior discounts!')
    else:
        if age > 23:
https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 2/6
1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory
            print('You were born in the last century.')

Note that we could rewrite the code above by using multiple conditions, like this.

value = input('What is your age?')
age = int(value)

if age < 21:
    print('In the United States, you can\'t by alcohol.')

if age < 16:
    print('In the United States, you can\'t drive a car.')
else:
    print('You can drive a car in the United States.')

if age > 65:
    print('Congratulations! You can get senior discounts!')

if age > 23:
    print('You were born in the last century.')

There are often many ways to solve problems. Sometimes you have to use your best judgment; you
want your code to be readable, but you also probably want to write less code.

Elif Statements

We could write a simple guessing game, like this.

num = int(input('Guess a number between 1 and 4.'))

if num == 2:
    print('You guessed it!')
else:
    print('That is not correct.')

However, we might want to provide the user more information based on each input. If we need to
evaluate many possible conditions, Python has a keyword elif that can be used for continued
evaluation of multiple conditions.

num = int(input('Guess a number between 1 and 4.'))

if num == 1:
    print('1 is not the answer, but that is close.')
https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 3/6
1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory

elif num == 2:
    print('You guessed it!')
elif num == 3:
    print("It wasn't 3, but that is close.")
elif num == 4:
    print('4 is not correct.')

Many languages have a switch statement to allow you to execute code based on many different
matching conditions, but Python doesn't have this. However, you can use elif to provide similar
functionality - to choose one of many options. Note that you can use else along with elif if you
want to execute statements if no conditions are met.

grade = float(input("What was the score?"))

print("The grade is:")
if grade > 91:
    print("A")
elif grade > 90:
    print("A-")
elif grade > 88:
    print("B+")
elif grade > 81:
    print("B")
elif grade > 80:
    print("B-")
elif grade > 78:
    print("C+")
elif grade > 71:
    print("C")
elif grade > 70:
    print("C-")
elif grade > 68:
    print("D+")
elif grade > 61:
    print("D")
elif grade > 60:
    print("D-")
else:
    print("F")

When to use or vs elif ?


In the food example, if your favorite food is both tacos and pizza, how would you solve that
problem? Would you use or or elif ?

https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 4/6
1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory

It ultimately depends on what you want to do in response. If you want to simply say, "Correct!" for
both answers, you could do this:
food = input('Guess my favorite food.')
if food == 'pizza' or food == 'tacos':
   print("That's right!")
else:
   print("That's wrong.")

If you want different outputs, though, this is where you would use an elif.

food = input('Guess my favorite food.')
if food == 'pizza':
   print("Pizza is the best!")
elif food == 'tacos':
   print('I really like tacos.')
else:
   print("That's not it.")

What if we wanted to write a program that finds the maximum of 3 numbers?

We can try this below.

1. We'll get the user to enter 3 different numbers.


2. We'll assume the greatest is the first number (don't worry, we'll check the rest of them).
3. We'll check if the second number is bigger than the first and third and first using elif .
4. We'll check if the third number is bigger than the second and first using elif .

num1 = int(input('Enter one number.'))
num2 = int(input('Enter another number.'))
num3 = int(input('Enter one more number.'))

greatest = num1

if num2 >= num3 and num2 >= num1:
    greatest = num2
elif num3 >= num2 and num3 >= num1:
    greatest = num3

print('%s is the greatest of those three numbers.' % greatest)

Try It!

https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 5/6
1/10/23, 1:16 PM PYCS 05 - Else and Elif - Colaboratory

Write code below that will ask the user what their favorite animal is. If the user enters dog or dogs
then print, "That's my favorite too!" If the user enters frog or frogs then print, "Hop hop!" If they
enter anything else, print, "That's a good one."
pet = input('What is your favorite animal?')

Can you modify the example above to ask the user for FOUR numbers and tell the user which one is
the SMALLEST?

num1 = int(input('Enter one number.'))
num2 = int(input('Enter another number.'))
num3 = int(input('Enter one more number.'))
num4 = int(input('Enter one last number.'))

Colab paid products


-
Cancel contracts here

Could not connect to the reCAPTCHA service. Please check your internet connection and reload to get a reCAPTCHA
challenge.

https://colab.research.google.com/drive/1OE8-ZUSL0iImUQbUa1w8lWLI3uBDm6uX?usp=sharing#scrollTo=Ev-qyTMj2wtM&printMode=true 6/6

You might also like