a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: ")) c=input("Enter the operator: ") n=0
def plus(a,b): n=a b print(n)
def minus(a,b): n=a-b print(n)
def multiply(a,b): n=a*b print(n)
def divide(a,b): n=a/b print(n)
if a%2==0: pass else: a =1
if b%2==0: b =1
if c==" ": d=a b plus(a,b) elif c=="-": d=a-b minus(a,b) elif c=="x" or "X": d=a*b multiply(a,b) elif c=="/": d=a/b divide(a,b) else: print("Input correct operator.")
print(d) if d==n: pass else: print("Oops, I didn't got right answer. Sorry for that, I am closing off.")
問題:
除法運算子不能正常作業。
無論計算是否正確,計算器最后一句都會列印出來。
uj5u.com熱心網友回復:
代碼中有兩個問題(好吧,代碼的格式也是一個問題。希望你只把它放在那個格式的問題中,如果不是請盡量縮進代碼,不要在一行中放置多個陳述句)
對于問題:它總是運行乘法選項,因為if陳述句是錯誤的。
而不是elif c=="x" or "X":你必須寫, elif c=="x" or c=="X":所以你錯過了在or子句中檢查的變數。
第二件事,您的變數n不會在函式內部更改。在函式內部,它定義了一個新的區域(函式的區域)變數,n如果你想改變外部變數,n你必須在每個改變n.
這是代碼:
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
c=input("Enter the operator: ")
n=0
def plus(a,b):
global n
n=a b
print(n)
def minus(a,b):
global n
n=a-b
print(n)
def multiply(a,b):
global n
n=a*b
print(n)
def divide(a,b):
global n
n=a/b
print(n)
if a%2==0:
pass
else:
a =1
if b%2==0:
b =1
print(a)
print(b)
if c==" ":
print("Plus")
d=a b
plus(a,b)
elif c=="-":
print("Minus")
d=a-b
minus(a,b)
elif c=="x" or "X":
print("Multiply")
d=a*b
multiply(a,b)
elif c=="/":
print("Divide")
d=a/b
divide(a,b)
else:
print("Input correct operator.")
if d==n:
pass
else:
print("Oops, I didn't got right answer. Sorry for that, I am closing off.")
uj5u.com熱心網友回復:
如果你除錯一次,你會注意到變數 n 的值直到程式結束才改變。原因是n只改變了每個函式的作用域,而對全域變數n的改變并沒有做!
要更改函式中的全域變數,請執行以下操作:
n=0
def plus(a,b):
global n
n=a b
print(n)
在每個函式的開頭,宣告 n 是全域變數 n。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/397560.html
