Input Function And While Loop In Python

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()}")

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

So let convert string into integer first

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:

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:

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:

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

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.

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:

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

**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

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:

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

Last updated