Python User Input

Python User Input

Python allows for user input. That means we are able to ask the user for input.

The method used to capture user input in Python 3.6+ is the input() function.

(Note: In Python 2.7, the function was called raw_input())


Using the input() Function

The program pauses execution when it encounters the input() function and waits for the user to type some text and press Enter.

Basic Input

username = input("Enter username: ")
print("Username is: " + username)

Input is Always a String

It is critical to remember that the input() function always returns a string (str), even if the user types a number. If you need to perform mathematical calculations on user input, you must cast it using int() or float().

Casting User Input

age = input("Enter your age: ")
// age is currently a string! Let's cast it:
age_num = int(age)
print(f"In 5 years you will be {age_num + 5}.")