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))
2
  • 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 Commented Nov 24, 2017 at 14:48
  • continue at the end is redundant. your loop will continue with or without that statement Commented Nov 24, 2017 at 14:50

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Note you should credit your sources (stackoverflow.com/questions/5424716/…) 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.
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.
after a little more research I understand what you are trying to say here. Thank you.
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))

1 Comment

Thank you.. This best explained it for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.