process is not reaching a line inside try block

Viewed 41

I am trying to self learn python and have written a basic program to add sum of 1st n numbers of digits. When I am giving an integer input, it is executing perfectly but on non-integer input, throwing an error NameError: name 'add_it_up' is not defined. My program is written below.

try:
    x = int(input('Enter the number upto which you want to add :'))

    try:

        def add_it_up(x):
            sum = 0
            for num in range(x + 1):
                sum = sum + num
            print(sum)
    except TypeError:
        print("Sorry we are facing a problem")
except ValueError:
    print("Please enter an intiger value only")

add_it_up(x)
2 Answers

You are defining a function in the try block, not running it. Put the add_it_up function outside the try/except and then call it inside. Like this:

def add_it_up(x):
        sum = 0
        for num in range(x + 1):
            sum = sum + num
        print(sum)

try: 
    x = int(input('Enter the number upto which you want to add :'))

    try:   
        add_it_up(x)
    except TypeError:
        print("Sorry we are facing a problem")

except ValueError: 
    print("Please enter an intiger value only")

scope of add_it_up function is inside of try statement only, this is why yuo are getting the errror.

def add_it_up(x):
        sum_ = 0
        for num in range(x + 1):
            sum_ = sum_ + num
        return sum_
try:
    x = int(input('Enter the number upto which you want to add :'))
    try:
        result = add_it_up(x)
        print(result)
    except TypeError:
        print("Sorry we are facing a problem")
except ValueError:
    print("Please enter an intiger value only")
Related