I am writing a program to calculate the sum of the first n natural numbers but I am having a hard time coding the first part of the program in which I ask for the input from the user (about how many successive natural numbers to add).
It's a very long code for such a simple task because I want the program to be able to:
ask to "try again" in case the input isn't a natural number;
accept mathematical expressions that are equal to a natural number (e.g. 6 / 3).
# Program to calculate sum of first n natural numbers try: n = eval(input('How many successive natural numbers, starting from 1, would you like to add up? ')) if type(n) != int and not n.is_integer() or n < 0: raise Exception except: while True: try: n = eval(input('How many successive natural numbers, starting from 1, would you like to add up? ')) if type(n) != int and not n.is_integer() or n < 0: raise Exception except: continue else: break print(n)
To get back to the point: why does my IDE keep telling me that n can be undefined?
And if you'd be willing to take the time to tell me how to shorten my code (that seems a little repetitive), I'd really appreciate it.
Thank you for your time!