In Python, you receive user input using the built-in input()
function. This function pauses the program and waits for the user to type something and press Enter. The input is then captured as a string.
Using the input()
Function
The core method for receiving input in Python is using input()
. Here's how it works:
message = input("Enter a message: ")
print("You entered:", message)
- The
input()
function displays the prompt "Enter a message:" to the user, requesting input. - The user types something and presses Enter.
- The text the user entered is then stored in the
message
variable as a string.
Handling Different Input Types
Why String Conversions Are Necessary
Because the input()
function always returns a string, you often need to convert the input to other data types, such as integers or floats, when you need to perform calculations. The reference states that inputs are automatically saved as strings, therefore you have to convert them before performing mathematical operations.
Converting to Integers
To convert a user input to an integer, you can use the int()
function:
age_str = input("Enter your age: ")
age = int(age_str)
print("Your age is:", age)
Converting to Floats
To convert to a floating-point number, use the float()
function:
price_str = input("Enter the price: ")
price = float(price_str)
print("The price is:", price)
Examples
Let's examine some examples to solidify our understanding of receiving input.
-
Simple Text Input:
name = input("Please enter your name: ") print("Hello, " + name + "!")
-
Integer Input for Calculation:
num1_str = input("Enter the first number: ") num2_str = input("Enter the second number: ") num1 = int(num1_str) num2 = int(num2_str) sum_result = num1 + num2 print("The sum is:", sum_result)
-
Floating Point Input:
radius_str = input("Enter the radius of the circle: ") radius = float(radius_str) area = 3.14159 * radius * radius print("The area is:", area)
Key Takeaways
- The
input()
function is how you get user input in Python. - The
input()
function returns user input as a string. - You'll often need to convert this string to an integer (
int()
) or a float (float()
) for mathematical operations. - Proper error handling using try/except blocks is important when converting user input, but is beyond the scope of this question.