Checking that user input is an int (python)

Viewed 141

Have been stuck on this for about an hour. Currently trying to teach myself Programming using Python. I am using a textbook for the programming stuff which walks me through pseudocode and then I attempt to convert this into python to learn the syntax. While to program runs and adds as it is supposed to, it will not print what I want it to if the user enters anything but an integer.

Pseudocode I am looking at:

1  Declare Count As Integer 
2  Declare Sum As Integer 
3  Declare Number As Float 
4  Set Sum = 0 
5  For (Count = 1; Count <=10; Count++) 
6    Write “Enter an integer: “ 
7    Input Number 
8    If Number != Int(Number) Then
9      Write “Your entry is not an integer.” 
10      Write “The summation has ended.” 
11      Exit For 
12    Else 
13 Set Sum = Sum + Number 
14    End If 
15  End For 
16  Write “The sum of your numbers is: “ + Sum

This is the code i have written to this point:

sum = 0
for count in range(0, 10):
    number = int(input("Write an integer: "))
    if number != int(number):
        print ("Your entry is not an integer.")
        print ("The summation has ended.")
        break
    else:
        sum = sum + number
    continue
print("The sum of your numbers is: " + str(sum))
2 Answers

The int(arg) function throws an exception if arg is not an integer.

You need to catch the exception:

number = input()
try:
    number = int(number)
except ValueError:
    print "Number is not an integer"

You could do something like this:

sum = 0

for count in range(1, 10):
    try:
        sum += int(input("Write an integer: "))
    except ValueError:
        print("Your entry is not an integer.")
        print("The summation has ended.")
        break

print("The sum of your numbers is: " + str(sum))
Related