0
votes

In the following script:

# shows multiplication table of a number upto that number
import time
while True:
    num = input("Enter number: ")
    try:
        def mult():
            for i in range(1, int(num)+1):
                print(str(i) + " x " + num + " = " + str(i * int(num)))
    except ValueError:
        print("Please enter a number")
        continue

    mult()
    time.sleep(2)

I want "Please enter a number" to be displayed if the input for num is not an integer value, as that gives ValueError due to int(num) found inside mult().

However, the try/except block doesn't seem to work because, when entering a non-numerical string, it displays Python's Traceback error:

Enter number: forty five
Traceback (most recent call last):
  File "...", line 13, in <module>
    mult()
  File "...", line 7, in mult
    for i in range(1, int(num)+1):
ValueError: invalid literal for int() with base 10: 'forty five'

Why is error handling not working?

2

2 Answers

0
votes

You can just remove the mult() function definition, as it doesn't seem particularly important (correct me if it is).

Your code will then look like this:

import time
while True:
    num = input("Enter number: ")
    try:
        for i in range(1, int(num)+1):
            print(str(i) + " x " + num + " = " + str(i * int(num)))
    except ValueError:
        print("Please enter a number")
        continue
    time.sleep(2)

the reason this didn't work originally is because your try statement was wrapped around a definition, not around an actual call of the mult() function. This means that when it ran, it tried to define a function called mult, and that worked fine. However, when it actually called the function on line 13, it caused it to break as there was no try statement.

0
votes

why are you defining the mult inside the try?

try putting the try inside the function. right now you are trying to check if you can create the function mult. after you succeed you attempt to call it (where you will encounter a problem).

`

# shows multiplication table of a number upto that number
import time
while True:
    num = input("Enter number: ")
    def mult():
        try:
            for i in range(1, int(num)+1):
                print(str(i) + " x " + num + " = " + str(i * int(num)))
        except ValueError:
            print("Please enter a number")
            continue

mult()
time.sleep(2)`

this should work, plus please notice that if you want to enter a value into your function, is should be done like: def mult(data)

called: mult('the data')