gpt4 book ai didi

python - 使用基本的 python 计算器,但无法让我的菜单正确循环

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:01 25 4
gpt4 key购买 nike

多亏了这个网站,作为一个Python新手,我才能够走到这一步,但是我有点卡住了。我正在尝试循环“选择”,因此在用户进行一些数学运算后,而不是仅仅结束它,他们可以选择执行其他操作,直到他们选择 0 退出。我尝试了很多其他尝试和条件语句,但最终只得到答案并陷入无限循环。

另外,我在这里很漂亮,但感谢任何帮助,而且我也是一个 python nub。我正在用 python 2.7 写这篇文章,如果这很重要的话。

def sum ( arg1, arg2):
total = a + b
return total;

def subtract ( arg1 , arg2):
total = a - b
return total;

def mult ( arg1, arg2):
total = a * b
return total;

def division ( arg1, arg2):
total = (a / b)
return total;



options = ["1", "2", "3", "4", "5", "0"]

print ("Please choose an option for mathing")
print ("1 for addition")
print ("2 for division")
print ("3 for subtraction")
print ("4 for multiplication")
print ("5 ")
print ("0 to exit")


#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break

else:
print("Please choose a valid option")

#user input for mathing
#input will be validated as follows
a = None
while a is None:
try:
a = int(input("please provide a number for A"))
except ValueError:
print "please use a valid integer"
pass

b = None
while b is None:
try:
b = int(input("please provide a number for B"))
except ValueError:
print "please use a valid integer"
pass


#performing the operations

if selection == '1':
print "The sum is", str(sum(a, b))

elif selection == '2':
print "The quotient is", str(division(a, b))

elif selection == '3':
print "The difference is", str(subtract(a, b))

elif selection == '4':
print "The product is", str(mult(a, b))

elif selection == '0':
exit()

最佳答案

为了提高效率,我会做一些事情..

options 应该是一本字典...你的 in 在字典上比在列表上更有效。这样做的好处是每个键的值都可以是函数方法。

例如。 options = {1: '求和', 2: '减去' ..... }

然后创建一个包含数学运算的类

class Calculator(object):

def sum(self, x, y):
return x + y
def subtract(self, x, y):
return x - y

#add more operations here

@staticmethod
def start():
while True:
#prompt for input and the operator

这样做的好处是,在检查选择时,您可以动态调用类方法来清理大量代码

if selection in options:
getattr(options[selection], Calculator)(a, b)

如果你想让我解释更多,我可以完成这个例子。

对于循环,您可以添加一个方法来启动操作并继续循环并每次执行更多操作

这是一个基本类,您可以使用我描述的那些方法来使用

class Calculator(object):
loop = None
calculations = 1
current_value = 0
selection = 0
options = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide'}

def __init__(self, loop=True):
self.loop = loop
print 'Welcome to my basic calculator!'
if not self.loop: # dont loop just execute once
self.run()
else:
while True:
self.run()

@staticmethod
def add(x, y):
return x + y

@staticmethod
def subtract(x, y):
return x - y

@staticmethod
def multiply(x, y):
return x * y

@staticmethod
def divide(x, y):
if y != 0: #cant divide by 0
return x / y

@staticmethod
def quit():
exit(0)

def run(self):
if self.calculations == 1:
self.current_value = self.prompt_user_input('please provide a number: ')

self.prompt_operator('Please choose an operator to continue\n1 for addition\n2 for subtraction\n3 for multiplication \n4 for division\n0 to quit\n')
y = self.prompt_user_input('please provide a number: ')
self.current_value = getattr(Calculator, self.options[self.selection])(self.current_value,y)
self.calculations += 1

print 'New value is: ' + str(self.current_value)

def prompt_operator(self, prompt_message):
while True:
self.selection = input(prompt_message)
if self.selection in self.options:
break
elif self.selection == 0:
self.quit()
else:
print("Please choose a valid option")

def prompt_user_input(self, prompt_message):
val = None
while val is None:
try:
val = int(input(prompt_message))
except ValueError:
print "please use a valid integer"
pass
return val

最后,要启动计算器,您只需调用它并传递 true 继续循环或传递 false 只进行一次计算

Calculator(loop=True)

关于python - 使用基本的 python 计算器,但无法让我的菜单正确循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930039/

25 4 0