[Tutor] Help on "IF" Statements

alan.gauld@bt.com alan.gauld@bt.com
Tue, 1 Aug 2000 16:16:32 +0100


> >>> x = int(raw_input("Please enter a number: "))
> >>> if x < 0:
> ...      x = 0
> ...      print 'Negative changed to zero'
> ... elif x == 0:
> ...      print 'Zero'
> ... elif x == 1:
> ...      print 'Single'
> ... else:
> ...      print 'More'

Works OK for me...

> I've done several attempts:
> 
> 1.  to type it: but the result is err
> 	>>> x = int(raw_input("Please enter a number: "))
> Please enter a number: 
> Traceback (innermost last):
>   File "<pyshell#2>", line 1, in ?
>     x = int(raw_input("Please enter a number: "))
> ValueError: invalid literal for int():

Thats because you just hit ereturn which is not a valid number so the call
to int() fails. To guard against that change:

> >>> x = int(raw_input("Please enter a number: "))

to
>>> x = raw_input("Please enter a number: ")
>>> if not ((len(x) >= 1) and (x[0] >='0') and (x[0] < '9')):
...    print 'I said enter a number bozo!'
... else: 
...	x = int(x)
...    if x < 0: # proceed as before...

That's still not bombproof but for that you probably 
want to use  exceptions which you haven't covered 
in the tutor yet :-)

Alan G.

> 
> 2.  to copy it (and then to delete the points from the
> front):

Sorry, I don't understand that bit...

> Please enter a number: 7
> >>>
> (no error but I can't see any print result.)

I got 'More'

You've understood IF OK, its the conversion of user 
input to an int thats causing the problem, and 
how to trap errors(which comes later...)

Alan G.