我知道這應該是非常簡單的,但在這一點上,我在智慧的結尾試圖弄清楚這一點。我已經在python中編寫了一個計算器,但由於某種原因,結尾if-else語句只會觸發else段。Python:如果條件似乎得到滿足,但沒有觸發
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x/y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator (+ - * /)."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
當我運行這段代碼,我得到兩個不同的問題: 如果我輸入一個有效的輸入(即:2 + 2),那麼我的輸出是
「2 + 2 = 4.0」
「2 + 2 = 4.0」
「2 + 2 = 4.0」
重複下去。
如果我輸入一個無效的輸入,我得到「再次播放?」提示,但不管輸入什麼,else語句都會觸發。 (例如,如果我在「再次播放?」中輸入「是」,則會打印: 「是」(< - 來自「再次打印」行) 「沒有」(< - 這是來自「其他:打印‘no'd’)
我不知道如何解決這些問題之一,在這一點上,所以任何幫助,將不勝感激
編輯:謝謝大家。 ,我希望我能查馬克大家幫助我理解關於我做錯了什麼不同的事情。