Python : User Input

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:

  • The input("Enter your name: ") statement prompts the user to enter their name.
  • Whatever the user enters is stored in the variable name.
  • The print("Hello, " + name + "!") statement then prints a greeting message using the value stored in the name variable.

Converting Input to Other Data Types:


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.

Handling User Input Errors:


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.")

 

Multi-line Input:


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.

Note:

  • The input() function always returns a string, so if you need the input to be of a different data type, you'll need to convert it using type casting (e.g., int(), float() ).
  • Be cautious when using input() with untrusted input, as it can potentially lead to security vulnerabilities (e.g., code injection). Always validate and sanitize user input when necessary.