Basic Calculator in Python

被刻印的时光 ゝ 提交于 2019-12-14 03:21:38

问题


I'm new to Python. I tried to make a basic calculator, but i can't really find the problem. It returns with 0 exit code, but nothing appears, no input no nothing. Any help with this will greatly be appreciated. Thank You.

def add(num1, num2):
    return num1 + num2

def subtract(num1, num2):
    return num1 - num2

def div(num1, num2):
    return num1/num2

def multi(num1,num2):
    return num1*num2

def main():
    operation = input("What do you want to do?(+, -, *, or /):")
    if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
        print("Your input is invalid. Please enter a valid input.")
    else:
        num1 = float(input("Enter value for num1: "))
        num2 = float(input("Enter value for num2: "))
        if (operation == "+"):
            print(add(num1, num2))
        elif (operation == "-"):
            print(subtract(num1, num2))
        elif (operation == "*"):
            print(multi(num1,num2))
        elif (operation == "/"):
            print(div(num1,num2))

    main()

回答1:


Based on the code above, you are never actually running main(). Right now, you have said that the definition of main is to prompt the user, check if the input was correct, and then do the math. The main() at the end causes the program to repeat after doing all this (not sure if you want the loop or not).

If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main(), because right now the indentation means it is inside of def main(). Just move it to the left to be at the same indentation level as the def main(): and your program should run fine.




回答2:


I think you are missing:

if __name__ == "__main__":
    main()

Your call to main() inside main itself won't execute and that's probably why you aren't getting any input.

Other than that your code should work as expected (make sure you don't divide by zero ;) ).

Edit: to make my answer more obvious, you should have done:

def main():
    operation = input("What do you want to do?(+, -, *, or /):")
    if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
        print("Your input is invalid. Please enter a valid input.")
    else:
        num1 = float(input("Enter value for num1: "))
        num2 = float(input("Enter value for num2: "))
        if (operation == "+"):
            print(add(num1, num2))
        elif (operation == "-"):
            print(subtract(num1, num2))
        elif (operation == "*"):
            print(multi(num1,num2))
        elif (operation == "/"):
            print(div(num1,num2))

if __name__ == "__main__":
    main()



回答3:


num1=float(input("enter the first number :"))
op = input("sellect the operation :")
num2 = float(input("enter the second number :"))
if op== "+" :
    print(num1+num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1*num2)
elif op == "/":
    print(num1 / num2)
else:
    print("please enter a real operation ")   
 #this one is more simple



回答4:


Basic Calculator:

Method 1:

# This function adds two numbers 
def add(x, y):
    return x + y
# This function subtracts two numbers 
def subtract(x, y):
    return x - y
# This function multiplies two numbers
def multiply(x, y):
    return x * y
# This function divides two numbers
def divide(x, y):
    return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user 
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
    print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
    print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
    print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
    print(num1,"/",num2,"=", divide(num1,num2))
else:
    print("Invalid input")

Method 2:

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user 
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
    print(num1,"+",num2,"=", num1+num2)
elif choice == '2':
    print(num1,"-",num2,"=", num1-num2)
elif choice == '3':
    print(num1,"*",num2,"=", num1*num2)
elif choice == '4':
    print(num1,"/",num2,"=", num1/num2)
else:
    print("Invalid input")

Happy Learning...:)




回答5:


while True:
 print("PRINT 'E' for exit")
 given_number=input("Give the operation :")
 given_number_in_string=str(given_number)

 position_of_multiplication=(given_number_in_string.find("*"))
 position_of_addition=(given_number_in_string.find("+"))
 position_of_substraction=(given_number_in_string.find("-"))
 position_of_division=(given_number_in_string.find("/"))



 if position_of_multiplication >= 0:

   position_of_multiplication=(given_number_in_string.find("*"))
   first_no=float(given_number_in_string[0:position_of_multiplication])
   second_no=float(given_number_in_string[position_of_multiplication+1:16])
   print(f"answer is  {first_no*second_no}")
   a=input("")

 elif position_of_addition >= 0:

    position_of_addition=(given_number_in_string.find("+"))
    first_no=float(given_number_in_string[0:position_of_addition])
    second_no=float(given_number_in_string[position_of_addition+1:16])
    print(f"answer is  {first_no+second_no}")
    s=input("")

 elif position_of_substraction >= 0:

    position_of_substraction=(given_number_in_string.find("-"))
    first_no=float(given_number_in_string[0:position_of_substraction])
    second_no=float(given_number_in_string[position_of_substraction+1:16])
    print(f"answer is  {first_no-second_no}")
    s=input("")

 elif position_of_division >= 0:

    position_of_division=(given_number_in_string.find("/"))
    first_no=float(given_number_in_string[0:position_of_division])
    second_no=float(given_number_in_string[position_of_division+1:16])
    print(f"answer is  {first_no/second_no}")
    s=input("")


 if given_number_in_string == "E":
    break


来源:https://stackoverflow.com/questions/34979532/basic-calculator-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!