So im trying to create a times table:
Write a program to print a multiplication table (a times table). At the start, it should ask the user which table to print and how high the table should go.

The output should look something like this:
Which multiplication table would you like?
5
How High?
10
Here’s your table:

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

but my code just keeps running infinitely
(EXAMPLE OF INFINITE OUTPUT)

Which multiplication table would you like:
None7
How high
None9
Heres your table 7 X 9 =
Heres your table 7 X 9 =
Heres your table 7 X 9 =
Heres your table 7 X 9 =
" "

EXAMPLE OF CODE:

num1 = int(input(print("Which multiplication table would you like: ")))
num2 = int(input(print("How high")))
total = 1

while total != 0:
    total = num1 * num2
    
    print("Heres your table", num1, 'X', num2, '=')

Dani AI

Generated

Quick practical fix for .

Two things are causing the weird output and the infinite loop. First, calling print(...) inside input(...) is wrong: print() returns None, so input(print("...")) ends up showing None as the prompt (that's why you saw None7). Pass the prompt string directly to input. Second, the loop never changes the value that controls termination: you compute a single product and then test while total != 0, so if the product is nonzero the loop never ends. was right to point out the loop problem, and is right that a for loop is the simplest solution.

A concise Python 3 example (works on Python 3.6+ for f-strings):

try:
    n = int(input("Which multiplication table would you like? "))
    m = int(input("How high? "))
except ValueError:
    print("Please enter whole numbers.")
else:
    if m < 1:
        print("Nothing to print: 'How high' must be at least 1.")
    else:
        for i in range(1, m + 1):
            print(f"{n} X {i} = {n * i}")

Extra tips: if you prefer a while loop, use a counter (i = 1 then while i <= m: ...; i += 1). Use clear variable names (e.g., multiplier), validate inputs, and remember that on Python 2 you would use raw_input() instead of input().

Recommended Answers

All 3 Replies

num1 and num2 do not change inside the while loop so exit condition is never fullfilled.

num1 and num2 do not change inside the while loop so exit condition is never fullfilled.

so how do i get an exit condition. im new to this haha

Assuming "How high" means the number of rows to print, use a for() loop instead:

for ctr in range(num2):
    print "row number", num+1

A link to getting input from the user. It's for Python 2.x but can be easily modified for 3.x.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.