In Python, you can use the input()
function to get input from the user via the keyboard.
Basic Usage:
Python
user_input = input("Enter your name: ")
print("Hello,", user_input)
- This code will:
- Display the message "Enter your name: " on the console.
- Wait for the user to type their name and press Enter.
- Store the entered name in the
user_input
variable. - Print a greeting message using the entered name.
Getting Numerical Input:
- By default,
input()
returns a string. To get numerical input, you need to convert the string to the desired data type:
Python
age = int(input("Enter your age: "))
print("You are", age, "years old.")
- This code:
- Prompts the user to enter their age.
- Uses
int()
to convert the user's input (which is a string) into an integer.
Example with Error Handling:
Python
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Invalid input. Please enter a number.")
- This code includes a
try-except
block to handle potential errors. - If the user enters something that cannot be converted to an integer (like letters), the
ValueError
will be caught, and an error message will be displayed.
Key Points:
- The text within the
input()
function is the prompt displayed to the user. - Always consider potential input errors and handle them gracefully (as shown in the error handling example).
This should give you a good understanding of how to use the input()
function to get keyboard input in Python.
0 件のコメント:
コメントを投稿