Using the input
Function to Receive User Input
The input()
function is used to receive input from the user, and it always returns the input data as a string
.
Using the input() Function
# Receive input from the user
user_input = input("Please enter your name: ")
# Output the entered data
print(f"Welcome, {user_input}!")
Converting the Data Type of Input
Since the data from input()
is returned as a string, you may need to convert it to another data type for arithmetic operations or logical comparisons.
For instance, if you want to receive a number from the user for mathematical operations, the input needs to be converted to an integer
or float
.
In Python, you can convert a given value to an integer using the int()
function and to a float using the float()
function.
The following example demonstrates using the int()
function to convert the age entered by the user into an integer.
Data Type Conversion of Input
age_input = input("Please enter your age: ")
age = int(age_input) # Convert string to integer using int()
print(f"You are {age} years old.")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.