Calculator created with Python - python

I'm new here in this "world".
I tried to create a calculator with Python,here's the code.
When I try to run it,IDLE gives me errors,can you help me,please? :D
Header 1
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
else:
print("Unknown command")

Try this (you don't have loop so use exit() rather than break, also use the right operators for add, divide, sub-struct, multiply.
from __future__ import division # to support division
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = raw_input(": ")
if user_input == "quit":
exit() #break is uesd in loops
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1-num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1*num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1/num2)
print("The answer is " + result)
else:
print("Unknown command")

The problem is the break statement here:
if user_input == "quit":
break
You can only use a break statement within a while and/or for loop.
The solution is to replace the break statement with print() or exit() instead.
For your program to be more effective (and to be able to use the break statement), you could execute your if,elif and else statements within a while loop:
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
while True:
user_input = input(": ")
if user_input == "quit":
print('Program terminated')
break
elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is" + result)
elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
else:
print("Unknown command")

The problem is you are implementing a break that is not in a while loop.
Breaks must occur in a while loop. So a way of getting around this problem is by saying:
if user_input == "quit":
exit()
Example2:
import sys
if user_input == "quit":
sys.exit()
Hope this helped!

if user_input == 'quit':
#break
pass

Related

Fatal Error Detected! Failed to execute script

