+ 1
Sum of square of first n natural numbers
try: num=int(input("Enter a number:")) def sum(num): result=0 if num < 0: print(num, "is not a natural number!") else: for i in range(1,num+1): result=result + (i*i) return result print("The sum of square of first", num, "natural number is:", sum(num)) except ValueError: print("Invalid Input") For the given code; How can I not execute, ***print("The sum of square of first", num, "natural number is:", sum(num))*** this statement for input less than zero? Putting this statement inside else block did not help!
2 Answers
+ 2
Move the `sum` function out of the try ... except block, then do the validation to decide whether to call the function (input is natural number, > zero)
def sum(num):
// function body
try:
# input <num> variable
if <num> < 0:
# error message
else:
# call the sum function
# display square sum here
except ValueError:
# bad input ...