【发布时间】:2016-01-22 22:22:26
【问题描述】:
我知道这看起来应该很简单,但在这一点上,我无计可施,试图弄清楚这一点。我在 python 中编写了一个计算器,但由于某种原因,结束 if-else 语句只触发了 else 段。
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 语句都会触发。 (例如,如果我在“再次播放?”中输入“是”,它将打印: “是”(
目前我不知道如何解决这两个问题,因此非常感谢任何帮助。
编辑:谢谢大家,我希望我能对你们所有人进行检查,以帮助我理解我做错的不同方面。
【问题讨论】:
标签: python if-statement infinite-loop