输入陷阱故障(除其他外)

2024-09-27 07:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我又来了,像往常一样不知所措。我是一个新手,所以这可能是咬了超过我可以咀嚼,但无论如何。 这个程序的目的是提供一个基于用户输入值的输出。如果用户没有输入正确的输入,它将实现一个输入陷阱

我试图使它这样一个字母或非整数值的输入会导致消息“请只输入整数。”它适用于浮点,但不适用于字母。我应该注意到,“输入一个介于0和10之间的数字”消息工作正常。 此外,循环应该在用户输入“done”时关闭,但这只会导致“ValueError:could not convert string to float:'done'”

我没有用While-True的格式写这篇文章,因为对于我来说,摆脱While循环的写作方法更舒服

setCount = 1
 allScore = 0
 done = False
 while not done:
   strScore = float (input ( "Enter Set#" + str(hwCount) + " score: "))
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
    totalScore = totalScore + (strScore)
    setCount = setCount + 1
elif ( setScore == int (strScore) and( setScore < 0 or setScore > 10)):
    print ("Please enter a number between 0 and 10.")
elif setScore != "done":
    print ("Please enter only whole numbers.")
else:
    done = True

Tags: and用户true消息字母not整数float
2条回答

你真的应该清理你的代码,所有这些额外的空间伤害可读性。我建议使用PyLint(pip install pylintpylint file.py

我不会太重构你的代码,但是你需要在转换成一个float之前检查“done”。如果有人输入了无效的答案,您需要捕捉ValueErrors并优雅地处理它

print("Enter the homework scores one at a time. Type \"done\" when finished. Ctrl+c to quit at any time.")
hwCount = 1
totalScore = 0
try:
    while True:
        strScore = input("Enter HW#" + str(hwCount) + " score: ")
        if strScore == 'done':
            break #done
        else:
            try:
                strScore = float(strScore)
            except ValueError:
                print('Invalid input: must be a numerical score or "done"')
                continue
        if (strScore == int (strScore) and strScore >=0 and strScore <=10):
            totalScore = totalScore + (strScore)
            hwCount = hwCount + 1
        elif ( strScore == int (strScore) and( strScore < 0 or strScore > 10)):
            print ("Please enter a number between 0 and 10.")
        elif strScore != "done":
            print ("Please enter only whole numbers.")
except KeyboardInterrupt:
    pass #done

这是你的程序的一个更完整的版本,供参考。这就是我重构它的方式

#!/usr/bin/env python3

def findmode(lst):
    bucket = dict.fromkeys(lst, 0)
    for item in lst:
        bucket[item] += 1
    return max((k for k in bucket), key=lambda x: bucket[x])

print("Enter the homework scores one at a time.")
print("Type 'done' when finished or ctrl+c to quit.")
scores = []
try:
    while True:
        strScore = input("Enter score: ")
        if strScore == 'done':
            break #done
        else:
            try:
                strScore = int(strScore)
            except ValueError:
                print('Invalid input: must be a score or "done"')
                continue
        if (0 <= strScore <= 10):
            scores.append(strScore)
        else:
            print("Please enter a valid score between 0 and 10.")
except KeyboardInterrupt:
    pass # user wants to quit, ctrl+c
finally:
    print("Total scores graded: {}".format(len(scores)))
    print("Highest score: {}".format(max(scores)))
    print("Lowest score: {}".format(min(scores)))
    print("Mean score: {}".format(sum(scores)/len(scores)))
    print("Mode score: {}".format(findmode(scores)))

您可以立即将输入字符串转换为读字符串所在行上的浮点值:

strScore = float (input ( "Enter HW#" + str(hwCount) + " score: "))

为了接受“done”作为输入,您需要将其作为字符串保存,并在完成所有输入验证后将其转换为float(或int)

删除float(),strScore将是一个字符串。然后检查是否等于“完成”。最后,将其转换为try块中的整数

print ( "Enter the homework scores one at a time. Type \"done\" when finished." )
hwCount = 1
totalScore = 0
while True:
    strScore = input ( "Enter HW#" + str(hwCount) + " score: ")
    if strScore == "done":
        break
    try:
        intScore = int(strScore)
    except ValueError:
        print ("Please enter only whole numbers.")
        continue
    if (intScore >=0 and intScore <=10):
        totalScore += intScore
        hwCount += 1
    else:
        print ("Please enter a number between 0 and 10.")

相关问题 更多 >

    热门问题