Python: User input

  • Input from Keyboard
  • For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string.

When taking input, use the input() function. When a program executes on the console, it asks the user for input. It’s important to remember that any input taken from the user, whether it’s a number or an alphabet, will be stored in string format.

Important points

  • When working with user input, it’s important to validate and sanitize the input to ensure it’s in the expected format and doesn’t introduce security vulnerabilities into your program.
  • To convert user input to a different data type, such as an integer or a float, you can use type casting. For example, if you want to convert a user input to an integer, you can use the int() function.
  • It’s important to handle exceptions when working with user input. For example, if the user enters a string when you’re expecting a number, you’ll want to handle that gracefully to avoid your program crashing.
  • Always provide clear instructions to the user when asking for input. This helps users understand what type of input is expected and reduces the likelihood of errors.
username = input("Enter username:")

For example

When you input the number 5, if you store it in a variable, it will be stored as a string, not an integer. When you take integer input from users and save it as an integer if it is an integer.