猜拳游戏未按预期工作
我想快速做一个简单的游戏,就是大家都知道的石头剪刀布,因为我刚在学习编程。我在Python的命令行里把它做成功了,但当我把代码重新输入到一个网站的代码测试器里时,它一直提示我有个EOFError
的错误,并且说问题出在if
语句的第3行。
这是我的代码:
import random
foe = random.randint(1, 3)
you = int(input("pick 1-3"))
print(you)
if you == foe:
print("it's a tie")
elif you > foe:
try:
print("checking for special conditions")
except:
if you == 3 and foe == 1:
print("you lose")
else:
print("you win")
finally:
print("complete")
else:
try:
print("checking for special conditions")
except:
if you == 1 and foe == 3:
print("you win")
else:
print("you lose")
finally:
print("complete")
这些代码在命令行里都能正常工作,我不明白为什么在这里就不行了。
顺便说一下:我13岁,是通过一个叫code-bullet的视频开始接触编程的。
我去那个地方看到了很多人有同样的问题,我查看了一些解决方案,想着能解决我的问题,但结果只是出现了另一个错误。我最后删掉了那行代码,但我不知道if
语句到底哪里出错了。
1 个回答
0
下面是你代码的一些改进建议(有位热心的社区成员已经把问题中的代码格式化了)。我可以确认在我的机器上用Python 3.11运行是没问题的。不过我不能保证它能在某些在线代码评估网站上运行。理论上应该没问题,但你需要自己试一下。
我对输入做了一些处理,确保它总是在1到3之间,包括1和3。否则,如果输入一个大于3的数字,就太容易作弊了。
此外,我去掉了所有多余的try..except..else..finally
语句。这些并不会让你的代码更快,也不是安全措施。其实这是逻辑错误。在这种情况下,你只需要用if..else
就可以了。它们的区别如下:
try:
# a statement that may raise an exception to signal an error
# no, print() is not one of them
except:
# catch the exception and do something to mitigate the error
else:
# do something if no exception occurred, i.e. there was no error
finally:
# do something regardless of whether there was an error or not
而且即使在“严肃”的程序中,我们也很少需要用到所有这些。
在你原来的代码中,这意味着:
try:
print("checking for special conditions")
# no exception, let's skip the "except" block
except:
# we never get here because there was no exception
# the code below is never executed
if you == 3 and foe == 1:
print("you lose")
else:
# always jump here, we always win, huzzah!
print("you win")
finally:
# jump here and print "complete"
print("complete")
你应该做的是使用一个简单的条件表达式,当条件满足时执行if
的部分,否则执行else
的部分。
import random
foe = random.randint(1, 3)
you = int(input("pick 1-3 "))
# make sure the input is between 1 and 3
if you < 1:
you = 1
elif you > 3:
you = 3
print(you)
if you == foe:
print("it's a tie")
elif you > foe:
print("checking for special conditions")
if you == 3 and foe == 1:
print("you lose")
else:
print("you win")
else:
print("checking for special conditions")
if you == 1 and foe == 3:
print("you win")
else:
print("you lose")
print("complete")
你的程序还有更多可以改进的地方。你可以自己动手试试,看看会有什么变化。