2

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?

1
  • You may also have a look at ast.literal_eval Commented Feb 10, 2013 at 7:36

3 Answers 3

1

Put the try/except inside the loop.

while True:
    try:
        n = int(input("How many numbers to sum up?: "))
        if n <= 0:
            print("You have to write a positive integer; try again!")
            continue
        break
    except ValueError:
        print("You have to write a positive integer; try again!")

You could also replace the last part of your code (the part after the first loop) with this:

squares = lambda x: [print('{0} * {0} = {1}'.format(x, x**2)), x**2][1]

print("Sum:", sum(squares(i) for i in range(1, n+1))

The lambda isn't recommended though ;). You could of course use a normal function instead:

def squares(x):
    print('{0} * {0} = {1}'.format(x, x**2))
    return x**2
Sign up to request clarification or add additional context in comments.

Comments

1

You can use str.isdigit() to accomplish this. According to the docs, isdigit() accepts compatibility superscript digits such as \u0660123. But python 3's input() escapes the backslash for this type of input so these strings shouldn't cause any issues.

while True:
  n = input("How many numbers to sum up?: ")
  if n.isdigit() and int(n) > 0:
    break
  else:
    print("You have to write a positive integer; try again!")

squares = (i**2 for i in range(1,int(n)+1))
s = 0
for integer in range(1,int(n)+1):
  nextsquare = next(squares)
  s += nextsquare
  print(integer, "*", integer, '=', nextsquare, sep='')

print('Sum', s)

Comments

0

I guess something like this? pseudo-python:

n = None
while n is None:
    try:
        n = int(input("How many numbers to sum up?: "))
    except ValueError:
        pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.