python中的ValueError异常
我最近开始尝试学习如何编码,我很兴奋我正在组装一个超级基本的计算器,但我已经把自己陷入了一个我不知道如何摆脱的角落,主要是由于我缺乏知识。我正在使用 try: except: 块来阻止人们输入字母,但这样做会阻止我输入 q 来退出。
answer = 0
while True:
print(f"Give me a number: (Saved Value: {answer})\n('q' to quit)")
try:
num1 = float(input("> "))
except ValueError:
if num1 == 'q':
break
else:
print("Numbers only please!\n")
continue
print(f"Give me another number: (Saved Value: {answer})\n('q' to quit)")
try:
num2 = float(input("> "))
except ValueError:
if num2 == 'q':
break
else:
print("Numbers only please!\n")
continue
print(f"Give me an operator: (+, -, /, *) (Saved Value: {answer})\n('q' to quit)")
my_math = input("> ")
if my_math == 'q':
break
if my_math == '+':
print(num1 + num2)
answer = num1 + num2
answer = answer
elif my_math == '-':
print(num1 - num2)
answer = num1 - num2
answer = answer
elif my_math == '/':
print(num1 / num2)
answer = num1 / num2
answer = answer
elif my_math == '*':
print(num1 * num2)
answer = num1 * num2
answer = answer
I recently started trying to learn how to code and I was excited that I was putting together a super basic calculator, but I have painted myself into a corner that I do not know how to get out of, due mainly to my lack of knowledge. I am using the try: except: block to prevent people from typing in letters but doing so prevents me from being able to type q to quit.
answer = 0
while True:
print(f"Give me a number: (Saved Value: {answer})\n('q' to quit)")
try:
num1 = float(input("> "))
except ValueError:
if num1 == 'q':
break
else:
print("Numbers only please!\n")
continue
print(f"Give me another number: (Saved Value: {answer})\n('q' to quit)")
try:
num2 = float(input("> "))
except ValueError:
if num2 == 'q':
break
else:
print("Numbers only please!\n")
continue
print(f"Give me an operator: (+, -, /, *) (Saved Value: {answer})\n('q' to quit)")
my_math = input("> ")
if my_math == 'q':
break
if my_math == '+':
print(num1 + num2)
answer = num1 + num2
answer = answer
elif my_math == '-':
print(num1 - num2)
answer = num1 - num2
answer = answer
elif my_math == '/':
print(num1 / num2)
answer = num1 / num2
answer = answer
elif my_math == '*':
print(num1 * num2)
answer = num1 * num2
answer = answer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么这应该按您的预期工作。
如果您将两次出现的 都缩进以与
if
语句保持一致,This should work as you intended if you indent both occurrences of
to be in line with the
if
statements.