I need to create a calculator in Python that can perform all of these tasks. I have gotten this far with my code to do addition, subtraction, multiplication, and division. Can someone show me what to add to my code to add log, power, Pythagorean theorem, and factorial to my calculator? These are all the requirements for my calculator below.
Each mathematic operation needs to be its own function/method:
Addition - Takes up to 5 arguments,
Subtraction - - Takes 3 arguments,
Multiplication - Takes 4 arguments,
Division - Takes 2 arguments,
Log - Takes 1 argument,
Raise a number to a power ex. X squared,
Solve Pythagorean theorem,
Factorial
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
It's just the ideas of your requested functions. I added some of them to your calculator. You can also change the hints that you want to show to the user.
PS: Better to use while for the calculator loop.
import math
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
! for factorial
log for logarithm(number, base)
hypot for Pythagorean
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
elif operation == '!':
print(math.factorial(number_1))
print(math.factorial(number_2))
elif operation == 'log':
print(math.log(number_1, number_2))
elif operation == 'hypot':
print(math.hypot(number_1, number_2))
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
I updated the answer based on the comment; you want to take a variable number of inputs from a user like n numbers. I used add() for your situation to answer your exact issue and removed additional codes.
def add(numbers_list):
return sum(numbers_list)
if __name__ == "__main__":
while(True):
number_of_inputs = int(input('Number of inputs? '))
numbers = [float(input(f'Please enter a number({i + 1}): ')) for i in range(number_of_inputs)]
print(add(numbers))
Related
def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op:
calculate()
number_1 = float(input("What is your first number? "))
if number_1 != float:
calculate()
number_2 = float(input("What is your second number? "))
if number_2 != float:
calculate()
if operator == "+":
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input")
calculate()
again()
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit
else:
print("Wrong Input")
again()
calculate()
Does anyone have an idea why my code always asks the operator questions again and again even if there was a right operator? Do i have to change the name of the list and the input getting compared or
There are quite a few things wrong in this code, but you've managed to use what you know and are in the right tracks so rather than giving you a solution I'll just review it for now.
Mostly, I'd recommend to keep your calculate function simple and handle the looping (rather than recursion) somewhere else.
def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op: # this will never be true because operator is a string, use `not in`
calculate() # you probably don't want to run calculate again, maybe return early
number_1 = float(input("What is your first number? "))
if number_1 != float: # number_1 is a float it's not the `float` type so always True
calculate() # return
number_2 = float(input("What is your second number? "))
if number_2 != float: # same as number_1 above
calculate() # return
if operator == "+": # this block is good, simple and to the point
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input") # here you also want to retry
calculate() # but not by recursing
again() # and definitely not call again
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit # what is this exit ?
else:
print("Wrong Input")
again() # also don't recurse this, loop if you want
calculate()
I'm a beginner to coding, and I'm still doing my "first" calculator, and I was wondering how to make only 5 characters ("-" "+" "/" "x" "^") into the only possible input the user can answer, or it will result in a message saying "Invalid", sorry for my limited knowledge about this, it's also my first post here, thanks in advance! This is what I did so far -
try:
number_1 = float(input("Insert number 1 here: "))
sign = str(input("+ - / x ^: "))
number_2 = float(input("Insert number 2 here: "))
except ValueError:
print("Invalid")
exit()
if sign != "-" "+" "/" "x" "^":
print("Invalid")
exit()
elif sign == "-":
print(number_1 - number_2)
elif sign == "+":
print(number_2 + number_1)
elif sign == "/":
if number_2 == 0:
print("Invalid")
exit()
print(number_1 / number_2)
elif sign == "x":
print(number_1 * number_2)
elif sign == "^":
print(number_1 ** number_2)
else:
print("Invalid")
You can use the power of functions! Make a function that repeatedly asks for user input until they give you something valid!
def ask_float(title):
while True:
try:
return float(input(title))
except ValueError:
print("Invalid choice. Try again!")
def ask_sign():
while True:
sign = input("+ - / x ^: ").strip()
if sign in ("+", "-", "/", "x", "^"):
return sign
print("Invalid choice. Try again!")
Now in your code you can do:
number_1 = ask_number("Insert number 1 here: ")
sign = ask_sign()
number_2 = ask_number("Insert number 2 here: ")
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
calculate()
cont()
Your program is throwing error because result is local variable of calculate() . In order to access it in cont() , you have to make it global .
def calculate():
#global variable
global result
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
global result
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
#variable declaration
result=None
calculate()
cont()
The result variable is local. Define the result variable globally. And, use global result inside the function implementation, to instruct the function not to create a new variable result, rather update the global variable.
Here is a hint.
result = 0 # default value
def function(n1, n2, operation):
global result
if operation == '+':
result = n1 + n2
return result
else:
return 0
Digressing a bit from the question, give a thought about the following code (python3+):
def function(n1, n2, operation):
if operation == '+':
print(f'{n1} + {n2} = {n1+n2}')
return n1 + n2
else:
return 0
I am working on creating a Calculator i want to be able to ask the user if he wants to clear the result or reuse the result with a second number to create a new result. any tips or help is appreciated
def cally():
op = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
n1 = float(input('Please enter the first number: '))
n2 = float(input('Please enter the second number: '))
if op == '+':
print(n1 + n2)
elif op == '-':
print(n1 - n2)
elif op == '*':
print(n1 * n2)
elif op == '/':
print(n1 / n2)
else:
print('You have not typed a valid operator')
cally()
def again():
calc_again = input("Do you want to calculate again?Please type Y for YES or N for NO.")
if calc_again == 'Y':
cally()
elif calc_again == 'N':
print('See you later.')
else:
again()
cally()
Modify cally() to add an optional argument which is the previous result. If this argument is present, use it as n1 instead of prompting. Also return the current result after printing it.
Then, after you call cally(), save its result in a variable, and if the user says they want to reuse the last result, pass that same variable back in to the next call to cally().
you can combine them into the same function and feed the previous result into the next operation as follows:
def cally(last_result=None):
op = input('''Please type operator''')
if last_result:
n1=float(last_result)
else:
n1 = float(input('Please enter the first number: '))
n2 = float(input('Please enter the second number: '))
if op == '+':
res = (n1 + n2)
elif op == '-':
res = (n1 - n2)
elif op == '*':
res = (n1 * n2)
elif op == '/':
res = (n1 / n2)
else:
print('You have not typed a valid operator')
return
print(res)
calc_again = input("Do you want to calculate again? Please type Y for YES or N for NO.")
if calc_again == 'Y':
cally(res)
elif calc_again == 'N':
print('See you later.')
cally()
EDIT - just saw John Gordon's answer, this is basically an implementation of it
Here I m making a small calculator. accepting two numbers and one operator this will be easy while I'm using function but in this I'm using the while condition statement but there is a error it will not breaking while every operation it will ask to user that it will want to any operation again in 'Y' for yes and 'N' for no but There is an error it will not changing the value of n. Below is my program:
n = 1
def again(number):
print('value of n in again fucntion', n)
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
else:
again(n)
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
again(n)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
again(n)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
again(n)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
again(n)
else:
print('You have not typed a valid operator, please run the program again.')
Can anybody please help me for solving this. Thanks in advance.
You use the local variable number in again, but use n outside. You have to assign the return value of again to n.
def again():
while True:
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
n = 1
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
n = again()
If you want to break your loop, then simply use break where you want the loop to stop.
Edit:
Your loop can be like:
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
if again(n) == 0:break
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
if again(n) == 0:break
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
if again(n) == 0:break
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
if again(n) == 0:break
else:
print('You have not typed a valid operator, please run the program again.')
There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
The final code will be something like this.
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
return True
elif calc_again.upper() == 'N':
return False
else:
return again()
while True:
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
break
if not again():
break
You can simplify your code as follow, and to avoid unnecessary recursion in the code:
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"/": lambda x, y: x / y,
"*": lambda x, y: x * y
}
continue_calculation = ""
while True:
calc_again = input('''Do you want to calculate again?Please type Y for YES or N for NO.''')
if calc_again == "n" or calc_again == "N":
break
operation = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
try:
print(operations[operation](number_1, number_2))
except:
print('You have not typed a valid operator, please run the program again.')