#This program calculates the average of integer entered
#Once the use press "S".
#"S" is the sentinel
COUNT= 0
SUM= 0
INT=1
Sentinel = "S"
print('Enter test scores as integers, or enter S to get average.')
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
#Continue processing as long as the user
#does not enter S
while INT!= Sentinel:
INT=input('Enter integer: ')
I=int(INT) #attempting to format the input(INT) as an integer
COUNT= + 1
SUM = COUNT + I
if INT == Sentinel:
AVRG= SUM/(COUNT-1)
我不断收到此错误消息: 回溯(最近一次调用最后一次): 文件“C:\Users\joshu\Documents\COP100 Python\practice examples\program4-13.py”,第 16 行,在 我=整数(INT) ValueError:int() 的无效文字,基数为 10:'S'
答案 0 :(得分:0)
您的代码假设用户将始终输入数值。
此行将接受用户输入的任何数据。它可以是数字或非数字。
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
在将数据转换为整数之前,请检查该值是否为数字。如果不是,那么您可能需要向用户发送一条错误消息。
I=int(INT) #attempting to format the input(INT) as an integer
你可以这样做:
if INT.isnumeric():
I = int(INT)
else:
print ('not a numeric value')
我假设用户只会输入整数。上面的代码仅适用于整数。如果要检查浮点数,请使用 try: except
语句。
此外,您计算 SUM
以获得平均值是不正确的。您不应将 COUNT
添加到 SUM
。您应该只在增加 I
时将 SUM
添加到 COUNT
。
也不要尝试使用变量名作为 sum、int(即使是大写)。
这是您可以尝试的工作代码。
count = 0
total = 0
Sentinel = "S"
#Continue processing as long as the user does not enter S
while True:
test_score = input('Enter test score as integer or enter S to get average: ')
# input received as a string to allow for the entry of "S"
if test_score.isnumeric():
score = int(test_score) #attempting to format the input(INT) as an integer
count += 1
total += score
elif test_score.upper() == Sentinel:
break
else:
print ('Not an integer or S. Please re-enter the value')
if count > 0:
print (total, count)
average_score = total/count
print ('average score is : ', average_score)
else:
print ('No valid entries were made. Average score is N/A')