Skip to content

Learning Python: Day 18

Using int() to accept numerical input

  • with the input() function, Python interprets everything as a string

>>> age = input(“How old are you? “)

How old are you? 21

>>> age

’21’

  • when we ask for the value of age, Python returns the string ’21’
  • you’ll get an error if you use the input as a number

>>> age = input(“How old are you? “)

How old are you? 21

>>> age >= 18

TypeError ‘>=’ not supported between instances of ‘str’ and ‘int’

  • string ’21’ can’t be compared to the numerical value 18
  • can be resolved by using int() function

>>> age = input(“How old are you? “)

How old are you? 21

>>> age = int(age)

>>> age >= 18

True

  • after entering 21, we convert it from a string to a numerical representation
  • this allows Python to run the conditional test to compares ages
  • real-world example testing if someone is tall enough to ride a roller coaster

rollercoaster.py

height = input(“How tall are you, in inches? “)

height = int(height)

if height >= 48:

….print(“\nYou’re tall enough to ride!”)

else:

….print(“\nYou’ll be able to ride when you’re a little older.”}

  • can compare height to 48 because height = int(height)

How tall are you, in inches? 71

You’re tall enough to ride!

  • when you use a numerical input to do calculations and comparisons, convert the input value to a numerical representation first

The modulo operator

  • modulo operator (%) – a useful tool for working with numerical information that divides one number by another number and returns the remainder

>>> 4 % 3

1

>>> 5 % 3

2

>>> 6 % 3

0

>>> 7 % 3

1

  • modulo operator only tells you the remainder, which can be useful for determining if a number is even or odd

even_or_odd.py

number = input(“Enter a number, and I’ll tell you if it’s even or odd: “)

number = int(number)

if number % 2 == 0

….print(f”\nThe number {number} is even.”)

else:

….print(f”\nThe number {number} is odd.”)

  • since even numbers are always divisible by 2, if the module of a number and two is zero, it’s even
  • otherwise, it’s odd

Enter a number, and I’ll tell you if it’s even or odd: 42

The number 42 is even.

Introducing while loops

  • for loop executes a block of code for each item in a collection
  • while loop runs as long as a certain condition is true

The while loop in action

  • you can use a while loop to count up through a series of numbers

counting.py

current_number = 1

while current_number <= 5:

….print(current_number)

….current_number += 1

  • first line assigns value to 1
  • second line sets a while loop to run while value is less than or equal to 5
  • third line inside the loop will print the value current_number
  • fourth line uses the += operator which is shorthand for current_number = current_number + 1

1

2

3

4

5

  • most programs use while loops
  • a game will keep running unless you ask it to quit

Letting the user choose when to quit

  • parrot.py will keep running as long as the user wants by putting most of the program inside a while loop
  • quit value = stop a program running

parrot.py

prompt = “\nTell me something, and I will repeat it back to you:”

prompt += “\nEnter ‘quit’ to end the program. “

message = “”

while message != ‘quit’:

….message = input(prompt)

….print(message)

  • as long as the value of message is not quit, the while loop continues to run
  • first time through the loop, message is an empty string
  • at message = input(prompt), user is prompted to enter their input
  • input is assigned to message and printed
  • condition is reevaluated, as long as quit is not entered, the user is prompted again to enter their input
  • ‘quit’ will cause Python to stop executing the while loop

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello everyone!

Hello everyone!

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello again.

Hello again.

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. quit

quit

  • a simple if test will prevent Python from printing quit

prompt = “\nTell me something, and I will repeat it back to you:”

prompt += “\nEnter ‘quit’ to end the program. “

message = “”

while message != ‘quit’:

….message = input(prompt)

….if message != ‘quit’:

……..print(message)

  • now program does a check before displaying the message

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello everyone!

Hello everyone!

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello again.

Hello again.

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. quit

Using a flag

  • imagine a game that needs to end if any one of the multiple conditions is met
  • trying to test all these conditions in one while statement becomes complicated
  • flag – acts as a signal to the program
  • can write a program to run while the flag is set to True and stop running when any of several events sets the value of the flag to False
  • while statement needs to check only one condition: whether the flag is currently True
  • let’s add a flag called active to parrot.py, which will monitor whether or not the program should continue running

prompt = “\n Tell me something, and I will repeat it back to you:”

prompt += “\nEnter ‘quit’ to end the program. “

active = True

while active:

….message = input(prompt)

if message == ‘quit’:

….active = False

else:

….print(message)

  • can add more tests (such as elif statements) for events that should cause active to become False

Using break to exit a loop

  • break statement – used to exit a while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test
  • it directs the flow of your program; can be used to control which lines of code are executed and which aren’t, the program only executes code that you want it to, when you want it to
  • for example, a program asking users about places they’ve visited
  • can stop the while loop by calling break as soon as the user enters the ‘quit’ value

cities.py

