输入陷阱的麻烦(除其他外)

时间:2016-11-11 19:43:36

标签: python while-loop

所以我再一次,一如既往的无能为力。我有点像新手,所以这可能比我能咀嚼的多,但无论如何。 该程序的要点是根据用户的输入值提供输出。如果用户没有输入正确的输入,则意味着实现输入陷阱。

我试图这样做,所以输入一个字母或一个非整数值会导致消息"请只输入整数。"它适用于浮点,但不适用于字母。我应该注意"输入0到10之间的数字"消息工作正常。 此外,当用户输入“完成”时,循环应该关闭,但这只会导致" ValueError:无法将字符串转换为浮点数:'已完成' ;" 即可。

我还没有用True格式写这个,因为我更容易在循环中坚持使用这种写法。

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

2 个答案:

答案 0 :(得分:0)

您可以立即将输入字符串转换为您读取它的同一行上的浮点数:

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

为了接受&#34;完成&#34;作为输入,您需要将其保留为字符串,并在完成所有输入验证后将其转换为float(或int)。

drop float()和strScore将是一个字符串。然后检查它是否等于&#34;完成&#34;。最后,将其转换为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.")

答案 1 :(得分:0)

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

我不会过多地重构您的代码,但您需要检查“已完成”代码。在转换为浮动之前。如果有人输入无效的答案并优雅地处理它,你就会想要捕获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)))