User input and while loops

Python basics

Python
Basics
Author

Kunal Khurana

Published

October 6, 2023

Learning outcomes

  1. how the input() function works
  2. while loops (text and numerical inputs)
  3. using while loop with lists and dictionaries
  4. control the flow of a while loop by setting an active flag, using the break statement, and using the continue statement
  5. using a while loop to move items from one list to another and to remove all instances of a value from a list.

input() function

message = input("Please enter your full name: ")
print(message)
print(f"\nHello, {message}!")

if/else + input

age = input("May i know your age, please?")
age = int(age)

if age <=12 or age >= 65 :
    print("\nYou can enter the zoo for free")

else:
    print("\nYou'll have to pay 45CAD for a 90 minutes visit")
    
May i know your age, please?6556

You can enter the zoo for free

Modulo operator

provides the remainder after division

4%3
1
5 % 2
1

while Loops

# counting (1 to 5)
current_number = 1
while current_number <=5:
    print(current_number)
    current_number += 1
    
1
2
3
4
5
# infinite loop which stops with quit message
prompt = "\nTell me something and I will repeat it back to you:"
prompt += "\n Enter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)

Tell me something and I will repeat it back to you:
 Enter 'quit' to end the program. I'm doing great!
I'm doing great!

Tell me something and I will repeat it back to you:
 Enter 'quit' to end the program. keep on playing with this game until you get tired
keep on playing with this game until you get tired

Tell me something and I will repeat it back to you:
 Enter 'quit' to end the program. quit
quit

While loops + Flag

  • description- when flag conditions are true, the program continues to run. Else, it stops.
  • benefits over while loop- can be used to execute several conditions. Contrary to while loop, which uses only one condition
prompt = "\n Tell me something, and I will repeat it back to you:"
prompt += "\n Enter 'quit' to end the program. "

active = True
while active :
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

 Tell me something, and I will repeat it back to you:
 Enter 'quit' to end the program. I'm doing good today!
I'm doing good today!

 Tell me something, and I will repeat it back to you:
 Enter 'quit' to end the program. quit
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 like to visit {city.title()}!")

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Dubai
I'd like to visit this Dubai!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Thailand
I'd like to visit this Thailand!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Switzerland
I'd like to visit this Switzerland!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Mexico
I'd like to visit this Mexico!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Thailand
I'd like to visit this Thailand!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Pataya
I'd like to visit this Pataya!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Cuba
I'd like to visit this Cuba!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)Vancouver
I'd like to visit this Vancouver!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)quit

using continue in a loop

# print list of odd numbers upto 10
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2== 0:
        continue
    print(current_number)
1
3
5
7
9
# print list of even numbers upto 20
current_even_n = 0
while current_even_n < 21:      #upto 20 gets printed
    current_even_n += 1
    if current_even_n % 2 == 1:
        continue
    print(current_even_n)
2
4
6
8
10
12
14
16
18
20
number = 1

while number <= 10:
    square = number * number
    print(f"The square of {number} is {square}")
    number += 1
x = 1

while x <= 10:
    square = x * x
    print(f"The square of {x} is {square}")
    x += 1  # prevents infinite loop

    
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100

Using while loop with lists and dictionaries

unconfirmed_users = ['raghav', 'britany', 'solance', 'aisha']
confirmed_users = []

while unconfirmed_users :
    current_user = unconfirmed_users.pop()
    
    #moving
    
    print(f"Verifying user: {current_user.title()}")
    confirmed_users.append(current_user)
    
    #displaying
    
    print("\nThe following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())
Verifying user: Aisha

The following users have been confirmed:
Aisha
Verifying user: Solance

The following users have been confirmed:
Aisha
Solance
Verifying user: Britany

The following users have been confirmed:
Aisha
Solance
Britany
Verifying user: Raghav

The following users have been confirmed:
Aisha
Solance
Britany
Raghav

Removing specific values from the list


pets = ['dog', 'cat', 'cheetah', 'beer', 'rabbit', 'lion']
print(pets)

while 'cat' in pets:
    pets.remove('cat')    #remove method

print(pets)
['dog', 'cat', 'cheetah', 'beer', 'rabbit', 'lion']
['dog', 'cheetah', 'beer', 'rabbit', 'lion']

Filling a dictionary with user input

responses = {}         #initializing empty dictionary


polling_active = True  # setting flag indicator to True

while polling_active:
    name = input("\nWhat is your name?")
    response = input("Which mountain would you like to climb someday?")
    
    #storing the response in a dictionary
    responses[name] = response  #where name is the key, and response is the value
    
    #finding out if we want to store more keys and variables in responses
    repeat = input("Would you like to let another person respond? (yes/no)")
    if repeat == 'no':
        polling_active = False
        
#polling complete; show the results
print("\n_______Poll Results_____________")
for name,response in responses.items():              #for loop iterates for key, value pairs in responses dictionary
    print(f"{name.title()} would like to climb {response.title()}.")

What is your name?sunita
Which mountain would you like to climb someday?valdavid
Would you like to let another person respond? (yes/no)no

_______Poll Results_____________
Sunita would like to climb Valdavid.
# callling the dictionary
print(responses)
{'sunita': 'valdavid'}

Writing the same code with break loop

  • new dictionary is responses_new
responses_new = {}         #initializing empty dictionary




while True:
    name = input("\nWhat is your name?")
    response = input("Which mountain would you like to climb someday?")
    
    #storing the response in a dictionary
    responses_new[name] = response  #where name is the key, and response is the value
    
    #finding out if we want to store more keys and variables in responses
    repeat = input("Would you like to let another person respond? (yes/no)")
    if repeat.lower() != 'yes':
        break  #exits the loop if response in not 'yes'
        
#polling complete; show the results
print("\n_______Poll Results_____________")
for name,response in responses_new.items():              #for loop iterates for key, value pairs in responses dictionary
    print(f"{name.title()} would like to climb {response.title()}.")

What is your name?kk
Which mountain would you like to climb someday?tatata
Would you like to let another person respond? (yes/no)yes

What is your name?paula
Which mountain would you like to climb someday?tatal
Would you like to let another person respond? (yes/no)no

_______Poll Results_____________
Kk would like to climb Tatata.
Paula would like to climb Tatal.
print(responses_new)
{'kunal': 'kanchunjunga', 'sushil': 'peu importe'}
# Dream vacation

vacation = {}

while True:
    key = input("\nWhat is your name?")
    value = input("If I ask you to visit one place in the world, where would you go?")
    
    vacation[key]= value
    
    repeat = input("Next person in line, if there is one? ('yes/no')")
    if repeat.lower() != 'yes':
        break

#polling complete, show results
print("______Poll_results")
for key,value in vacation.items():
    print(f"{key.title()} would like to go {value.title()}.")

What is your name?kunal
If I ask you to visit one place in the world, where would you go?dubai
Next person in line, if there is one? ('yes/no')yes

What is your name?martina
If I ask you to visit one place in the world, where would you go?new brunswick
Next person in line, if there is one? ('yes/no')yes

What is your name?kathy
If I ask you to visit one place in the world, where would you go?québec city
Next person in line, if there is one? ('yes/no')no
______Poll_results
Kunal would like to go Dubai.
Martina would like to go New Brunswick.
Kathy would like to go Québec City.