繁体   English   中英

我在 function 错误之外返回时遇到问题

[英]Im having trouble with a return outside of function error

我正在为我的功能使用导入。 我一直在我的代码中获得 function 之外的回报我是 python 的新手。我绞尽脑汁试图找出问题所在。 我知道这可能像缩进一样简单,但我似乎无法弄清楚。 任何帮助将不胜感激。 我缩进了所有函数,但仍然出现错误。 对不起,如果我看起来很笨,我已经缩进了所有内容,但仍然没有任何效果。

class calculatorClass:

    def add(self, a, b):
        return a + b

    # This function subtracts two numbers
    def subtract(self, a, b):
        return a - b

    # This function multiplies two numbers
    def multiply(self, a, b):
        return a * b

    # This function divides two numbers
    # The ZeroDivisionError exception is raised when division or modulo by zero takes place for all numeric types
    def divide(self, a, b):
        try:
            return a / b
        # This exception will be raised when the user attempts division by zero
        # Implemented here so if the users input is '0' it will display error that you can't divide by zero
        except ZeroDivisionError:
            print("Error: Cannot divide by zero!")


calc = calculatorClass()


# This function allows for string manipulation

def scalc(self, p1):
    string1 = p1.split(",")
    if string1[2] == "+":
        result = calc.add(float(string1[0]), float(string1[1]))
    elif string1[2] == "-":
        result = calc.subtract(float(string1[0]), float(string1[1]))
    elif string1[2] == "*":
        result = calc.multiply(float(string1[0]), float(string1[1]))
    elif string1[2] == "/":
        result = calc.divide(float(string1[0]), float(string1[1]))
    else:
        result = 0
    return result


# This function returns the results of input values in addition, subtraction, multiplication and division
def AllInOne(self, a, b):
    add = a + b
    subtract = a - b
    multiply = a * b
    divide = a / b

    print('res is dictionary', {"add": add, "sub": subtract, "mult": multiply, "div": divide})
    return {"add": add, "sub": subtract, "mult": multiply, "div": divide}
from Mylib import add, subtract, multiply, divide, AllInOne, scalc


def main():
   print("\nWelcome to Calculator!\n")
calculatorObj = calculatorClass()

menuList = ["1) Addition", "2) Subtraction", "3) Multiplication", "4) Division", "5) Scalc", "6) AllInOne",
"0) Exit\n"]
# Takes user input to proceed with selected math operations
while True:
   try:
      print("Please enter your choice to perform a math operation: ")
      for n in menuList:
         print(n)
         menuChoice = int(input("Please input your selection then press ENTER: "))
      if menuChoice == 0:
            print("Goodbye!")
            return
# Checks users input against available options in menu list, if not user is notified to try again.
      if menuChoice > 6 or menuChoice < 0:
         print("\nNot a valid selection from the menu!"
"\nTry again! ")
      main()
# This exception will be raised if the users input is not the valid data expected in this argument.
   except ValueError:
      print("\nError!! Only integer values, Please try again!")

   main()
# User input to determine input of range a user can work with
   print("Please enter a value for low & high range between -100 & 100")
   lowRange = int(input("Enter your low range: "))
if lowRange < -100 or lowRange > 100:
      print("Error: ensure input doesn't exceed range of -100 to 100")

break
highRange = int(input("Enter your high range: "))
if highRange < -100 or highRange > 100:
   print("Error: ensure input doesn't exceed range of -100 to 100")

break
# Takes user input to perform math operations with input value
firstNum = float(input("Enter your first number: "))
secondNum = float(input("Enter your second number: "))
# Checks users input value is within the given ranges
while True:
   if firstNum < lowRange or firstNum > highRange:
      print("Error: first number input exceeds ranges, try again!")

break
if secondNum < lowRange or secondNum > highRange:
   print("Error: second number input exceeds ranges, try again!")

break
# Computes math calculations based on users menu selection
if menuChoice == 1:
   print(firstNum, '+', secondNum, '=', calculatorObj.addition(firstNum, secondNum))
elif menuChoice == 2:
   print(firstNum, '-', secondNum, '=', calculatorObj.subtraction(firstNum, secondNum))
elif menuChoice == 3:
   print(firstNum, '*', secondNum, '=', calculatorObj.multiplication(firstNum, secondNum))
elif menuChoice == 4:
   print(firstNum, '/', secondNum, '=', calculatorObj.division(firstNum, secondNum))
elif menuChoice == 5:
   print('The result of ', firstNum, '+', secondNum, '=', calculatorObj.scalc(str(firstNum) + ','
   + str(secondNum) + ',+'))
   print('The result of ', firstNum, '-', secondNum, '=', calculatorObj.scalc(str(firstNum) + ' ,'
   + str(secondNum) + ',-'))
   print('The result of ', firstNum, '*', secondNum, '=', calculatorObj.scalc(str(firstNum) + ', '
   + str(secondNum) + ',*'))
   print('The result of ', firstNum, '/', secondNum, '=', calculatorObj.scalc(str(firstNum) + ', '
   + str(secondNum) + ',/'))
elif menuChoice == 6:
   res = calculatorObj.allInOne(firstNum, secondNum)
   print(str(firstNum) + " + " + str(secondNum) + " = " + str(res["add"]))
   print(str(firstNum) + " - " + str(secondNum) + " = " + str(res["sub"]))
   print(str(firstNum) + " * " + str(secondNum) + " = " + str(res["mult"]))
   print(str(firstNum) + " / " + str(secondNum) + " = " + str(res["div"]))

# This will ask the user if they want to us the calculator again
while True:
   reCalculate = input("\nWould you like to try another operation? (y/n): ")
if reCalculate == 'Y' or reCalculate == 'y':
   print()


else:
      print("\nThanks for using calculator! "
      "\nGoodbye!")
return

main()



这是正确的缩进代码

class calculatorClass:

    def add(self, a, b):
        return a + b

    # This function subtracts two numbers
    def subtract(self, a, b):
        return a - b

    # This function multiplies two numbers
    def multiply(self, a, b):
        return a * b

    # This function divides two numbers
    # The ZeroDivisionError exception is raised when division or modulo by zero takes place for all numeric types
    def divide(self, a, b):
        try:
            return a / b
        # This exception will be raised when the user attempts division by zero
        # Implemented here so if the users input is '0' it will display error that you can't divide by zero
        except ZeroDivisionError:
            print("Error: Cannot divide by zero!")


calc = calculatorClass()


# This function allows for string manipulation

def scalc(self, p1):
    string1 = p1.split(",")
    if string1[2] == "+":
        result = calc.add(float(string1[0]), float(string1[1]))
    elif string1[2] == "-":
        result = calc.subtract(float(string1[0]), float(string1[1]))
    elif string1[2] == "*":
        result = calc.multiply(float(string1[0]), float(string1[1]))
    elif string1[2] == "/":
        result = calc.divide(float(string1[0]), float(string1[1]))
    else:
        result = 0
    return result


# This function returns the results of input values in addition, subtraction, multiplication and division
def AllInOne(self, a, b):
    add = a + b
    subtract = a - b
    multiply = a * b
    divide = a / b

    print('res is dictionary', {"add": add, "sub": subtract, "mult": multiply, "div": divide})
    return {"add": add, "sub": subtract, "mult": multiply, "div": divide}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM