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

# 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()

Related

this code always go to else I tried to put if in if to force code to go to it but still go to else

def add(x, y):
return x + y
def multiple(x, y):
return x * y
def subtrack(x, y):
return x - y
def divide(x, y):
return x / y
print('select your operation please')
print('1-Add')
print('2-Multiple')
print('3-subtrack')
print('4-Divide')
chose=int(input('enter your selection please: '))
num1=int(input('enter your first num please: '))
num2=int(input('enter your second num please: '))
if chose == '1':
print(num1,'+',num2,'=',add(num1,num2))
elif chose == '2':
print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == '3':
print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == '4':
print(num1,'/',num2,'=',divide(num1,num2))
else:
print("invalid number operation")
this code always go to else I tried to put if in if to force code to go to it but still go to else some solutions please
I don't know what language this is but chose is an int an your if checks on an string(or char depending the language).
if you change your comparison to:
if chose == 1:
print(num1,'+',num2,'=',add(num1,num2))
elif chose == 2:
print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == 3:
print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == 4:
print(num1,'/',num2,'=',divide(num1,num2))
else:
print("invalid number operation")
It should work as expected
When doing:
if chose == '1'
You're comparing to a char in python.
If you do
if chose == 1
you're actually comparing to a int. Which is also what you enter in the inputs.
removing the ' around the right hand side of your if comparison operators, you will not keep getting pushed to the 'else' statement!
You are receiving user input and converting to int and while comparison you are comparing it with string i,e. if chose == '1':
the solution is:
1.you receive user input in int or compare the integer value
chose=int(input('enter your selection please: '))
if chose == 1:
print(num1,'+',num2,'=',add(num1,num2))
elif chose == 2:
print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == 3:
print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == 4:
print(num1,'/',num2,'=',divide(num1,num2))
else:
print("invalid number operation")
2.You receive user input in str and compare the string value
chose=str(input('enter your selection please: '))'=
if chose == '1':
print(num1,'+',num2,'=',add(num1,num2))
elif chose == '2':
print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == '3':
print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == '4':
print(num1,'/',num2,'=',divide(num1,num2))
else:
print("invalid number operation")

How can i add a function to show me history of calculations and results?

How can i add a function to show me history of calculations and results? Either in the console or create a .txt file. This is code I got from the internet BTW. I am a beginner to python also.
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("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Modification of your text to write to a file (e.g. 'log.txt')
Opens file in append mode
Using Python string interpolation to compose string to write
Code
# 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")
with open('log.txt', 'a') as history: # open file 'log.txt' in append mode for logging
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
history.write(f'{num1} + {num2} = {add(num1, num2)}\n') # append to history file
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
history.write(f'{num1} - {num2} = {subtract(num1, num2)}\n') # append to history file
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
history.write(f'{num1} * {num2} = {multiply(num1, num2)}\n') # append to history file
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
history.write(f'{num1} / {num2} = {divide(num1, num2)}\n') # append to history file
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
you can add a print statement inside each of your functions.
i.e:
def add(x, y):
result = x + y
print('add', x, y, 'result =', result)
return result
Here is a possible solution:
# 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")
print("5.History")
history = []
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4/5): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4', '5'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
history.append(f'{num1} + {num2} = {result}')
print(history[-1])
elif choice == '2':
result = subtract(num1, num2)
history.append(f'{num1} - {num2} = {result}')
print(history[-1])
elif choice == '3':
result = multiply(num1, num2)
history.append(f'{num1} * {num2} = {result}')
print(history[-1])
elif choice == '4':
result = divide(num1, num2)
history.append(f'{num1} / {num2} = {result}')
print(history[-1])
elif choice == '5':
print(*history, sep='\n')
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Basically you keep a list with all previous printed messages, and you print them all whenever the user chooses option '5'.
One really neat way to do it is with decorators. With this approach you only have to write the logic once and can apply it to all the functions. This logic is specific for binary operations but could obviously be extended and also modified to write to a log file:
# `log_op` is the decorator
def log_op(f_name, f_op):
def wrapper(f):
def inner(*args, **kwargs):
result = f(*args, **kwargs)
print(f"{f_name}: {args[0]} {f_op} {args[1]} = {result}")
return result
return inner
return wrapper
#log_op('add', '+')
def add(x, y):
return x + y
#log_op('subtract', '-')
def subtract(x, y):
return x - y
add(1,2) # add: 1 + 2 = 3
subtract(1,2) # subtract: 1 - 2 = -1

Python - Reset button calculator and other issues

Python - Reset button calculator and other issues
This is a python calculator. I developed a part here. but, In this calculator, when the user enters two wrong numbers or one wrong operator, the reset function is given by $ + enter. How to add reset capability to code?
How to fix it?
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
# This function uses to power
def power(x, y):
return x**y
# This function uses for the remainder
def remainder (x, y):
return x % y
print("Please select the 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")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4','5' ,'6'):
num1 = float(input("Enter first number: "))
num2 = float(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))
elif choice == '5':
print(num1, "**", num2, "=", power(num1, num2))
elif choice == '6':
print(num1, "%", num2, "=", remainder(num1, num2))
elif choice == '7':
print(num1 , "#", num2, "=", terminate(num1,num2))
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
print("Thank you")
#this funtion uses to optimize the code [ select_op(choice) funtion also used here ]
def find(choice):
if reset_operand == "yes":
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
select_op(choice)
elif reset_operand == "no":
select_op(choice)
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
if choice in ('1', '2', '3', '4', '5', '6'):
reset_operation = input("Do you need to change the operation? (yes/no): ")
if reset_operation == "yes":
choice = input("Enter again choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
if reset_operation == "no":
if choice in ('1', '2', '3', '4', '5', '6'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
find(choice)
else:
print("Unrecongnized operation !")

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

python calculator program with expected indented block error

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.

Categories