prompt = “\nPlease enter the name of a city you have visited:”

prompt += “\n(Enter ‘quit” when you are finished.) “

while True:

….city = input(prompt)

….if city == ‘quit’:

……..break

….else:

……..print(f”I’d love to go to {city.title()}!”)

  • loop that starts with while True will run forever unless it reaches a break statement

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) New York

I’d love to go to New York!

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) San Francisco

I’d love to go to San Francisco!

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) quit

  • can use the break statement in any of Python’s loops, such as a for loop to quit working through a list or dictionary

Using continue in a loop

  • continue statement – can be used to return to the beginning of the loop, based on the result of a conditional test rather than breaking out of a loop without executing the rest of its code
  • for example, a loop that counts from 1 to 10 but prints only odd numbers

counting.py

current_number = 0

while current_number < 10:

….current_number += 1

….if current_number % 2 == 0:

……..continue

….print(current_number)

  • if modulo is 0, the continue statement tells Python to ignore the rest of the loop and return to the beginning
  • if the current number is odd, the rest of the loop is executed and Python prints the current number

1

3

5

7

9

Avoiding Infinite Loops

  • every while loop needs a way to stop running so it won’t continue running forever

counting.py

x = 1

while x <= 5:

….print(x)

….x += 1

  • if you omit the line x += 1, the loop will run forever

# This loop runs forever!

x = 1

while x <= 5:

….print(x)

  • print a series of 1s

1

1

1

1

–snip–

  • infinite while loops will occur from time to time
  • press CTRL-C or close the terminal window
  • test every while loop to ensure it stops when expected to
  • one part of the program should make the loop’s condition False or cause it to reach a break statement

Using a while loop with lists and dictionaries

  • will need to use lists and dictionaries with our while loops to keep track of many users and pieces of information
  • shouldn’t modify a list inside a for loop because Python will have trouble keeping track of the items in the list
  • use a while loop to modify a list as you work through it

Moving items from one list to another

  • can use a while loop to pull users from the list of unconfirmed users as we verify them and then add them to a separate list of confirmed users

confirmed_users.py

# Start with users that need to be verified,

# and an empty list to hold confirmed users.

unconfirmed_users – [‘alice’, ‘brian’, ‘candace’]

confirmed_users = []

# Verify each user until there are no more unconfirmed users.

# Move each verified user into the list of confirmed users.

while unconfirmed_users:

….current_user = unconfirmed_users.pop()

….print(f”Verifying user: {current_user.title()}”)

….confirmed_users.append(current_user)

# Display all confirmed users.

print(“\nThe following users have been confirmed:”)

for confirmed_user in confirmed_users:

….print(confirmed_user.title())

  • when the list of unconfirmed users is empty, the loop stops and the list of confirmed users is printed

Verifying user: Candace

Verifying user: Brian

Verifying user: Alice

The following users have been confirmed:

Candace

Brian

Alice

Removing all instances of specific values from a list

  • remove() function works to remove one instance of a value
  • to remove all instances of a value, run a while loop until the value is no longer in the list

pets.py

pets = [‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]

print(pets)

while ‘cat’ in pets:

….pets.remove(‘cat’)

print(pets)

[‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]

[‘dog’, ‘dog’, ‘goldfish’, ‘rabbit’]

Filling a dictionary with user input

  • can prompt for as much input as you need in each pass through a while loop

mountain_poll.py

response = {}

# Set a flag to indicate that polling is active.

polling_active = True

while polling_active:

….# Prompt for the person’s name and response.

….name = input(“\nWhat is your name? “)

….response = input (“Which mountain would you like to climb someday? “)

….# Store the response in the dictionary.

responses[name] = response

….# Find out if anyone else is going to take the poll.

repeat = input(“Would you like to let another person respond? (yes/ no) “)

….if repeat == ‘no’

……..polling_active = False

….# Polling is complete. Show the results.

….print(“\n— Pol Results —“)

….for name, response in responses.items():

……..print(f”{name} would like to climb {response}.”)

  • program defines an empty dictionary (responses) and sets a flag (polling_active)
  • Python will run the code in the while loop as long as polling_active is True

What is your name? Eric

Which mountain would you like to climb someday? Denali

Would you like to let another person respond? (yes/ no) yes

What is your name? Lynn

Which mountain would you like to climb someday? Devil’s Thumb

Would you like to let another person respond? (yes/ no) no

— Poll Results —

Eric would like to climb Denali.

Lynn would like to climb Devil’s Thumb.

Summary

  • learned how to use input() to allow users to provide their own information
  • learned to work with both text and numerical input
  • learned how to use while loops to allow programs to run as long as needed
  • saw several ways to control the flow of a while loop by setting an active flag, using the break statement, and using the continue statement
  • learned how to use a while loop to move items between lists and remove all instances of a value from a list
  • learned how while loops can be used with dictionaries

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *