Python calculator script with functions and lists - python

I am trying to create a simple python calculator with inputs as lists and functions defining the operations that can be performed.
I am having trouble getting my functions to return the value after they have returned.
The program is supposed to get numbers in the form of a list and then pass them into the while loop in the main part of the program. The user can perform as many operations as they want before the program quits.
Please let me know what my error is or if I need to add anything.
def display_menu():
print("Please Choose an option")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
print("q to quit")
def addition():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 + num
return num1
def subtraction():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 - num
return num1
def multiply():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
def division():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
displ_menu()
operator = input("Please enter an operator: ")
while operator != "q":
if operator == "+":
addition()
elif operator == "-":
subtraction()
elif operator == "*":
multiply()
else:
division()
displ_menu()
operator = input("please enter an operator")
print("Closing calculator")

Related

Input number A and B and sum them together, given that A has a pre-defined limit in Python

I am doing a calculator that input number A and number B then sum them up, given that A has a pre-defined limit (e.g. A has to be less than 8)
def welcome():
print("Welcome user")
print("")
def ans_num1():
num1 = int(input("Enter your 1st num: "))
while num1 <= limit1:
print("Good boy")
break
else:
print("Wrong input")
ans_num1()
def ans_num2():
num2 = input("Enter your 2st num: ")
def calculator():
print("The sum of 2 numbers are: ")
print(num1 + num2)
print("")
def thanks():
print("Thank you and Goodbye :)")
welcome()
limit1 = int(input("Enter your limit: "))
asknum1()
asknum2()
calculator()
thanks()
But I am getting an error message saying that:
The sum of 2 numbers are:
Traceback (most recent call last):
line 31, in <module>
calculator()
line 20, in calculator
print(num1 + num2)
NameError: name 'num1' is not defined
I am new to python and stuck, need help right now!
When doing the following you create a variable num2 local to the method, it can only accessed in the method's scope, you need to return values from the method in one way and pass them as parameter in another way
def ans_num2():
num2 = input("Enter your 2st num: ")
Giving :
def welcome():
print("Welcome user\n")
def asknum(limit, nb):
res = int(input("Enter your number %s " % nb))
while res > limit:
res = int(input("Enter your number %s " % nb))
return res
def calculator(num1, num2):
print("The sum of 2 numbers are: ", num1 + num2, "\n")
def thanks():
print("Thank you and Goodbye :)")
welcome()
limit = int(input("Enter your limit: "))
num1 = asknum(limit, 1)
num2 = asknum(limit, 2)
calculator(num1, num2)
thanks()
num1 and num2 are local variable i.e they dont have scope outside the function they are declared in . to fix them declare them outside the function or add global keyword.
also you have written asknum1() and not ans_num1() same with ans_num2()
def welcome():
print("Welcome user")
print("")
def ans_num1():
global num1 #num1 is declared globally
num1 = int(input("Enter your 1st num: "))
while num1 <= limit1:
print("Good boy")
break
else:
print("Wrong input")
ans_num1()
def ans_num2():
global num2 #declared globally
num2= int(input("Enter your 2st num: "))
def calculator():
print("The sum of 2 numbers are: ")
print(num1 + num2)
print("")
def thanks():
print("Thank you and Goodbye :)")
welcome()
limit1 = int(input("Enter your limit: ")) #already declared globally
ans_num1() #fixed the function name
ans_num2()
calculator()
thanks()

How to write a condition in a function to make this comment Python

How to write a condition in a function to make this comment "Please provide two integers or floats"
Now I have a ValueError like " could not convert string or float "
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
def divede():
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
num1, num2 = divede()
while True:
if num2 == []:
print("Please provide two integers or floats")
elif num2 != 0:
print(f"{num1} / {num2} is {num1/num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()
here I have a problem:
while True:
if num2 == []: # wrong condition
print("Please provide two integers or floats")
Thx for all answers
Change your division function to this:
def divede():
num1 = input("Enter first number:")
num2 = input("Enter second number:")
try:
num1, num2 = float(num1), float(num2)
except ValueError:
print("Invalid entry, please enter numbers")
return divede()
return num1, num2
In that case you do not need the first if in your while loop.
My code is too complicate :)
correct answer is :
def divide(a,b):
try:
total = a / b
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
return total
The error you get arises as soon as you try to convert your string input to float in one of the following lines:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
I would suggest you change your divede function to the following:
def divede():
while True:
try:
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))
return num1, num2
except(ValueError):
print("Please provide two integers or floats")
The while loop makes sure that the user is asked for repeating input until he actually provides two numbers.
The except(ValueError) is there to catch only the specific errors you want.
Then you also need to change the rest of the script like so:
while True:
if num2 != 0:
print(f"{num1} / {num2} is {num1 / num2}")
break
else:
print("Please do not divede by zero")
num1, num2 = divede()

