3

I want to use raw_input() function in Python. I want to receive a number from user about the size of the storage i wrote this down :

number=raw_input()

if the user doesn't provide an input then number = 10 so

if number is None:
   number = 10

when i print number, i get nothing i even tried:

if number==-1:
   number=10
print"the storage size was set to:",number

The output was:

> the storage size was set to -1

and not 10

So how should I solve this ?

Bryce Frank
  • 697
  • 10
  • 24
  • What python version are you using? Also, `number` will always be a `string`. – Idos May 06 '17 at 13:58
  • 3
    `raw_input()` returns a string and you are checking equality with an integer. The condition will always return false. In first case if you do not input anything, it will be just blank string( `''`) – kuro May 06 '17 at 13:58

5 Answers5

2

If you don't care to distinguish between "no input" and "invalid input" (like a non-integer literal), set the default, then attempt to replace it with the user input.

number = 10
try:
    number = int(raw_input())
except (EOFError, ValueError):
    pass

ValueError will be raised on invalid inputs, including the empty string. EOFError is raised if the user does something like type Control-d in a terminal that interprets that as closing standard input.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

First of all you have to convert the input (default for raw_input is a string) into an int using int() function. But be sure that you first check if user typed something. Otherwise you can't 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 an empty string is not equal to None. None is the only value of NoneType and "" is a string.

So you can compare the input with an empty string, but you can do better (an empty string is evaluated as False):

if not num_input:
    number = 10

and to be even more efficient you can simply add an else statement to my first piece of code:

num_input = raw_input()
if num_input:
    number = int(num_input)
else:
    number = 10
Graham
  • 7,431
  • 18
  • 59
  • 84
kmartin
  • 194
  • 3
  • 9
0

compare number with empty string; not with None .

if number == '':  
    number = 10     
kuro
  • 3,214
  • 3
  • 15
  • 31
Himanshu dua
  • 2,496
  • 1
  • 20
  • 27
0

In Python when the variable is empty then it's have inside empty '', so if you want to check if your variable is unset you need to compare it to '' and not to None.

if number=='':
   number=10
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
0

You should just compare number and empty.:

if number=="":
    number==10