In Python, you can use the input() function to prompt the user for input from the keyboard. The input() function reads a line of text entered by the user and returns it as a string. Here's how to use the input() function:
name = input("Enter your name: ")
print("Hello, " + name + "!")
In this example:
By default, the input() function returns the user's input as a string. If you need the input to be of a different data type (e.g., integer, float), you can use type casting to convert it:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
In this example, the int() function is used to convert the input string to an integer before storing it in the age variable.
When using the input() function, keep in mind that it always returns a string. If the user enters something that cannot be converted to the desired data type, it will raise an error. You can use error handling techniques like try-except to handle such cases:
try:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
If you need to prompt the user for multi-line input, you can use a loop to read lines until the user indicates they are done (e.g., by entering an empty line):
lines = []
print("Enter multiple lines of text (press Enter twice to finish):")
while True:
line = input()
if line:
lines.append(line)
else:
break
text = "\n".join(lines)
print("You entered:")
print(text)
In this example, the loop continues to prompt the user for input until they enter an empty line. The lines entered by the user are stored in a list, which is then joined into a single string and printed.