Categories
Python

Part 6: INPUT FUNCTION & WHILE LOOP

In this article, we will learn how to collect user responses using input function, to work with the Python’s while loops and to use the while loop with lists and dictionaries

1. input() FUNCTION 101

input() function is used to receive the user’s input. We can store this piece of information inside a variable that can be used later in the program. In the following example, we will write a basic input() function that ask user to enter his/her name and then prints it:

# asking user input and storing it inside a variable
user_name = input("Please enter your name: ")
                  
# printing the message using saved varibale value
print(f"Welcome to the website, {user_name.title()}")
Please enter your name: Walter white
Welcome to the website, Walter White

1.1. Prompt

The input() function takes one argument, the prompt, which is the instruction to user on what sort of information we are collecting. For example, in the above example, Please enter your name: is a prompt.

a. Writing meaningful prompts

  • Each time we use the input() function, we should put some energy in writing clear, concise and meaningful prompt that tells the prospective user what sort of information we are collecting
  • It is also a good practice to add a space at the end of your prompts to separate the prompt from your user’s response.
  • To go one step forward in our mission to write clear code, we can save the prompt inside a variable that can be used later in the prompt() function
prompt = "What is your favorite car? "
fav_car = input(prompt)

print(f"User loves {fav_car.title()}")
What is your favorite car? tesla
User loves Tesla

1.2. Using int() to Accept Numerical Input

When you use the input() function, Python interprets it as a string. Therefore, if we are collecting numerical data, we need to use int() function to convert the string into number

user_age = input("What is your age? ")

if user_age >= 18:
    print("You are eligible to vote")
else:
    print("You can't vote")
What is your age? 21

TypeError: '>=' not supported between instances of 'str' and 'int'

So let convert string into integer first

user_age = input("What is your age? ")
# string to integer
user_age = int(user_age)
if user_age >= 18:
    print(f"You are eligible to vote")
else:
    print("You can't vote")
What is your age? 21
You are eligible to vote

1.3. The Modulo Operator

Modulo operator (%) divides one number by another number and returns the remainder — its only job is to tell the remainder.

Let’s write a simple program that tells whether a number is even or odd:

# asking for user to enter the number
number = input("Enter a number and magically know if it is even or odd: ")
# connverting str to int
number = int(number)
# applying logic to see if number is even
if number % 2 != 0:
    print(f"{number} is an odd number")
else:
    print(f"{number} is an even number")
Enter a number and magically know if it is even or odd: 1001
1001 is an odd number

2. INTRODUCING while LOOPS

We have studied for loops earlier, so it is good starting point to lay down the primary difference between a for and a while loop

The for loop takes in a collection of items and executes a block of code once for each item in the collection. In contrast, the while loop runs as long as a certain condition is True

2.1. while Loop in Action

Let’s print table of 15, using a while loop:

# initial number to start from
current_number = 10
# we only want to print 10*10 = 100 
# so defining the limit
limit = 100

# initiating while loop
# which runs as long as current_number <= 100
while current_number <= limit:
    print(current_number)
    # adding 10 to last value of current_number
    current_number += 10
10
20
30
40
50
60
70
80
90
100

The += operator is shorthand for current_number = current_number + 1.

2.2. Letting User Choose When to Quit

In the above program, we are providing the condition after which while loop will stop. We can give this power to user. For example:

# declaring prompt 
prompt = "Tell me what to print?\nEnter 'quit' when bored\nEnter your message here: "

# we need an empty variable to make it work with while loop
message = ""

# initiating while loop
while message != 'quit':
    message = input(prompt)
    print(message)
    # to avoid the case sensitivity of "quit"
    message = message.lower()
Tell me what to print? Enter 'quit' when bored I like learning Python
I like learning Python
Tell me what to print? Enter 'quit' when bored While loops are easy
While loops are easy
Tell me what to print? Enter 'quit' when bored QUIT
QUIT

2.3. Using a Flag

In the above example, there is only one condition, whose False status will end the while loop. However, we can write code that should run as long as many conditions are True. In such cases, we can define one variable that determines whether or not the entire program is active — this variable is called a flag. It acts like a signal to the program. In this, we only need to check the status of one variable (flag) to decide whether to keep the while loop running or not. Let’s use the same example as above and reproduce result using Flag variable

prompt = "\nTell me what to print?\nEnter 'quit' when bored\nEnter your message here: "
active = True
while active:
    message = input(prompt)
    message = message.lower()
    if message == 'quit':
        active = False
    else:
        print(message)

Tell me what to print?
Enter 'quit' when bored
Enter your message here: I prefer winter over summer
i prefer winter over summer

Tell me what to print?
Enter 'quit' when bored
Enter your message here: quit

2.4. Using break to Exit a Loop

