[Tutor] User input question

shey crompton shey@argonaut.com
Thu, 8 Aug 2002 15:59:13 +0100


Ahh, I see where I was going wrong now. Thanks.

Out of curiosity, the  if __name__ == "__main__":  line...
Where does __name__ and __main__ refer to in the script?

 -----Original Message-----
From: 	ibraheem umaru-mohammed [mailto:iumarumo@eidosnet.co.uk] 
Sent:	08 August 2002 15:34
To:	shey crompton
Subject:	Re: [Tutor] User input question

[shey crompton wrote...]
-| I have been trying to modify a script that prints out the times tables to
-| one that asks the user to input which times table they would like printed
-| out (between 1 and 13).
-| I have tried so many different ways of doing this without any success. I
am
-| sure it's a simple answer, but I am starting to get frustrated.
-| The script below is my latest attempt, and the error message I get is
below
-| it. 
-| Hints, and tips greatly appreciated.
-| 
-| Shey
-| 
-| 
-| def timestab(n):
-|     if i < 13:
-|         print "%d x %d = %d" % (i,n,i*n)
-|     else:
-|         print "Only positive numbers between 1 and 12 please!"
-| 
-| i = input('Try a number ')
-|     print timestab(i)
-| 
-| 
-| The error message is:
-| 
-| File "C:\Documents and Settings\shey\Desktop\timesTab_8.py", line 15
-|     print timestab(i)
-|     ^
-| SyntaxError: invalid syntax
-| 

Firstly, the error you get is because of the whitespace in front of the
print statement. Secondly, timestab doesn't explicitly return anything,
so print'ing the return of timestab, will print 'None'.
Thirdly, the timestab function checks that the value of i is less than
13, but doesn't check whether it is greater than zero.
Fourthly, it is safer to use "raw_input" instead of "input", because
input can return the result of an expression, and unless you trust your
users, (which you shouldn't) then they might do something harmful.
Finally, if you want to print the times table for a given number upto
a given number, then you are going to need some sort of loop...

Have a look at the following changes I have made:

			...<snip>...
#!/usr/bin/python

def timestable(n):
  if n in range(1,13):
    for i in range(1,13):
      print "%d x %d = %d" % (n,i,n*i)
  else:
    print "Only positive numbers between 1 and 12 inclusive please"

if __name__ == "__main__":
  userinput = raw_input("Please enter a number between 1 and 12 inclusive:
")
  try:
    timestable(int(userinput))
  except ValueError, e:
    print "Invalid number entered"

			...<snip/>...


Hope that helps a little.

Kindest regards,

			--ibs.

-- 
			ibraheem umaru-mohammed
			   www.micromuse.com
			         --0--