Python程序查询1

Python程序查询1,python,Python,我刚刚写了几行代码,下面是一行: def fun(x,y): op=input("Please enter the operator: ") if op=='*': y=y*x if op=='+': y=y+x if op=='-': y=x-y if op=='/': y=x/y return y for n in range(1,999): if n==1:

我刚刚写了几行代码,下面是一行:

def fun(x,y):
    op=input("Please enter the operator: ")
    if op=='*':
        y=y*x
    if op=='+':
        y=y+x
    if op=='-':
        y=x-y
    if op=='/':
        y=x/y
    return y


for n in range(1,999):
    if n==1:
        try:
            a=int(input("Please enter the value 1: "))
            b=int(input("Please enter the value 2: "))

            if a not in ('*','/','+','-') or b not in ('*','/','+','-'):
                f=fun(a,b)
                break
        except:
            print("Please enter the proper number")

        print(f)            
f的值没有打印出来,即使我已经给出了正确的输入。这是因为exception子句。如果是这样,当在try/except子句中定义值时,我们应该如何在外部打印这些值

下面是显示的输出

Please enter the value 1: 1

Please enter the value 2: 2

Please enter the operator: *
只要将print(f)命令从for循环中拉出,它就可以工作:

for n in range(1,999):
    ...

print(f)

您在执行
if
语句之后立即调用
fun
,之后执行
break
语句。这使控制脱离了循环

然而,
print
就在循环中

因此,不执行
打印

我认为你不需要这个

if a not in ('*','/','+','-') or b not in ('*','/','+','-'):
a
b
都是整数,为什么要将它们与字符串进行比较

如果有
break
语句,循环将只执行一次以获得正确的输入

差不多

for n in range(1,999):
        try:
            a=int(input("Please enter the value 1: "))
            b=int(input("Please enter the value 2: "))

            f=fun(a,b)

        except:
            print("Please enter the proper number")
            break

        print(f)  

在得到一个运算符后,您正在跳出for循环。。您不需要测试所有这些运算符(
a不在(…)
,等等),因为
a
b
在该阶段保证是整数。@Sayse同意,删除
中断符
。只需使用
a=int(输入(…)
b=int(输入(…))
f=fun(a,b)
。不要捕获所有异常,只捕获
ValueError
或者
ZeroDivisionError
,这样你仍然可以使用CTRL-C来结束你的程序。也许你这样做只是为了调试原因,或者是因为捕获全部而无法结束你的循环/程序,但是有一个循环,并且只在一次迭代中做一些事情(
如果n==1
)没有什么意义。“它起作用”取决于op对代码的期望,如果他们只想用2个数字进行数学运算,他们也可以删除for循环