[Tutor] User input question
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 8 Aug 2002 17:40:28 +0100
> OK guys, bear with me - this is my first EVER foray into
> Python, but I think
> I may have stumbled clumsily into a solution (of sorts)....
Pretty close. You should find you still get None
printed at the end tho'...
Now lets tidy it up a wee bit
> def timestab(n):
> m = 1
> if i < 13:
Better to check if n<13 since n hold the value you
pass to timestab(the value of i in your case).
> while m < 14:
It was conventional to only print the first 12 lines at my schoool! This
prints 13... but idf thats what you want thats OK.
> print "%d x %d = %d" % (m,n,m*n)
> m = m + 1
> else:
> print "Only positive numbers between 1 and 12 please!"
An easier way uses a for loop and range:
def timestab(n):
if n<13:
for m in range(1,14):
print "%d x %d = %d" % (m, n, m*n)
else: print "Only positive numbers please"
Now tidy that up more by observing that the error message
really relates to the input() operation rather than
printing the table so if we move it outside
def timestab(n):
for m in range(1,14):
print "%d x %d = %d" % (m, n, m*n)
i = input("What table?")
if i < 13:
timestab(i)
else:
print "Only positive numbers 1-12 please"
Finally we could check if the number really was positive
by checking if it was divisible by 2 using the modulo
operator:
if i < 13 and (i % 2 == 0):
....
But yours works and that's always a great result
for a first timer. Well done.
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld