Python 3 中的 Else 语句始终运行 [英] Else statement in Python 3 always runs
本文介绍了Python 3 中的 Else 语句始终运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在用 Python 制作一个基本的计算器,但我遇到了这个问题.计算完成后,总是打印无效数字",然后暂停.我认为这与打破 if 块的换行符有关,但我不确定.
I've been making a basic calculator with Python and I have come across this issue. After the calculations are made "Invalid Number" always prints and then the pause happens. I think it has something to do with the newline breaking the if block but I'm not sure.
任何帮助将不胜感激.提前致谢.
Any help will be appreciated. Thanks in advance.
def badnum():
print("Invalid Number")
print("Press enter to continue")
input("")
def main():
print("Select an action ")
print("1.) Add")
print("2.) Subtract")
print("3.) Multiply")
print("4.) Divide")
ac = int(input(">>>"))
if ac == 1:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn+sn
print(a)
if ac == 2:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn-sn
print(a)
if ac == 3:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn*sn
print(a)
if ac == 4:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn/sn
print(a)
else:
badnum()
print("
"*100)
while True:
try:
main()
except ValueError:
badnum()
except ZeroDivisionError:
print("Infinity")
print("
"*100)
推荐答案
不,这与您编写代码的方式有关,请考虑使用 if...elif
:
No, it has got something to do with how you have written your code, consider this with if...elif
:
ac = int(input(">>>"))
if ac == 1:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn+sn
print(a)
elif ac == 2:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn-sn
print(a)
elif ac == 3:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn*sn
print(a)
elif ac == 4:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn/sn
print(a)
else:
badnum()
<小时>解释:之前,您正在检查 ac == 1
和 ac == 4
不能同时为真,所以第二个 else
语句也被执行了.这可以通过 if..elif
结构省略:一旦较早的比较之一变为真,其余的就不再执行.
Explanation: Before, you were checking for
ac == 1
and ac == 4
which cannot both be true, so the second else
statement was executed as well. This can be omitted with the if..elif
construction: once, one of the earlier comparisons become true, the rest is not executed anymore.
这篇关于Python 3 中的 Else 语句始终运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文