2

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))
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Runferurlife
  • 55
  • 1
  • 6
  • 1
    this is meaningless: `number != int(number)` because you already assign to `number` the result from `int(input(...))` which means it's always going to be an int – EdChum Nov 24 '17 at 14:48
  • `continue` at the end is redundant. your loop will continue with or without that statement – Adelin Nov 24 '17 at 14:50

2 Answers2

2

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"
Vyko
  • 212
  • 1
  • 6
  • Note you should credit your sources (https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) and or at least add to them by noting that this works in Python 3, but Python 2 you should cast to a string first such as: int(str(number)) as @maxkoryukov noted in the above answer's comments. – Steve Byrne Nov 24 '17 at 15:00
  • I see this.. where would I put it in the code I already have? I have seen this try-except method and attempted to put it into my code for about 30 min. Couldn't figure it out. – Runferurlife Nov 24 '17 at 15:12
  • after a little more research I understand what you are trying to say here. Thank you. – Runferurlife Nov 24 '17 at 18:56
0

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))
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65