In this article, I will explain how to read user input in Python. Python 2 and Python 3 differ slightly in the ways that they support reading user input. Though the main focus of this article would be to demonstrate how to read user input in Python 3, I will quickly touch upon the Python 2 approach as well and explain how it differs from Python 3
Python 3 provides a method input()
. You can use this to read input that a user enters. This method treats the value entered by a used as a String.
The following code demonstrates this:
name = input("Enter your name:")
print("Hello ",name)
input()
method accepts as parameter a String that it displays to the userThe input()
method converts the value entered by a user to String. So, if you want to read an integer type, you need to use typecasting. Python provides an in-built method int()
that converts a value to an Integer. The following code demonstrates this:
num = int(input("Enter a number:"))
if num%2==0:
print("Number is even")
else:
print("Number is odd")
int()
method typecasts the value read via input()
to an integerJust like the int()
method, Python supports a float()
method. You can use this method to typecast the input that the user enters to float.
Python 2 supports two in-built methods to read user input. These are as follows:
raw_input()
- This is similar to the input()
function in Python 3. It converts the value entered by a user to a Stringinput()
- This method converts the value entered by the user to the appropriate data type.The Python Masterclass Everything you need to know about Python Python for beginners Python for finance
So in this article, we understood how to read user input in Python. We took at look at the input() method in Python 3. We also saw how to use typecasting to convert the user input to data of the appropriate type. Finally, we touched upon reading user input in Python 2 and how it differs from Python 3.