【问题标题】:Trouble with input trap (Among other things)输入陷阱问题(除其他外)
【发布时间】:2016-11-11 19:43:35
【问题描述】:

所以我又来了,一如既往地一无所知。我有点新手,所以这可能比我能咀嚼的更多,但无论如何。 该程序的重​​点是根据用户的输入值提供输出。如果用户没有输入正确的输入,它的目的是实现输入陷阱。

我正在尝试使输入字母或非整数值导致消息“请仅输入整数”。它适用于浮点数,但不适用于字母。我应该注意到“输入 0 到 10 之间的数字”消息工作正常。 此外,当用户输入“完成”时,循环应该关闭,但这只会导致 “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

【问题讨论】:

  • 当用户输入done 时,您希望float(input(..)) 如何工作?当您期望输入可能不是浮点数时,不要立即转换为float!先检查是不是done

标签: python while-loop


【解决方案1】:

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

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

为了接受“完成”作为输入,您需要将其保留为字符串,并在完成所有输入验证后将其转换为浮点(或整数)。

drop 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.")

【讨论】:

  • 好吧,太棒了。那样的话,我该怎么写呢?
  • @Liam 我根据你的例子添加了一个建议
【解决方案2】:

你真的应该清理你的代码,所有这些额外的空格都会损害可读性。我建议使用 PyLint (pip install pylint, pylint 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)))

【讨论】:

  • 很高兴知道。我将通过编码来处理我的间距。非常感谢。
  • @Liam 我已经稍微重构了代码并发布了我可能会如何构建程序。认为这将是您学习的好机会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
相关资源
最近更新 更多