【问题标题】:I get an EOF error when running my code, what can i do?运行代码时出现 EOF 错误,我该怎么办?
【发布时间】:2022-11-13 07:21:19
【问题描述】:

基本上我有一个程序,你必须让老师耐心等待,然后数“一”、“二”、“三”、“四”、“一”等,当你失败时,它会写下“连胜是...... ,但你失败了”,耐心达到 0 后,老师说“今天够了”,然后忽略所有输入,但是当我收到这样的命令时:

2
one
two
three
four
one
twu
one
two
three
three

在某些情况下,我在启动它时会遇到 EOF 错误,即使我将所有需要的输入转换为整数。 代码:

patience = int(input())
a = input()
streak = 0
mistake = False
one = "one"
two = "two"
three = "three"
four = "four"
nextNum = one
while 1:
    if a == nextNum:
        mistake = False
        streak += 1
        if nextNum == one:
            nextNum = two
        elif nextNum == two:
            nextNum = three
        elif nextNum == three:
            nextNum = four
        elif nextNum == four:
            nextNum = one
    elif not mistake:
        mistake = True
        nextNum = one
        patience -= 1
        if patience == 0:
            print("The counting streak was " + str(streak) + ", but you failed.")
            print("Enough for today.")
        if patience >= 1:
            print("The counting streak was " + str(streak) + ", but you failed.")
        streak = 0
    a = input()

我不知道这里有什么问题,因为它就像一个随机的机会,我不明白为什么。

【问题讨论】:

  • 使用https://pythontutor.com/visualize.html#mode=edit 尝试您的代码,您会看到逐步执行时会发生什么。
  • 每位老师一开始有多少耐心?

标签: python eof


【解决方案1】:

原因

让我们看看while循环,当你第一次猜对时,变量mistake被设置为false。因此,如果您第二次猜错,mistake 将被设置为 true。第三次,如果您再次猜错,则不会发生任何事情。因为nextNum不相等到变量a,而mistake早些时候被设置为True。因此,不要使用elif,而是使用else。这样,如果没有正确猜到 nextNum,则运行 else case。

解决方案

我建议将elif not mistake: 更改为else:。 也不要忘记删除布尔变量mistake = 的其他三个引用,它只是一个不必要的行。

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    相关资源
    最近更新 更多