I'm very new to coding and just started recently. I made a very basic calculator and tried to make it into an exe file so that I could run it on a system without python. But after making it into an exe file using pyinstaller, it says it cannot execute script. Please help!
print("Welcome to Subahs Calculator")
print("Choose an operation to perform:")
print("1.Addition")
print("2.Substraction")
print("3.Multiplication")
print("4.Division")
print("5.Square")
print("6.Square Root")
operation = input()
if operation == "1":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = float(num1) + float(num2)
print("The result is " + str(result))
elif operation == "2":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = float(num1) - float(num2)
print("The result is " + str(result))
elif operation == "3":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = float(num1) * float(num2)
print("The result is " + str(result))
elif operation == "4":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
result = float(num1) / float(num2)
print("The result is " + str(result))
elif operation == "5":
num1 = input("Enter the number: ")
result = pow(float(num1), 2)
print("The result is " + str(result))
elif operation == "6":
num1 = input("Enter the number: ")
result = sqrt(float(num1))
print("The result is " + str(result))
else: print("Invalid Operation")
k = input("Press Enter to exit.")```

what's wrong with my simple calculator, it doesn't error and doesn't execute

I can't quite figure out why my code won't work.
Whenever I click run, it doesn't follow back with a traceback error, it just says process finished with exit code 0.
I thought it might be the casefold but then when I applied it to "Y". casefold it wouldn't work full stop.
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
Just add calculate() at the very end to call the function.
Put function calling calculate() at the end without any indent. Your function isn't even getting called, thus giving no error.
You need to call this calculate() function first (at least it's not being executed in your code sample).
def calculate()
# func code here
#Exec this function
calculate()
I guess it should be like this:
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
calculate()

Restart Python program if user input to 'run again?' is 'y'

while True:
# main program
number = (" ")
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer in y, n:
break
print("Invalid input.")
if answer == 'y':
continue
else:
print 'Goodbye'
break
Essentially I want the program to restart when the user enters 'y' as a response to 'run again?' Any help would be vastly appreciated. Thanks.
As #burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:
if answer in y, n: - you probably mean if answer not in ('y', 'n'):
number = (" ") is an irrelevant line
while True makes no sense in your main program
print("Invalid input.") is below a break, thus it'll never be executed
So you'll have something like:
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
if answer == 'y':
main()
else:
print 'Goodbye'
if __name__ == '__main__':
main()
You should probably add a few checks to handle cases when users enter non-number input etc.
Your code looks really messed up. Try to write some better(clean) code next time.
while True:
total = 0
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
num3 = int(input("enter a number"))
total = num1 + num2 + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
con = int(input("Run again? 1/0: "))
if con==0:
break

Type Error: Int object is not callable

I have an error with my code when I try to run it.
CODE
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = input()
num1 = input("Enter your first number: ")
num2 = input("Enter your second number: ")
def addition(num1, num2):
num1
num2
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
num1
num2
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
num1
num2
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
num1
num2
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == "1":
addition
elif choice == "2":
subtraction
elif choice == "3":
multiply
elif choice == "4":
division
else:
print("Invalid Input")
Everything works until python is called to print the answer.
I am aware of the possible duplicates but none of the code provided there works.
The issue is in the lines -
if choice == 1():
addition
elif choice == 2():
subtraction
elif choice == 3():
multiply
elif choice == 4():
division
I have no idea what you want 1() to do, seems like a typo. Also you should be calling the functions addition , etc , like - addition(num1, num2) .
And choice is string not int . And you should convert num1 and num2 to int.
More issues in your code -
Why are you doing - num1 and num2 in your functions , it does not do anything, you can remove the first two lines of each function.
Your print function in wrong, in Python 3.x , the %(ans) should be inside the function, not outside it.
Code -
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s' %(ans))
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s' %(ans))
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s' %(ans))
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s' %(ans))
if choice == '1':
addition(num1, num2)
elif choice == '2':
subtraction(num1, num2)
elif choice == '3':
multiply(num1, num2)
elif choice == '4':
division(num1, num2)
The problem is due to this
if choice == 1():
Where as it should be
if choice == 1:
And you have to convert num1 and num2 to integer types
And you should call the function just not declare them that is
if choice == 1:
addition(num1, num2)
And you have to do this for other things
And after doing all the changes your program would look like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == 1:
addition(num1,num2)
elif choice == 2:
subtraction(num1,num2)
elif choice == 3:
multiply(num1,num2)
elif choice == 4:
division(num1,num2)
else:
print("Invalid Input")
My changes would be:
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans=None
if choice == 1:
ans = num1 + num2
elif choice == 2:
ans = num1 - num2
elif choice == 3:
ans = num1 * num2
elif choice == 4:
ans = float(num1) / num2
if ans:
print('Your answer is %s') %(ans)
else:
print("Invalid Input")
The error with your current code is just with the brackets in your print statements. if instead of having %ans outside of the print statement, the code works when it is like this
print('Your answer is %s' %ans)
A neater version of the same code you just wrote looks like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
return num1+num2
def subtraction(num1, num2):
return num1-num2
def multiply(num1, num2):
return num1*num2
def division(num1, num2):
return num1/num2
if choice == 1:
ans = addition(num1,num2)
elif choice == 2:
ans = subtraction(num1,num2)
elif choice == 3:
ans = multiply(num1,num2)
elif choice == 4:
ans = division(num1,num2)
else:
print("Invalid Input")
if choice in range(4):
print('Your answer is %s' %ans)
Ironically, this has ended up with me writing an answer to my own question with admittedly some help from # Vignesh Kalai, although hid code was a little off. So before anything else I will address the changes to my code.
Firstly, instead of defining every operation I have linked than with the choice of their "ID"'s.
Secondly, I am using "" + str(x) to print the answers out instead of the admittedly bad idea of using %s.
REVISED CODE
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
if choice == 1: #Addition
num1
num2
ans = num1 + num2
print("Your answer is " + str(ans))
elif choice == 2: #Subtraction
num1
num2
ans = num1 - num2
print("Your answer is " + str(ans))
elif choice == 3: #Miltiplication
num1
num2
ans = num1 * num2
print("Your answer is " + str(ans))
elif choice == 4: #Division
num1
num2
ans = float(num1) / float(num2)
print("Your answer is " + str(ans))

Python - is this loop correct?

def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print("\t\t\tCalculator App")
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
#invalid operation
print("You have entered an invalid key")
else:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
if(operation == "+"):
print("Answer is: ", add(var1, var2))
elif(operation == "-"):
print("Answer is: ", sub(var1, var2))
elif(operation == "*"):
print("Answer is: ", multi(var1, var2))
else:
print("Answer is: ", div(var1,var2))
main()
rerun = input("ReRun? (y/n)")
while(rerun == "y"):
main()
rerun = input("ReRun? (y/n) ")
else:
exit()
Reading books, watching videos, and self study has been challenging.
Please let me know if this is the correct way to loop this program, i'm sure there are alternatives.
If you mean the rerun loop down at the bottom, the following is probably cleaner:
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
It should be noted that it defaults to rerunning if the user enters something not expected.
I would have done something like
operators = dict()
operators['+'] = lambda x,y: x+y
operators['-'] = lambda x,y: x-y
operators['*'] = lambda x,y: x*y
operators['/'] = lambda x,y: x/y
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if operation in operators:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
print("Answer is: ", operators[operation](var1, var2))
else:
print("You have entered an invalid key")
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
Which I believe is more readeable and easier to expand (add new operators)

Categories

Resources