【问题标题】:My first program我的第一个程序
【发布时间】:2013-12-26 03:53:53
【问题描述】:

我在 Code Academy 上做了很多课程,但我感到很沮丧,因为一些编译器拒绝返回相同结果的答案。因此,我决定暂时脱离并使用我所学的计算器工具创建自己的程序。它不能正确运行。当它在菜单中时,if/elif/else 语句不起作用。该程序似乎忽略了输入。所以,这是我的第一个程序代码...

import math
user_choice=(">>")
def add():
    print "What two numbers would you like to add?"
    a= int(raw_input(user_choice))                     
    b= int(raw_input(user_choice))
    c= a + b
    print c
def sub():
    print "What two numbers would you like to subtract?"
    a=int(raw_input(user_choice))
    b=int(raw_input(user_choice))
    c=a-b
    print c
def mult():
    print "What two numbers would you like to multiply?"
    a=int(raw_input(user_choice))
    b=int(raw_input(user_choice))
    c= a*b
    print c
def div():
    print "What two numbers would you like to divide?"
    a=int(raw_input(user_choice))
    b=int(raw_input(user_choice))
    c=a/b
    print c
def exp():
    print "What number would you like to power?"
    a=int(raw_input(user_choice))
    print "By what number would you like it to be powered to?"
    b=int(raw_input(user_choice))
    c= math.pow(a,b)
    print  c
def square():
    print "What number would you like to square root?"
    a=int(raw_input(user_choice))
    b=math.sqrt(a)
    print b

print "+---------------------------+"   
print "|   Welcome to my basic     |"
print "|    calculator!         |"
print "|                           |"
print "|What would you like to do? |"
print "|                |"
print "|1: Addition         |"
print "|2: Subtraction          |"
print "|3: Multiplication       |"
print "|4: Division         |"
print "|5: Exponents            |"
print "|6: Square Root          |"
print "|7: Quit         |"
print "|                           |"
print "+---------------------------+"

if int(raw_input(user_choice)) ==  "1":
     add()

elif int(raw_input(user_choice)) == "2":
     sub()

elif int(raw_input(user_choice)) == "3":
     mult()

elif int(raw_input(user_choice)) == "4":
     div()

elif int(raw_input(user_choice)) == "5":
     exp()

elif int(raw_input(user_choice)) == "6":
     square()

elif int(raw_input(user_choice)) == "7":
     exit()

else:
    print "Sorry, I didn't understand your entry.Try entering a value 1-7"

目前还没有“如果错误”代码,但我只是坚持让它工作。所有功能都有效。只是无法使选项起作用。

【问题讨论】:

  • 您应该检查之前请求用户输入...每次在主代码中检查条件时,您都在请求用户输入。此外,字符串!= ints。
  • if int(raw_input(user_choice)) == "1": 在将输入转换为int 时,应直接与int 进行比较
  • 一旦您解决了 Paul 在下面指出的问题,您可能希望将此代码发送到 codereview.stackexchange.com 并获得一些建议,了解如何最大限度地减少您拥有的条件数量并允许更多功能

标签: python if-statement calculator


【解决方案1】:

int(rawinput()) 将返回一个integer,而不是== 到像"1" 这样的字符串。从它们中删除int(),它应该可以工作。

【讨论】:

    【解决方案2】:

    改变

    if int(raw_input(user_choice)) ==  "1":
    

    if int(raw_input(user_choice)) ==  1:
    

    数字不应该被引用,只有文字字符串应该。
    一个建议,可以只获取一次输入,然后做 if/elif/else 条件测试,例如:

    option = int(raw_input(user_choice))
    print "You choose %d" % option
    
    if option == 1:
        add()
    elif option == 2:
        sub()
    ......
    

    【讨论】:

      【解决方案3】:

      除了其他人指出的事情之外,我将在这里留下我个人将如何实施它。这肯定不是最好的方法,但我希望它能给你一些想法(你会采用或拒绝)以及一些你可以进一步调查以扩展你的 Python 技能的点:

      class Operation:
          def __init__(self, f, argc):
              #f is the function to use, argc the number of arguments it takes
              self.f = f
              self.argc = argc
      
          def __call__(self):
              #read in the args
              args = [int(input('>> ')) for _ in range (self.argc)]
              #print out the result of the function passed in the ctor
              print(self.f(*args))
      
      #your operations keyed to the options of your menu
      operations = {'1': Operation(lambda a, b: a + b, 2),
                    '2': Operation(lambda a, b: a - b, 2),
                    '3': Operation(lambda a, b: a * b, 2),
                    '4': Operation(lambda a, b: a / b, 2),
                    '5': Operation(lambda a, b: a ** b, 2),
                    '6': Operation(lambda a: a ** .5, 1)}
      
      while True:
          print('''
      1: Addition
      2: Subtraction
      3: Multiplication
      4: Division
      5: Exponentiation
      6: Square root
      7: Quit''')
          choice = input('Your choice: ') #raw_input for py2
          if choice == '7': break
          try: operations[choice]()
          #KeyError means choice is not in the dict
          except KeyError: print('Unkown option')
          #Something else went wrong, division by zero, etc
          except Exception as e: print('Something went horribly wrong: {}'.format(e))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2012-05-08
        • 2014-06-13
        • 2018-12-08
        • 2016-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多