To ask for user input in Python, use the built-in input()
function.
For example:
name = input("Enter your name: ") print(f"Hello {name}")
Output example:
Enter your name: Jack Hello Jack
In addition to asking for simple string input like this, you also want to learn how to:
- Ask for multiple inputs in one go.
- Ask for input again until valid input is given.
To learn more about these, keep on reading.
How to Ask for Multiple Inputs in Python
To ask for multiple inputs in Python, use the input().split()
method.
Ask for Multiple Inputs Separated by Blank Spaces
For example, let’s ask a user the first name and the last name and store them on different variables:
fname, lname = input("Enter your full name: ").split() print(f"Hello {fname} {lname}")
Example output:
Enter your full name: Jack Jones Hello Jack Jones
This works because the split()
method splits the input based on a blank space by default.
Ask for Multiple Inputs Separated by Custom Character
To split the input based on some other character, specify the separator character in the split()
call.
For example, let’s ask a user for a list of three numbers:
a, b, c = input("Enter three comma-separated values: ").split(",") print(f"The values were {a}, {b}, and {c}")
Example output:
Enter three comma-separated values: 1,2,3 The values were 1, 2, and 3
How to Ask for Input Again in Python
To ask for user input until they give valid input, use an endless while loop with some error handling.
For example, let’s create a program that asks the user’s age.
If the user does not enter an integer, we print an error message and ask again. This process continues until the user inputs an integer.
Here is the code:
while True: try: age = int(input("Enter your age: ")) except ValueError: print("This is not a valid age.") continue else: break print(f"You are {age} years old")
Output example:
Enter your age: test This is not a valid age. Enter your age: 4.2 This is not a valid age. Enter your age: 30 You are 30 years old
This code works such that:
- It starts an endless loop with
while True
. - It then tries to convert user input to an integer in the
try
block. - If it fails (due to a value error), it prints an error message in the
except
block and continues the endless while loop. - If it succeeds, the
else
block is executed which breaks the loop and continues to the next statements.
If you are new to Python, this may not ring a bell. If you want to learn more about error handling in Python, check this article.
Conclusion
Today you learned how to ask for user input in Python using the input() function.
In addition to asking for a single input, you now know how to
- Ask for multiple inputs.
- Ask for input until valid input is given.
Thanks for reading.