已经坚持了大约一个小时。目前正在尝试使用Python自学编程。我正在使用教科书编写的东西,它引导我通过伪代码然后我尝试将其转换为python以学习语法。虽然编程运行并按预期添加,但如果用户输入除整数之外的任何内容,它将不会打印我想要的内容。
Pseudocode我在看:
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
这是我写到这一点的代码:
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))
答案 0 :(得分:2)
如果int(arg)
不是整数,arg
函数会抛出异常。
您需要捕获异常:
number = input()
try:
number = int(number)
except ValueError:
print "Number is not an integer"
答案 1 :(得分:0)
你可以这样做:
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))