How input() function Works in Python?

How input() function Works in Python?

Did you know that Python’s input() function prompts the user to enter text while the program is running?

When you use input(), the program will pause and wait for the user to provide some input. Once the user has entered the text, Python will store it in a variable, making it easy for you to use it in your code.

This function can be useful for creating interactive programs that need user input.

Let me give you an example. Consider the following program:

color = input("Please enter your favorite color: ")
print(color)

The above program prompts the user to enter their favorite color. Once the user enters the text and presses Enter, the input will store in the variable color. The program then uses the print() function to display the color the user entered and show it back to them. The result of the above program will be:

Please enter your favorite color: Blue
Blue

Write Clear and Effective Prompts for User Input

When using the input() function, it’s important to provide a clear prompt that tells the user exactly what kind of information you are expecting. To make it easy for the user to enter their input, include a space after the prompt’s colon.

In some cases, you may need to write a prompt that is longer than one line. To do this, you can store the prompt in a variable and concatenate the more lines using the += operator.

Here’s an example of a multi-line prompt:

prompt = "I seem to have forgotten my telepathic abilities today."
prompt += "\nCan you tell me your name? "
name = input(prompt)
print("\nHello, " + name + "!")

In this example, a multi-line prompt is constructed using two lines of code. The first line creates a string that provides context for why the user is being asked to provide their name. The second line adds a new line character (“\n“) and includes the actual question for the user.

By concatenating the strings, the prompt is displayed over two lines, which makes it easy for the user to read and enter their input. Once the user provides their name, the program greets them by name using the input stored in the name variable.

I seem to have forgotten my telepathic abilities today.
Can you tell me your name? Vilash

Hello, Vilash!

Use the int() Function to Accept Numerical Input

When you use the input() function in Python, it treats all user input as a string data type. For instance, take a look at this interpreter session that prompts the user to enter their birth year:

>>> year = input("What is birth year? ")
What is birth year? 1990

>>> year
'1990'

Suppose the user enters the number 1990 as their birth year. But when we check the value of the variable year, it returns ‘1990’ which is the string representation of the input. It is because Python treats all user input as a string by default.

Example: Find age by birth year

Let’s say you want to calculate your age based on your birth year and the current year. You can achieve this by subtracting your birth year from the current year. Here’s an example code that does this:

>>> age = 2023 - year

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'int' and 'str'

But, when you attempt to do this calculation, you may encounter a TypeError with a message saying ‘unsupported operand type(s) for -: ‘int’ and ‘str”.

To resolve this issue, we can use the int() function in Python, which converts the input into a numerical value. It converts a string representation of a number to an integer value. Here’s an example of how to use the int() function:

>>> year = input("What is birth year? ")
What is birth year? 1990

>> year = int(year)
>>> year
1990

In this example, when we enter 1990 at the prompt, Python interprets the number as a string. But the value is then converted to a numerical representation by int(). To verify if the value is an integer, you can check the variable type by type() function as shown in the below example.

>>> type(year)
<class 'int'>

The result shows <class, ‘int’> which means it is an integer type.

Now you can find your age by the above modified code:

>>> year = input("What is birth year? ")
What is birth year? 1990

>>> age = 2023 – year
24

Example: Check if the user is a teenager or not

Consider the following scenario where you need to check if the user is a teenager or not, based on their age. Here’s an example program that uses the int() function:

age = input("Please enter your age: ")
age = int(age)

if age >= 13 and age <= 19:
    print("You are a teenager!")
else:
    print("You are not a teenager.")

First, it will prompt your age. The input is then converted to an integer using the int() function. Then, the program checks whether the user’s age falls between 13 and 19. If so, the program prints “You are a teenager!”. Otherwise, it prints “You are not a teenager.”

It is important to convert the input value to a numerical type before calculations or comparisons with numerical input.

Accepting Multiple Inputs with a While Loop

You can use a while loop to ask the user for input until a certain condition is met. This is useful when you need to accept more than one input from the user.

Let’s say you want to create a program that asks the user for a list of names and then displays the list back to the user. You don’t know how many names the user wants to enter, so you need to keep asking for input until they say to stop.

Here’s an example of how you could use a while loop to achieve this:

# initialize an empty list to store the names
names = []

# keep asking for input until the user is done
while True:
    # prompt the user to enter a name
    name = input("Enter a name (or 'quit' to finish): ")
    
    # check if the user is done
    if name == 'quit':
        break
    else:
        # add the name to the list
        names.append(name)

# display the list of names to the user
print("The names you entered are:")
for name in names:
    print(name)

The code above will produce the following output:

Enter a name (or 'quit' to finish): vilash
Enter a name (or 'quit' to finish): priya
Enter a name (or 'quit' to finish): kunal
Enter a name (or 'quit' to finish): ram
Enter a name (or 'quit' to finish): quit
The names you entered are:
vilash
priya
kunal
ram

Conclusion

Accepting user input is an important aspect of programming that allows us to solve an end user’s problem. By using the input() function, we can prompt the user to provide the necessary information for our program to work with. We have also learned how to keep programs running using Python’s while loop, allowing users to input as much information as needed. By applying these concepts, we can create more effective programs that are tailored to meet the needs of our users.

Leave a Comment

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

Scroll to Top