Python User Input

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.

Tutorials dojo strip

Example:

The following code prompts the user to enter their name and then prints a greeting:




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:


Converting to Float:

The following code prompts the user to enter their height and converts the input to a float:




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:




Tutorials dojo strip