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 variableuser_name =input("Please enter your name: ")# printing the message using saved varibale valueprint(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 integeruser_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 numbernumber =input("Enter a number and magically know if it is even or odd: ")# connverting str to intnumber =int(number)# applying logic to see if number is evenif 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 fromcurrent_number =10# we only want to print 10*10 = 100 # so defining the limitlimit =100# initiating while loop# which runs as long as current_number <= 100while 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 loopmessage =""# initiating while loopwhile 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 =Truewhile active: message =input(prompt) message = message.lower()if message =='quit': active =Falseelse: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: "whileTrue: message =input(prompt) message = message.lower()if message =='quit':breakelse: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 numbernumber =0# checking if the current value# of 'number' is less than 10while 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 loopif number %2==0:continue# if the result is False, it will print the numberprint(number)
1
3
5
7
9
Though, we can achieve the same result without the continue statement
number =0while number <10: number +=1if 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_listold_list = ['banana','apple','mango']new_list =[]# printing the content of old_list and new_listprint("Old list is:")print(old_list)print("New list is:")print(new_list)print("\n")# loop runs as long as old_list is not emmptywhile 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 movementprint(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 oncars = ['toyota','honda','tesla','honda','bmw','buick','honda']# printing the list before we remove 'honda' from itprint("Before removing all instances of honda: ")print(cars)# while loop will run as long as 'honda' remain in the listwhile'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 dictresponses ={}# while loop runs as long as condition dont 'break' itwhileTrue:# 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 pairsprint("... 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