Python: Problem with raw_input reading a number
Do
totPrimes = int(totPrimes)
while count < totPrimes:
# code
raw_input
gives you a string you must convert to an integer or float before making any numeric comparison.
How can I read inputs as numbers?
Solution
Since Python 3, input
returns a string which you have to explicitly convert to int
s, with int
, like this
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
You can accept numbers of any base and convert them directly to base-10 with the int
function, like this
>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365
The second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a ValueError
.
>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'
For values that can have a fractional component, the type would be float
rather than int
:
x = float(input("Enter a number:"))
Differences between Python 2 and 3
Summary
- Python 2's
input
function evaluated the received data, converting it to an integer implicitly (read the next section to understand the implication), but Python 3'sinput
function does not do that anymore. - Python 2's equivalent of Python 3's
input
is theraw_input
function.
Python 2.x
There were two functions to get user input, called input
and raw_input
. The difference between them is, raw_input
doesn't evaluate the data and returns as it is, in string form. But, input
will evaluate whatever you entered and the result of evaluation will be returned. For example,
>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)
The data 5 + 17
is evaluated and the result is 22
. When it evaluates the expression 5 + 17
, it detects that you are adding two numbers and so the result will also be of the same int
type. So, the type conversion is done for free and 22
is returned as the result of input
and stored in data
variable. You can think of input
as the raw_input
composed with an eval
call.
>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)
Note: you should be careful when you are using input
in Python 2.x. I explained why one should be careful when using it, in this answer.
But, raw_input
doesn't evaluate the input and returns as it is, as a string.
>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)
Python 3.x
Python 3.x's input
and Python 2.x's raw_input
are similar and raw_input
is not available in Python 3.x.
>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)
raw_input function in Python
It presents a prompt to the user (the optional arg
of raw_input([arg])
), gets input from the user and returns the data input by the user in a string. See the docs for raw_input()
.
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input()
in that the latter tries to interpret the input given by the user; it is usually best to avoid input()
and to stick with raw_input()
and custom parsing/conversion code.
Note: This is for Python 2.x
how to check whether raw_input is integer, string and date in python
datetime.datetime.strptime()
will raiseValueError
if the string does not match the format.raw_input()
always return string object, soisinstance(data1, int)
always isFalse
if you don't covert thedata1
to int object before check.I'd suggest use
try...except
to catch theValueError
like the following code:import datetime
data1 = raw_input("data = ")
print(data1)
try:
datetime.datetime.strptime(data1, '%Y-%m-%d')
except ValueError:
try:
int(data1)
except ValueError:
print("str it is")
else:
print("int it is")
else:
print("date it is")Demo:
kevin@Arch ~> python2 input_check.py
data = 2014-01-02
2014-01-02
date it is
kevin@Arch ~> python2 input_check.py
data = 12
12
int it is
kevin@Arch ~> python2 input_check.py
data = foobar
foobar
str it is
Related Topics
Way to Change Google Chrome User Agent in Selenium
Add Leading Zeros to Strings in Pandas Dataframe
Lost Connection to MySQL Server During Query
Transpose Column to Row with Spark
Unnest (Explode) a Pandas Series
Python: Calling 'List' on a Map Object Twice
Python: Problem with Raw_Input Reading a Number
In Practice, What Are the Main Uses for the "Yield From" Syntax in Python 3.3
What's the How to Install Pip, Virtualenv, and Distribute for Python
What's the Difference Between Select_Related and Prefetch_Related in Django Orm
Python's Equivalent of && (Logical-And) in an If-Statement
Matplotlib Make Tick Labels Font Size Smaller
Can Pandas Automatically Read Dates from a CSV File