python calculator program with expected indented block error - python

I have created a python calculator, I need to get it to restart, I have added the loop:
#This line defines the end of the program so it restarts.
def sys():
#These lines will define each operation.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def Multiply(x, y):
return x * y
def Divide(x, y):
return x/y
#This asks the user what operation they would like to use
print("Please select operation ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
#This tells the user to enter the number of the operation they would like
operation = input("Enter operation(1/2/3/4):")
#This asks the user to input the two numbers they would like the calculator to calculate
num1 = int(input("Please enter first number: "))
num2 = int(input("Please enter second number: "))
#This is the part of the program that will calculate the calculations
if operation == '1':
print(num1, "+", num2, "=", add(num1,num2))
elif operation == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif operation == '3':
print(num1,"*",num2,"=", subtract(num1,num2))
elif operation == '4':
print(num1,"/",num2,"=", subtract(num1,num2))
else:
print("Invalid input")
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
sys()
else:
print("thanks for playing")
sys.exit()
It keeps saying expected an indented block and shows, that it wants the indent in front of:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def Multiply(x, y):
return x * y
def Divide(x, y):
return x/y
but when I add them in, it keeps saying, that the operation is not defined. I also feel like the loop will not work either.

It looks like you are trying to recursively re-run the code, in which case you probably want e.g.
import sys # so you can use sys.exit()
def add(x, y): # no need for these function definitions to be in the loop
...
...
def main(): # conventional name - sys shadows the module you just imported
print("Please select operation ")
print("1. Add")
...
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
main()
else:
print("Thanks for playing")
sys.exit() # or just 'return'
if __name__ == "__main__": # if run directly, rather than imported
main()
You can define functions within other functions (although there's no need here), but remember you need another level of indentation:
def outer(n):
def inner(x):
return x ** 2
return 2 * inner(n)
Note that using recursion means you will eventually hit the system recursion depth limit; iteration is probably wiser:
def main():
while True:
...
inp = input("Enter clear to play again or exit to exit")
if inp != "clear":
print("Thanks for playing")
break

You may be interested in this solution to your problem. It makes use of the operator module, which provides named functions for all the standard Python operators. It also uses a list to translate the operation number to a function and a symbol for printing.
from operator import add, sub, mul, div
operations = [
(add, '+'),
(sub, '-'),
(mul, 'x'),
(div, '/'),
]
while True:
print('1. Add')
print('2. Subtract')
print('3. Multiply')
print('4. Divide')
op = int(raw_input('Enter operation (1/2/3/4): '))
if 0 < op <= len(operations):
func, sym = operations[op-1]
num1 = float(raw_input('Please enter first number: '))
num2 = float(raw_input('Please enter second number: '))
print('{} {} {} = {}'.format(num1, sym, num2, func(num1, num2)))
else:
print('Invalid operation')
continue
while True:
inp = raw_input('Enter clear to play again or exit to exit: ')
if inp == 'exit':
print('Thanks for playing')
exit()
elif inp == 'clear':
break
output
1. Add
2. Subtract
3. Multiply
4. Divide
Enter operation (1/2/3/4): 3
Please enter first number: 8
Please enter second number: 9
8.0 x 9.0 = 72.0
Enter clear to play again or exit to exit: exit
Thanks for playing

If you have an empty function, put in the phrase pass as in:
def some_func():
pass
And that error will no longer occur.

Related

How do I reset my calculator, when I enter "$" to input , instead of a number , python

I need to reset this calculator when user enter "$" instead first or second input number or user enter "$" end of the input number (ex: 5$,20$).
the (a,b) is input number1 and number2. it was assigned as global varibles.
select_op(choice) is function, running the operation that user need. input_function() is function for input two numbers.
# Functions for arithmetic operations.
def add(a,b):
return (a+b) # 'a' and 'b' will add.
def subtract(a,b):
return (a-b) # 'b' substract from 'a'.
def multiply(a,b):
return (a*b) #'a' multiply by 'b'.
def divide(a,b):
if b == 0 : .
return None
else:
return (a/b) # 'a' divided by 'b'.
def power(a,b):
return (a**b) # 'a' power of 'b'.
def remainder(a,b):
if b == 0:
return None
else:
return (a%b) # reminder of 'a' divided by 'b'.
#this function for out put of operation
def select_op(choice): #this function will select operation
if choice == "+":
input_function()
print(a,' + ',b,' = ',add(a,b))
elif choice == "-":
input_function()
print(a,' - ',b,' = ',subtract(a,b))
elif choice == "*":
input_function()
print(a,' * ',b,' = ',multiply(a,b))
elif choice == "/":
input_function()
if b==0:
print("float division by zero")
print(a,' / ',b,' = ',divide(a,b))
elif choice == "^":
input_function()
print(a,' ^ ',b,' = ',power(a,b))
elif choice == "%":
input_function()
if b==0:
print("float division by zero")
print(a,' % ',b,' = ',remainder(a,b))
elif choice == "#": #if choice is '#' program will terminate.
return -1
elif choice == "$": #if choice is '$' program reset.
return None
else:
print("Unrecognized operation")
#this function for input two operands.
def input_function():
number1=float(input("Enter first number: "))
number2=float(input("Enter second number: "))
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Be sure to check whether the string returned from input() ends with a "$" before converting it to a float.
To reset when a user types something that ends with "$", you could throw an exception to break out of your calculator logic and start over. We'll surround the stuff inside your while loop with a try/catch, so that the exception doesn't stop your program, but merely starts a new iteration in the while loop.
# I omitted all your other functions at the start of the file
# but of course those should be included as well
class ResetException(Exception):
pass
#this function for input two operands.
def input_function():
s = input("Enter first number: ")
if s.endswith("$"):
raise ResetException()
number1=float(s)
s = input("Enter second number: ")
if s.endswith("$"):
raise ResetException()
number2=float(s)
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
try:
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
except ResetException:
pass

Save and display calculation history of the python calculator

I need to extend the given calculator program to record the calculations, and recall them as a list using an additional command '?'.
Things to do:
Declare a list to store the previous operations
Save the operator, operands, and the results as a single string, for each operation after each calculation
implement a history() function to handle the operation '?'
Display the complete saved list of operations (in the order of execution) using a new command ‘?’
If there are no previous calculations when the history '?' command is used, you can display the following message "No past calculations to show"
Can someone help me, please?
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice):
if (choice == '#'):
return -1
elif (choice == '$'):
return 0
elif (choice in ('+','-','*','/','^','%')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return 0
if num1s.endswith('#'):
return -1
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue
while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return 0
if num2s.endswith('#'):
return -1
try:
num2 = float(num2s)
break
except:
print("Not a valid number,please enter again")
continue
if choice == '+':
result = add(num1, num2)
elif choice == '-':
result = subtract(num1, num2)
elif choice == '*':
result = multiply(num1, num2)
elif choice == '/':
result = divide(num1, num2)
elif choice == '^':
result = power(num1, num2)
elif choice == '%':
result = remainder(num1, num2)
else:
print("Something Went Wrong")
else:
print("Unrecognized operation")
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
print("8.History : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()```
You need to declare function history() and list,
last_calculation = []
def history():
global last_calculation
if last_calculation == []:
print("No past calculations to show")
else:
for i in last_calculation:
print(*i) #for single line
Then in the if loop add below code to end of the operations,
last_calculation.append(result)
Then trigger history() function, use 'continue' to make operation after the call history()
if choice=='?':
history()
continue
To save the history, you can add a global variable which is an empty list. Like this:
history = []
...
def record_history(*args):
history.append(args)
def select_op(choice):
...
record_history(choice, num1, num2, result)
...
This is not the most cleanest solution, but the simplest one since you are only using functions. Ideally functions should not have any side effects and should not depend on the "state" of the program. To save any kind of "state" refactoring this implementation into classes would make things more clean. Something like
class Calculator:
def __init__(self):
self.history = []
def record_history(self, *args):
self.history.append(args)
def select_op(self, choice):
...
self.record_history(choice, num1, num2, result)
...
Tips
Make your life simpler by using the standard library
The operator library provides functions like add, sub, mul etc.
The cmd.Cmd class can be used to build interactive consoles easily.
This is my answer to the problem you face. I have created this and checked it.
calculations = []
def record_history(args):
calculations.append(args)
def history():
if calculations == []:
print("No past calculations to show")
else:
for i in calculations:
print(i)
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice):
if choice == '#':
return -1
elif choice == '$':
return 0
elif choice in ('+', '-', '*', '/', '^', '%'):
while True:
num1s = input("Enter first number: ")
print(num1s)
if num1s.endswith('$'):
return 0
if num1s.endswith('#'):
return -1
try:
num1 = float(num1s)
break
except:
print("Not a valid number, please enter again")
continue
while True:
num2s = input("Enter second number: ")
print(num2s)
if num2s.endswith('$'):
return 0
if num2s.endswith('#'):
return -1
try:
num2 = float(num2s)
break
except:
print("Not a valid number, please enter again")
continue
result = 0.0
last_calculation = ""
if choice == '+':
result = add(num1, num2)
elif choice == '-':
result = subtract(num1, num2)
elif choice == '*':
result = multiply(num1, num2)
elif choice == '/':
result = divide(num1, num2)
elif choice == '^':
result = power(num1, num2)
elif choice == '%':
result = remainder(num1, num2)
else:
print("Something Went Wrong")
last_calculation = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
print(last_calculation)
record_history(last_calculation)
elif choice == '?':
history()
else:
print("Unrecognized operation")
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
print("8.History : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
if select_op(choice) == -1:
#program ends here
print("Done. Terminating")
break

I have a simple Python Calc and I need a "quit" choice

# Program make a simple calculator
# 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("İşlem seçiniz.")
print("1.Toplama")
print("2.Çıkarma")
print("3.Çarpma")
print("4.Bölme")
while True:
# Take input from the user
choice = input("Seçim yapınız(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("İlk numarayı giriniz: "))
num2 = float(input("İkinci numarayı giriniz: "))
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("Hatalı Giriş")
This is my simple calc with a def func an i need a quit/break choice in menu, i want a choice code like this
def run():
while True:
choice = get_input()
if choice == "a":
# do something
elif choice == "q":
return
if __name__ == "
__main__":
run()
I would be really grateful if someone helps me. Thank you.
This is my school homework, I would really appreciate it if you could explain more about the codes. I try to improve myself as much as I can, it makes me sad to be unable to do something as simple as this, but I need your help. Wish me luck to improve. And take care of your health, stay at home
You could import sys module and exit the code in following way:
import sys
def run():
# do stuff
if choice == "q":
sys.exit() # this exits the python program
Add an option to break from while loop on input if user say enters a q?
elif(x == "q"):
break
I've made a few menus before, my favorite option in this case would be to put the menu options inside it's own function, and have it return the choice back to the main function. Like this:
def multiply(number1, number2):
return number1 * number2
def showmenu():
print("1. Multiply")
print("2. Quit")
return input("Choice:")
def main():
playing = True
num1 = 5
num2 = 3
while playing:
choice = showmenu()
if choice == '1':
print(f'{num1} * {num2} = {multiply(num1,num2)}')
elif choice == '2':
print("Quitting!")
playing = False
if __name__ == "__main__":
main()

stuck with a simple python program "elif"

Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# 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 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
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")

How would you use a variable which is defined below your function?

I am trying to make a calculator using classes but I get error as "variable not defined"
What I am trying is (there are more functions in my codes, but the related code is)
def Start():
x = input("Please input what you want do to a number then the number; a whole number.\n(Example pi 2)\nYou can pow (pow 2 3; 2 to the power of 3),pi,square and cube: ").lower()
x = x.split()
Action = x[0]
number = int(x[1])
print ("Your number: " + str(number))
class Cal:
def pi():
print ("Your number multiplied by Pi: " + str(math.pi * number))
def Again():
y = input("Type 'Yes' to do another one if not type 'No': ").lower()
if "yes" in y:
print ("\n")
Start()
Work()
Again()
elif "no" in y:
pass
def Work():
if Action.startswith("pi"):
Cal.pi()
else:
pass
Start()
Work()
Again()
I am getting "Variable not defined only"
I am using Windows 7 and Python 3.3. What could be the possible issue?
You have to explicitely pass your "variables" to the functions that need them. You can read more about this in any programming tutorial (starting with Python's official tutorial). To "get" the variables from the function that sets them you have to return the variable(s). That's really CS101 BTW
As an exemple:
def foo(arg1, arg2):
print arg1, arg2
def bar():
y = raw_input("y please")
return y
what = "Hello"
whatelse = bar()
foo(what, whatelse)
More on this here: http://docs.python.org/2/tutorial/controlflow.html#defining-functions
Fixed version of your script (nb tested on Python 2.7 with a hack for input but should work as is on 3.x):
import math
def Start():
x = input("Please input what you want do to a number then the number; a whole number.\n(Example pi 2)\nYou can pow (pow 2 3; 2 to the power of 3),pi,square and cube: ").lower()
x = x.split()
Action = x[0]
number = int(x[1])
print ("Your number: " + str(number))
return (Action, number)
class Cal:
def pi(self, number):
print ("Your number multiplied by Pi: " + str(math.pi * number))
def Again():
y = input("Type 'Yes' to do another one if not type 'No': ").lower()
if "yes" in y:
print ("\n")
args = Start()
Work(*args)
Again()
elif "no" in y:
pass
def Work(Action, *args):
if Action.startswith("pi"):
Cal().pi(*args)
else:
pass
def Main():
args = Start()
Work(*args)
Again()
if __name__ == "__main__":
Main()
Inside your Start() function, put
global Action
That way, the variable will enter the global scope, so it will be visible from the other functions.
However, this is not good style. Rather, you should pass parameters to other functions instead of relying on global variables.

Categories