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

Working on a basic python calculator and can't get my menu to loop properly

多亏了这个网站,我才能够走到这一步,作为 python 的新手,我有点卡住了。我正在尝试循环 'selection',因此在用户进行一些数学运算后,而不是仅仅结束它会让他们选择做其他事情,直到他们 select 0 退出。我尝试了一堆其他的 try 和条件语句,但最终得到了答案,因此陷入了无限循环。

此外,我在这里很漂亮,但任何帮助都将不胜感激,而且我是一个 python 小人。如果重要的话,我正在用 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()
#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:
        if selection == 1:
           sum()
        if selection == 2:
           subtract()  
          .....
         if selection == 'q'
              break            

将逻辑更改为我上面所做的,对于选项,采取一些操作并在退出字符上中断/

只需围绕提示和计算进行循环即可。如果他们输入 0,则从最外层循环中断:

while True: 
    #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")                

    if selection == '0':
        break

    ...

首先,您的代码不能像现在这样工作:

if selection == '1':  #should return false

那是因为使用 input 你是在获取一个数字数量,然后将它与一个字符串进行比较。

selectioninput改为raw_input

或者像下面这样更改条件语句:

if selection == 1: 

然后在整个执行块上添加一个while True,一遍又一遍地执行,直到选择0。

我会做一些事情来提高效率..

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

例如。 options = {1: 'sum', 2: 'subtract' ..... }

然后用你的数学运算做一个class

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

这有什么好处是在您检查选择时您可以动态调用 class 方法来大量清理代码

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

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

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

这是一个基本的class你可以使用我描述的那些方法

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)