基本计算器,多种输入和功能选择

basic calculator, multiple input and choice through functions

正如您从我的代码中看出的那样,我想制作一个基本的计算器,系统会先询问您要做什么,然后要求您输入 2 个数字以由代码计算出。我遇到了一个问题,代码 returns 什么都没有,甚至没有尝试使用它应该使用的功能。

##Simple Calculator program##
print("Welcome to my basic calculator program")

print("In this program you will be asked to input what function you want to do then")
print("select 2 numbers, where the program will then do the mathematic operation on those 2 numbers")
#Class containing the functions and basic caluclation
 
class calculator_class():
    print("Please select a function by entering these :")
    print("Addition")
    print("Subtraction")
    print("Multiplication")
    print("Division")
    #this is a function which asks the user to choose what operator to choose before choosing their number
    
    def userchoice():
        
        userchoices = str(input())
        if userchoices in ["Addition","Subtraction","Multiplication","Division"]:
            return(
        
        
        if userchoices == "Addition":
            print(addition())
        elif userchoices == "Subtraction":
            print(subtraction())
        elif userchoices == "multiplication":
            print(multiplication())
        elif userchoices == "division":
            print(division())
        else:
            print(invalid_choice())
    print(userchoice())
    #here the user chooses the 2 numbers
    print("Please select 2 numbers to calculate")
        
    usernumber1 = int(input("Please input your first number here  : "))
    usernumber2 = int(input("Please input your second number here : "))
        
    #Functions of which contain addition, subtraction, multiplication and division
    def addition():
        print("A D D I T I O N")
        print("Just calculating...")
        
        print(usernumber1 + usernumber2)
        
    
    def subtraction():
        print("S U B T R A C T I O N")
        print("Just calculating...")
        print(usernumber1 - usernumber2)
        
    
    def multipliction():
        print("M U L T I P L I C A T I O N ")
        print("Just calculating...")
        print(usernumber1 * usernumber2)
        
    
    def division():
        print("D I V I S I O N ")
        print("Just calculatin...")
        print(usernumber1 / usernumber2)
        
        
    def invalid_choice():
        print("You did not pick a valid option, please try again")
    

你在这段代码中有很多错误的方法。

  1. 只输入一个符号(例如 *)比输入“乘法”更容易
  2. 最好为每个用户输入应用.lower()
  3. python 中的输入始终是 str,因此 userchoices = str(input()) 中的 str() 是多余的
  4. int() for input() 可能会导致错误(int('1.2') # error),所以把这样的代码放在try/except