User Input in Python
User input is the key to making your Python programs interactive. It is like having a conversation with your code. A large part of user interaction is allowing users to input information into a program.
In Python, we use the input() function to prompt the user for input during runtime.
What is input()?
In Python, the input() function is used to prompt the user for input while the program is running. It shows the user a message (known as the prompt) and waits for them to type something on the keyboard before pressing the Enter key. The user’s input is returned as a string.
Here’s a basic example:
- username = input(“Enter username:”)
print(“Username is: “ + username)
Output: Enter username:
Username is: Anas
- number_as_integer = int(number_as_string)
print(f “The value of the integer is {number_as_integer}”)
Output:
The value of the integer is 123
- num = input(‘Enter a number: ‘)
print(‘You Entered:’, num)
print(‘Data type of num:’, type(num))
Output: Enter a number: 10
You Entered: 10
Data type of num: <class ‘str’>
In the above example, we have used the input() function to take input from the user and stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number. So, type(num) returns <class ‘str’>.
To convert user input into a number we can use int() or float() functions as:
- num = int(input(“Enter a number: “)
print(num, “ “ , type(num))
floatNum = float(input(“Enter a decimal number: “))
print(floatNum, “ ”, type(floatNum))
Output: Enter a number: 29
29 <class ‘int’>
Enter a decimal number 100.4
100.4 <class ‘float’>
Here, the data type of the user input is converted from string to integer .
Best Practices for Using input() Function:
The following are some best practices to remember when using the input() function:
- Always include a prompt argument to provide clear direction for the user.
- When converting input strings into other data types, use type conversion functions.
- Validate user input with conditional statements to ensure the data entered is valid and meets your expectations.
- Avoid using the input() function for sensitive information like passwords, as the user’s input will be displayed in plain text.
Conclusion:
The input() function is a fundamental tool for user interaction in Python programs. You can make reliable and easy-to-use applications if you know how to use it well and follow best practices.