Python 3中的其他语句始终运行 [英] Else statement in Python 3 always runs
本文介绍了Python 3中的其他语句始终运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在用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("\n"*100)
while True:
try:
main()
except ValueError:
badnum()
except ZeroDivisionError:
print("Infinity")
print("\n"*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中的其他语句始终运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文