基本python计算器中的函数出现问题,不确定如何修复
我对编程相当陌生,想做一个简单的计算器作为练习,但我似乎无法得到一个函数以我想要的方式工作,我确信这是因为我遗漏了一些东西,但我不确定到底是什么。我试图寻找一些答案,但我要么不太理解,要么不知道如何实现它。在我编写的代码中,如果我删除ask()并将其替换为我定义为的代码,它会工作,但当我使用ask()时,它不会工作,并给出一个错误,指出“未定义名称“x”。任何帮助,以及任何提示或方法,我可以改善这一点表示感谢。提前谢谢基本python计算器中的函数出现问题,不确定如何修复,python,function,calculator,Python,Function,Calculator,我对编程相当陌生,想做一个简单的计算器作为练习,但我似乎无法得到一个函数以我想要的方式工作,我确信这是因为我遗漏了一些东西,但我不确定到底是什么。我试图寻找一些答案,但我要么不太理解,要么不知道如何实现它。在我编写的代码中,如果我删除ask()并将其替换为我定义为的代码,它会工作,但当我使用ask()时,它不会工作,并给出一个错误,指出“未定义名称“x”。任何帮助,以及任何提示或方法,我可以改善这一点表示感谢。提前谢谢 def Add(x, y): print("Addi
def Add(x, y):
print("Adding %d and %d" % (x, y))
print("Answer:", x + y)
def Subtract(x, y):
print("Subtracting %d from %d" % (y, x))
print("Answer:", x - y)
def Multiply(x, y):
print("Multiplying %d and %d" % (x, y))
print("Answer:", x * y)
def Divide(x, y):
print("Dividing %d from %d" % (y, x))
print("Answer:", x / y)
def ask():
print("Which two numbers would you like to use?")
x = input(">")
y = input(">")
print("Would you like to (a)dd, (s)ubtract, (m)ultiply, or (d)ivide two numbers?")
op = input(">")
if op == "a":
ask()
Add(x, y)
elif op == "s":
ask()
Subtract(x, y)
elif op == "m":
ask()
Multiply(x, y)
elif op == "d":
ask()
Divide(x, y)
else:
print("I don't know what that means.")
print("\n")
您应该返回这些值,还应该将它们转换为
float
或任何您想要的值,以便对它们执行数字运算
def ask():
print("Which two numbers would you like to use?")
x = float(input(">"))
y = float(input(">"))
return (x,y)
然后可以从函数中获取返回的值,如
if op == "a":
x,y = ask()
Add(x, y)
除了你手头的问题之外,我能提出一些建议吗
在处理之前,需要将用户输入解析为int。另外,
ask
需要返回用户输入。虽然这比您可能想要的要多,但希望您可以将其用作进一步编码的模板。感谢您的帮助和建议,我以后一定会记住这些。这是一个很好的解决方案,但您应该解释为什么必须这样做。
# use these as templates
str_fun_cal = "{}: {} with {}"
str_res = "Answer: {}"
# Look at the cleanliness of this!!!!
# Also these actually do what they say they do instead of just printing the result out. Useful for further
# functionality
def Add(x, y):
return x + y
def Subtract(x, y):
return x - y
def Multiply(x, y):
return x * y
def Divide(x, y):
return x / y
# use a dictionary to select the function the user calls
func_call_dict = {'a':Add, 's':Subtract, 'm':Multiply, 'd':Divide}
# Fixed an issue with not returning any values
def ask():
print("Which two numbers would you like to use?")
in_x = float(input(">"))
in_y = float(input(">"))
return in_x, in_y
# Printing function to clean things up
def print_fun(fun_call, x, y, res):
print(str_fun_cal.format(fun_call, x, y))
print(str_res.format(res))
print("Would you like to (a)dd, (s)ubtract, (m)ultiply, or (d)ivide two numbers?")
op = input(">")
# check to see if in dictionary, if so then execute the corresponding function if not, display error
if op in func_call_dict:
x, y = ask()
sel_fun = func_call_dict[op]
calc_val = sel_fun(x, y)
print_fun(sel_fun.__name__, x, y, calc_val) # use of `.__name__` returns the name of the function (Add, Subtract, etc,.)
else:
print("I don't know what that means.")
print("\n")