Why "None" word is printed in python code - python

I've tried Simple Python Calculator with Maintaining past history with it. The word "None" is getting printed after each calculations. How to remove that "None" word from my code
Here is my code for python calculator!!
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 = 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
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 ))
print((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")
exit()
The output is,
Select operation.
1.Add : +
2.Subtract : -
3.Multiply : *
4.Divide : /
5.Power : ^
6.Remainder: %
7.Terminate: #
8.Reset : $
8.History : ?
Enter choice(+,-,*,/,^,%,#,$,?): ?
No past calculations to show
Select operation.
1.Add : +
2.Subtract : -
3.Multiply : *
4.Divide : /
5.Power : ^
6.Remainder: %
7.Terminate: #
8.Reset : $
8.History : ?
Enter choice(+,-,*,/,^,%,#,$,?): -
Enter first number: 2
Enter second number: 3
2.0 - 3.0 = -1.0
None
Select operation.
1.Add : +
2.Subtract : -
3.Multiply : *
4.Divide : /
5.Power : ^
6.Remainder: %
7.Terminate: #
8.Reset : $
8.History : ?
Enter choice(+,-,*,/,^,%,#,$,?): ?
2.0 - 3.0 = -1.0
Select operation.
1.Add : +
2.Subtract : -
3.Multiply : *
4.Divide : /
5.Power : ^
6.Remainder: %
7.Terminate: #
8.Reset : $
8.History : ?
Enter choice(+,-,*,/,^,%,#,$,?): #
Done. Terminating
How to Remove the extra None ...

The problem is here:
print((record_history(last_calculation)))
The functoin record_history doesn't return a value, so it implicitly returns None. Instead of trying to print the result of the call (i.e., None), just call it by replacing the above with:
record_history(last_calculation)

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

Calculator to execute loop until "exit"

I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.

ValueError when trying to convert strings to floating point

I'm having troubles running this program.
It tells me I have a
ValueError: could not convert string to float
The problem is though, that it just skips my input commands and jumps to
print("Invalid Response")
This program works fine on my cellphone but not on my windows 10 laptop.
Any help? Try running it and let me know if it works for you.
def calc(): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin():
result = calc()
print("Operate? y/n: ")
cont = input()
if cont == "y":
print(result) # output is: ought to be:
chars = input() #result result
contin_num = float(input())
calc(contin_num) #result operate y/n
print(result, chars, contin_num)
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
calc()
contin()
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")
This is the desired code. I changed a little bit some indentations are wrong in case of contin() function and some logic. Please refer to this if I am wrong in some place do tell me. Thank you
def calc(num1,chars,num2): #The function performing calculation.
if chars == "+":
result = num1 + num2
print (result)
return result
elif chars == "-":
result = num1 - num2
print(result)
return result
elif chars == "*":
result = num1 * num2
print(result)
return result
elif chars == "/":
result = float(num1) / float(num2)
print(result)
return result
else:
print("Invalid or unsupported operation")
cont = ""
def contin(res):
num1 = res
print("Operate? y/n: ")
cont = raw_input()
if cont == "y":
print(num1) # output is: ought to be:
chars = raw_input() #result result
num2 = float(input())
num1=calc(num1,chars,num2) #result operate y/n
print num1
elif cont == "n":
result = 0
print(result)
else:
print ("Invalid response.")
num1 = float(input ())
chars = raw_input ()
num2 = float(input ())
result = 0
while num1 > 0 or num2 > 0:
res = calc(num1,chars,num2)
contin(res)
break
if num1 == 0 and num2 == 0:
print("Zero or undefined.")

how to add restart command in python? [duplicate]

This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
This is a simple calculator i wrote but after finishing it won't restart the application
this is my code:
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
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
choice = input("Enter choice(a/s/m/d):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd':
print (" the letter you intered is not in our lists!")
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
input("press enter to close")
when its finished i want it to ask the user if they want to restart or not . i used different while looping its not working.
Just loop until the user wants to quit:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = input("Enter choice(a/s/m/d) or q to quit:")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue # if invalid input, ask for input again
elif choice == "q":
print("Goodbye.")
break
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
I used str.format to print your output, if choice not in {"a", "s", "m", "d","q"} uses in to test for membership replacing the long if statement.
You might want to wrap the int input inside a try/except to avoid your program crashing if the user does not enter the correct input.
try:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
except ValueError:
continue
If you want to do it like the example in your comment:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = raw_input("Enter choice(a/s/m/d)")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
inp = input("Enter 1 to play again or 2 to exit")
if inp == "1":
main()
else:
print("thanks for playing")
break
Instead of this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
Use this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
elif choice==e:
print("goodbye")
break
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
You'll need to wrap the part that's processing user input in a while loop. You'll also need an option to break that while loop in your selection process. I added an input value of e that handles exiting the loop. Your first if statement and the else statement at the end were redundant, so I switched them around a little as well.
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
while True:
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
print("E.Exit")
choice = input("Enter choice(a/s/m/d/e):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == 'e':
print("Goodbye")
break

Categories