To avoid using any conditional test like active = True or *message = ‘quit’ * — we can use break statement.

prompt = "\nTell me what to print?\nEnter 'quit' when bored\nEnter your message here: "
while True:
    message = input(prompt)
    message = message.lower()
    if message == 'quit':
        break
    else:
        print(message)
Tell me what to print?
Enter 'quit' when bored
Enter your message here: GOT is a good series
got is a good series

Tell me what to print?
Enter 'quit' when bored
Enter your message here: QUIT

We can use the break statement in any of Python’s loops

2.5. Using continue in a Loop

Rather than breaking out of a loop entirely (i.e, using break statement) without executing the rest of the code, we can use the continue statement to return to the beginning of the loop based on the result of a conditional test. Therefore, if the conditional tests declared before continue statement is True, Python will ignore the rest of the loop and return to the start. Otherwise, it will run the remaining code.

In this example, we will use break statement to print all odd number between 0 and 10:

# starting value of number
number = 0

# checking if the current value
# of 'number' is less than 10
while number < 10:
    # incrementing number by one, in each loop
    number += 1
    # checking if the current number is even
    # if the result is True, it will return to top of while loop
    if number % 2 == 0:
        continue
    # if the result is False, it will print the number
    print(number)
1
3
5
7
9

Though, we can achieve the same result without the continue statement

number = 0
while number < 10:
    number += 1
    if number % 2 != 0:
        print(number)

**Avoid infinite loop: ** Every while loop needs a signal that stops it so it won’t continue to run forever. To avoid writing infinite loops, we need to throughly test our code that it does stop when we expect it to be. If you are using the Jupiter notebook and ends up running an infinite loop, press Kernel and then Interrupt

3. USING A while LOOP WITH LISTS AND DICTIONARIES

3.1. Moving Items from One List to Another

In this simple example, we will move all the items from old list to a new list, using a while loop on top of pop and append methods

# defining old_list and new_list
old_list = ['banana','apple','mango']
new_list =[]

# printing the content of old_list and new_list
print("Old list is:")
print(old_list)
print("New list is:")
print(new_list)
print("\n")

# loop runs as long as old_list is not emmpty
while old_list:
	# removing last item from old_list using pop method
	# and saving it inside variable, fruit
    fruit = old_list.pop()
	#printing the confirmation of movement
    print(fruit.title() + " has been moved to inventory")
	# adding item to new list using append method
    new_list.append(fruit)
    
print("\n")
print("Old list is:")
print(old_list)
print("New list is:")
print(new_list)
Old list is:
['banana', 'apple', 'mango']
New list is:
[]


Mango has been moved to inventory
Apple has been moved to inventory
Banana has been moved to inventory


Old list is:
[]
New list is:
['mango', 'apple', 'banana']

3.2. Removing All Instances of Specific Values from a List

We can use remove() method to remove a first occurrence of a value from a list. However, we can use the same remove() method with while loop to remove all the instances of given value from the list.

Suppose we would like to remove all instances of honda from the cars list:

# defining list that we will work on
cars = ['toyota','honda', 'tesla', 'honda', 'bmw', 'buick', 'honda']

# printing the list before we remove 'honda' from it
print("Before removing all instances of honda: ")
print(cars)

# while loop will run as long as 'honda' remain in the list
while 'honda' in cars:
    #removing 'honda' from 'cars'
    cars.remove('honda')

# printing the list after we remove all occurance of 'honda'
print("\nAfter removing all instances of honda: ")
print(cars)
Before removing all instances of honda: 
['toyota', 'honda', 'tesla', 'honda', 'bmw', 'buick', 'honda']

After removing all instances of honda: 
['toyota', 'tesla', 'bmw', 'buick']

3.3. Filling a Dictionary with User Input

We will start with an empty dictionary and then we use input() method and while loop to add the key-value pair to a dictionary

# defining an empty dict
responses ={}

# while loop runs as long as condition dont 'break' it
while True:
    # collecting user input and storing it inside variables
    name = input("What is your name?\n")
    response = input("What is your favorite TV series?\n")
    # adding the key-value pair to dictionary
    responses[name] = response
    # conditional test that will break the loop
    repeat = input("Is anybody left to answer? (yes/no)\n")
    if repeat == 'no':
        break
        
# printing the dictionary key-value pairs
print("... Following answers have been received...\n")
for name, response in responses.items():
    print(f"{name.title()}'s favorite TV show is {response.title()}")
What is your name?
dexter morgan
What is your favorite TV series?
dexter
Is anybody left to answer? (yes/no)
yes
What is your name?
Walter white
What is your favorite TV series?
breaking bad
Is anybody left to answer? (yes/no)
no
... Following answers have been received...

Dexter Morgan's favorite TV show is Dexter
Walter White's favorite TV show is Breaking Bad

Leave a Reply