How to use raw_input without input
I want to use a function raw_input()
in Python. I want to get a number from the user about the storage size I wrote this:
number=raw_input()
if the user does not provide input, then number = 10
, therefore
if number is None:
number = 10
when i print the number i get nothing, i even tried:
if number==-1:
number=10
print"the storage size was set to:",number
The output was:
<P -> storage size was set to -1
but not 10
So how do I solve this?
If you don't want to distinguish between "no input" and "invalid input" (for example, not an integer literal), set the default and then try replacing it with user input.
number = 10
try:
number = int(raw_input())
except (EOFError, ValueError):
pass
ValueError
will be hoisted on invalid inputs including an empty string. EOFError
occurs if the user does something like type Control-d in the terminal, which interprets it as closing standard input.
source to share
First of all, you need to convert the input (default for raw_input is a string) to int using a function int()
. But make sure you check first that the user has typed something. Otherwise, you cannot convert an empty string. For example:
num_input = raw_input()
if num_input:
number = int(num_input)
Then already the second part of your question should work:
if number == -1:
number = 10
print "the storage size was set to:", number
The second point is that empty is string
not equal None
. None
is the only value NoneType
, and ""
- string
.
So, you can compare the input to an empty string, but you can do better (empty string evaluates to False
):
if not num_input:
number = 10
and to be even more efficient, you can simply add a statement else
to my first piece of code:
num_input = raw_input()
if num_input:
number = int(num_input)
else:
number = 10
source to share