I am currently writing a program in Python 3.3.0 which prints out the n first square numbers and finally prints out their sum. The condition is that the user can only compute an integral number of terms greater than zero. Here is the code:
print("WELCOME!")
n = input("How many numbers to sum up?: ")
while n <= 0:
print("You have to write a positive integer; try again!")
n = input("How many numbers to sum up?: ")
i = 1
sum = 0
while 0 < i <= n:
print(i,"*",i,"=", i**2)
sum += i**2
i += 1
print("Sum:", sum)
Now, I managed to code the error message for when the user types in a negative number. However, I am having difficulties coding an error message for when the user types in a string, such as "fifteen".
I want the program to allow the user to try assigning 'n' a value once again and again, just as if they had typed a negative number; basically I want to code a loop asking for the same thing over and over again if the user inputs a string.
The problem is that input() always assigns a string to an arbitrary variable, so I tried writing code for converting the string to an integer. It works fine when the user inputs an integral value, however it cannot define int(n) if 'n' is not an integer.
I have googled a lot regarding this issue and I found some examples using try and except ValueError but none of them seem to be able to create a loop out of it.
Anybody got an idea?
ast.literal_eval