User input allows you to gather data from users, making your programs interactive and dynamic.
Getting User Input
You can use the input()
function to get user input. The input()
function reads a line from input, converts it to a string, and returns it.
Example:
The following code prompts the user to enter their name and then prints a greeting:
name = input("Enter your name: ") print("Hello, " + name + "!")
Converting Input
By default, the input()
function returns the input as a string. If you need the input in another type, you must convert it.
Converting to Integer:
The following code prompts the user to enter their age and converts the input to an integer:
age = int(input("Enter your age: ")) print("You are " + str(age) + " years old.")
Converting to Float:
The following code prompts the user to enter their height and converts the input to a float:
height = float(input("Enter your height in meters: ")) print("Your height is " + str(height) + " meters.")
Error Handling
It is good practice to handle potential errors when converting user input. This can be done using try
and except
blocks to catch exceptions like ValueError
.
Example:
The following code prompts the user to enter their age and handles non-numeric input:
try: age = int(input("Enter your age: ")) print("You are " + str(age) + " years old.") except ValueError: print("Invalid input! Please enter a numeric value.")