What does Python input function return? The output of the input function is always a string. The input function of Python library takes the data from the user and then it converts it into a string. After that, you can process that string in whatever way you want.
For Python 2, the function raw_input() is used to get string input from the user via the command line, while the input() function returns will actually evaluate the input string and try to run it as Python code.
Use raw_input()
instead of input()
:
testVar = raw_input("Ask user for something.")
input()
actually evaluates the input as Python code. I suggest to never use it. raw_input()
returns the verbatim string entered by the user.
The function input
will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin
) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input
which is the same as input
but omits the evaluation.
We can use the raw_input()
function in Python 2 and the input()
function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input()
function. It waits for the user to type some input and press return
and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With