python-3.x - 需要一些关于遵循 python 3 代码的见解
问题描述
我试图构建这个基本代码是为了好玩,但我遇到了一些奇怪的错误。下面的代码要求一个基本的打印方程的答案。当答案是 10 或更大时,它的行为很奇怪。我尝试实现一些错误处理方法(我猜失败在 int(ansr_raw) 处)。我认为更好的方法会帮助我。您无需为我拼出代码,但为我指出正确的方向会很有帮助。代码和输出如下所示。
代码 -
import random
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
while True:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
else:
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
break
elif choice in 'no':
continue
else:
print("Wrong choice. continuing game.")
continue
print('answer format invalid')
continue
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
这是输出(添加了箭头标记)-
9 + 3 = ?
Enter the answer: 12
answer format invalid <----
2 - 9 = ?
Enter the answer: 5
wrong answer.
1 - 3 = ?
Enter the answer: 2
Right Answer.
8 + 3 = ?
Enter the answer: 11
answer format invalid <----
1 + 2 = ?
Enter the answer: 3
Right Answer.
6 + 2 = ?
Enter the answer:
解决方案
问题是你说的地方
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
对于像 9 这样的单个数字,是的,该字符串中有一个 9,但只有几个两位数(01、23、34、45、56、67、78、89),你想要做,检查字符串是否可以变成整数;做这个。
try:
ansr = int(ansr_raw)
except ValueError:
完整代码:
import random
import sys
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
running = True
while running:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
try:
ansr = int(ansr_raw)
except ValueError:
answerInv = True
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
sys.exit(0)
elif choice in 'no':
continue
answerInv = False
else:
print("Wrong choice. continuing game.")
answerInv = False
continue
if answerInv:
print('answer format invalid')
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
推荐阅读
- java - JAVA SWING ICEPDF pdf未显示全部内容
- javascript - 如何在不实际应用它们的情况下交付 2 个带导轨的 css
- python - 根据含义相等字符串
- apache - 对服务器的每个请求执行 php 脚本
- wireshark - 从wireshark解码数据包中的特定字段访问数据的最佳方法是什么
- reactjs - 如何将数据从 graphql 传递到另一个页面?
- javascript - 续集日期范围之间的查询(createdAt)
- css - SVG“矢量效果:非缩放笔画”在
: 火狐与 Chrome - flutter - onPressed 在 Flutter 中创建多个 CheckboxListTile 实例
- vue.js - Vue:拥有依赖于 Vuex 存储属性的组件的最佳 Vuex 实践