The best way to take input for a user is using raw_input
, this will take in user input as a string. Let me demonstrate:
>>> var = raw_input("Enter")
Enter>? happy
>>> var
'happy'
Notice the quote-marks on happy, this indicates a string. You may also notice, input
, and yes that can be used to take user input, but here is one example where that is a bad idea:
>>> a = 2
>>> input("Enter")
Enter>? a+1
3
Here, input
actually gets evaluated, since we've already declared a
, a + 1 == 3
, and we see that as the output in our console session. This later becomes a security concern (you would not want users messing around with your variables), so for user input, raw_input
is the best choice.
Since you get a string
from raw_input
, you can convert it to whatever you like, if it can be converted, for example:
>>> var = raw_input("Enter")
Enter>? 122
>>> var = int(var)
>>> var
122
However, floats will not work with int
:
>>> int('1.223')
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '1.223'
You will need to use float
here, then it works:
>>> float('1.223')
1.223