Basic calculator will only add values [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I'm new to python and am trying to make a basic calculator that takes two numbers and performs the operation specified by the user, but regardless of the operation I enter, the numbers always add.
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
if operation == "Add" or "add":
add = num1 + num2
print(add)
elif operation == "Subtract" or "subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or "multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
With what I have, if num1 = 10 and num2 = 5 and I enter "multiply" the result I get is 15, not 50.
if operation == "Add" or "add"
These are two conditions:
if operation == "Add" which does what you expect.
if "add" - Always evaluates to True because it's a constant string.
So you could just as well have written:
if True. You need to replace it with:
if operation == "Add" or operation == "add"
Anyway, I would like to suggest a few things.
Lowercase then check only once
You should lowercase your input string instead of double checking "Add" or "add":
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" ).lower() # Notice the `lower` here
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation "multiply":
mult = num1 * num2
print(mult)
elif operation "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Use the built-in operator module
The operator module contains exactly the methods that you seek for. You could use it for convenience (haven't tested, should work):
import operator
keywords = {"add": "add", "subtract": "sub", "multiply": "mul", "divide": "truediv"}
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
op_func = keywords.get(operation.lower(), "add") # defaults to add
print(getattr(operator, op_func)(num1, num2))
def fun(operation, num1,num2):
operation = operation.lower()
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation == "multiply":
mult = num1 * num2
print(mult)
elif operation == "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
fun('multiply', 10,5)
Why:
if operation == "add" or "Add": this is always True
We can use if operation == "add" or operation == "Add":
You have to do like this:
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = str(input("Type Add, Subtract, Multiply, or Divide" ))
if operation == "Add" or operation =="add":
add = num1 + num2
print(add)
elif operation == "Subtract" or operation =="subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or operation =="multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or operation =="divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Because of or operation with string, all your conditions will be true.
That's why it will only go to first condition no matter what you give in the input.

Looping main function while resetting variables

Just started learning Python in my computing fundamentals class. We have to build a program that creates practice sets for mathematics. The user inputs two numbers, an operator, then a solution, and the program tells them if they are correct/incorrect. After that, the program is supposed to loop back around so the user can continue practicing. The program is supposed to loop for a total of 5 practice sets. I have the loop, but when it's executed it repeats the inputs initially entered by the user instead of resetting, so the user cannot make any more inputs. What am I missing?
I tried a while True: loop on my global variables but that just causes the main function to loop without completing the program. The assignment very clearly dictates that the use of a while loop is needed, as my professor included slight hints to help us.
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(input("Enter Solution: "))
res1 = num1+num2
res2 = num1-num2
res3 = num1*num2
res4 = num1/num2
timesCorrect = 0
timesIncorrect = 0
def main ():
counter = 0
while counter < 4:
print(num1)
print(num2)
print(op)
print(UserSolution)
counter = counter + 1
The function is indeed looping like I want it to, but it isn't resetting the variables like I want it to.
You need to move your input statements to within the loop, for example:
timesCorrect = 0
timesIncorrect = 0
def main ():
counter = 0
while counter < 4:
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(input("Enter Solution: "))
res1 = num1 + num2
res2 = num1 - num2
res3 = num1 * num2
res4 = num1 / num2
print(num1)
print(num2)
print(op)
print(UserSolution)
counter = counter + 1
Also, if you want it to loop five times, you need to change the counter comparison to < 5, or <= 4, instead of < 4.
Probably going to be a little beyond the scope of your assignment, but here's an untested suggestion:
# Mix it up a little by hiding the user's suggested solution with getpass()
from getpass import getpass
### Set iterator variable to avoid hard-coding the script
max_iterations = 5
def evaluate_expression(first_input, second_input, operator):
"""
Function to handle arithmetic
"""
my_solution = 0
if operator == '+':
my_solution = first_input + second_input
elif operator == '-':
my_solution = first_input - second_input
elif operator == '/':
# Can't divide by zero, so we have to handle that.
if second_input != 0:
my_solution = first_input / second_input
else:
my_solution = 0
elif operator == '*':
my_solution = first_input * second_input
return my_solution
def main():
### Counters
correct_guesses = 0
incorrect_guesses = 0
try_counter = 1
while try_counter <= max_iterations:
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(getpass("Enter Solution: ")) # Hide the input
### We van evaluate the expression and return the result to a variable using eval()
# temp_solution = eval(f'{num1} {op} {num2}')
## Traditional evaluation method
#if op == '+':
# my_solution = num1 + num2
#elif op == '-':
# my_solution = num1 - num2
#elif op == '/':
# my_solution = num1 / num2
#elif op == '*':
# my_solution = num1 * num2
# Call our expression and evaluate the results
if evaluate_expression(num1, num2, op) == UserSolution:
print('You\'re correct!')
correct_guesses += 1
else:
print('Incorrect answer!')
incorrect_guesses += 1
try_counter += 1
print(f'Number of correct guesses: {correct_guesses]\nNumber of incorrect guesses: {incorrect_guesses}')

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

Categories

Resources