I'm making this program that asks you for a number then prints out the first 1000 terms of that number's times table. I'm using Python 3x The output should be:
http://snag.gy/KxM37.jpg
But instead it gives me this: http://snag.gy/SQTAe.jpg
This is the code:
multiplication = 0
firstnumber = int(input("Enter a number: "))
number = firstnumber
for j in range(0, 1001):
for i in range(0, 1001):
multiplication = multiplication+1
number = number*multiplication
print(str(multiplication) + " times " + str(firstnumber) + " is " + str(number))
Thanks
3 Answers 3
I find it easier to think through the problem before trying to start coding.
You have the first step: Get a number from the user
I think the second step consists of going from 0 To 1000 and multiplying that number. In psuedo-code:
users_number = some_number
for num from 0 - 1000:
print(num * usernumber)
2 Comments
Your problem is that you update number and keep multiplying it. You foresaw this problem and created a variable called firstnumber to tackle it, but you forgot to use it. Here’s what you meant to do:
>>> multiplication = 0
>>> firstnumber = int(input("Enter a number: "))
Enter a number: 17
>>> number = firstnumber
>>> number = firstnumber
>>> for j in range(0, 1001):
... for i in range(0, 1001):
... multiplication = multiplication+1
... number = firstnumber * multiplication
... print(str(multiplication) + " times " + str(firstnumber) + " is " + str(number))
...
1 times 17 is 17
2 times 17 is 34
3 times 17 is 51
4 times 17 is 68
5 times 17 is 85
6 times 17 is 102
7 times 17 is 119
8 times 17 is 136
9 times 17 is 153
10 times 17 is 170
11 times 17 is 187
12 times 17 is 204
13 times 17 is 221
14 times 17 is 238
15 times 17 is 255
16 times 17 is 272
You are likely, however, much better off, to do something like this:
number = int(input("Enter a number: "))
mult = int(input("How many multiples: "))
for i in range(mult+1):
print("%d times %d is %d" %(number, i, number*i))
9 Comments
Might not be the best code, but better than what you were trying.
given_number = int(input("Enter a number: "))
for multiplier in range(1,1001):
print("{0:4} times {1} is {2}".format(multiplier, given_number, multiplier*given_number))
firstnumber * multiplication, notnumber * multiplication.1001to a smaller number like5and you'll probably see what's wrong with your code.