This is my code. I've imported a library as "lib". when for some reason I receive a ZeroDivisionError when I enter a zero for my second number. I believe it's the dictionary causing the issue or maybe the function that the division element the dictionary points to. I'm not allowed to have any exception handling in the library. any pointers would be very much appreciated.
import Mylib as lib
def user_data():
try:
lower_range = int(input("Please enter a lower range value "))
higher_range = int(input("Please enter a higher range value "))
first_number = int(input("Please enter your first number "))
second_number = int(input("Please enter your second number "))
dictionary = {'add': lib.addition(first_number, second_number),
'sub': lib.subtraction(first_number, second_number),
'mult': lib.multiply(first_number, second_number),
'div': lib.division(first_number, second_number)}
if lib.is_in_range(lower_range, higher_range, first_number) and lib.is_in_range(lower_range, higher_range,
second_number):
menu_selection(first_number, second_number, dictionary)
else:
print("The input values are out side the input ranges")
print("Please check the numbers and try again")
print("Thanks for using our calculator")
run_again()
except ValueError:
print("You must enter a number. Please try again")
user_data()
def menu_selection(first_number, second_number, dictionary):
options = ['1) Add two numbers', '2) Subtract two numbers', '3) Multiply two numbers', '4) Divide two numbers',
'5) Scalc', '6) All in one']
print(*options, sep="\n")
user_option = input("Please select your option ")
if user_option == '1':
print(first_number, '+', second_number, "=", dictionary['add'])
elif user_option == '2':
print(first_number, '-', second_number, "=", dictionary['sub'])
elif user_option == '3':
print(first_number, '*', second_number, "=", dictionary['mult'])
elif user_option == '4':
try:
print(first_number, '/', second_number, "=", dictionary['div'])
except ZeroDivisionError:
print("Can't divide a number by 0")
elif user_option == '5':
week_5()
elif user_option == '6':
print('All four calculations are', lib.allinone(first_number, second_number))
run_again()
def run_again():
finished = input("Would you like to run another calculation? Y or N ? ")
if finished == "Y":
user_data()
elif finished == "N":
input("Thank you for using the calculator. Press ENTER to exit")
exit()
else:
input("Invalid answer. Press Enter to exit")
exit()
def week_5():
try:
calc_string = input("Enter values in this format: number 1, number 2, operator to include the commas ")
print(lib.scalc(calc_string))
except ZeroDivisionError:
print("Can't divide a number by 0")
user_data()
Please see the lib library for further context
def scalc(p1):
lstring = p1.split(",")
if lstring[2] == "*":
res = multiply(int(lstring[0]), int(lstring[1]))
if lstring[2] == "+":
res = addition(int(lstring[0]), int(lstring[1]))
if lstring[2] == "-":
res = subtraction(int(lstring[0]), int(lstring[1]))
if lstring[2] == "/":
res = division(int(lstring[0]), int(lstring[1]))
return res
def addition(first_number, second_number):
return first_number+second_number
def subtraction(first_number, second_number):
return first_number-second_number
def multiply(first_number, second_number):
return first_number*second_number
def division(first_number, second_number):
return first_number / second_number
def is_in_range(lower_range, higher_range, numbers):
return lower_range <= numbers <= higher_range
def allinone(first_number, second_number):
addition(first_number, second_number), \
subtraction(first_number, second_number),\
multiply(first_number, second_number), \
division(first_number, second_number)
Since you cannot have error handling within the library, add a check for the second number before doing the calculation, see code below:
Since you cannot have error handling within the library, add a check for the second number before doing the calculation, see code below:
def menu_selection(first_number, second_number, dictionary):
options = ['1) Add two numbers', '2) Subtract two numbers', '3) Multiply two numbers', '4) Divide two numbers',
'5) Scalc', '6) All in one']
print(*options, sep="\n")
user_option = input("Please select your option ")
if user_option == '1':
print(first_number, '+', second_number, "=", dictionary['add'])
elif user_option == '2':
print(first_number, '-', second_number, "=", dictionary['sub'])
elif user_option == '3':
print(first_number, '*', second_number, "=", dictionary['mult'])
elif user_option == '4':
if (second_number != 0):
print(first_number, '/', second_number, "=", dictionary['div'])
else:
print("Can't divide a number by 0")
elif user_option == '5':
week_5()
elif user_option == '6':
print('All four calculations are', lib.allinone(first_number, second_number))
run_again()
Looks like the definition is listed in the error:
1 Traceback (most recent call last):
2 File "c:\Users\dduke\Documents\vsCode\stacks\zerodiv\test.py", line 75, in <module>
3 user_data()
4 File "c:\Users\dduke\Documents\vsCode\stacks\zerodiv\test.py", line 14, in user_data
5 'div': lib.division(first_number, second_number)}
6 File "c:\Users\dduke\Documents\vsCode\stacks\zerodiv\Mylib.py", line 27, in division
7 return first_number / second_number
8 ZeroDivisionError: division by zero
Notice specifically line 5 in the error. You can follow the progression of code to see how it ended up there.
After ended up on line 14 of test.py, we're taken to 27 on Mylib.py - which is trying to divide by zero.
Your function saw nothing wrong with the values provided and attempted to run the division code in test.py.
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: ")
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))
i want to make it so when you get your answer it automatically asks for another operator and another number until you type stop
like real calculators
from math import*
info = input("Would you like information? : ")
if info == "yes":`enter code here`
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
num1 = float(input("Enter your first number: "))
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")
from math import *
info = input("Would you like information? : ")
if info == "yes":
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
while True:
num1 = input("Enter your first number: ")
if num1 == "stop":
break
num1 = float(num1)
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")
print("Code finished")
It obviously does not take edge cases into concideration (like division by zero, making sure that the stuff that you pass to float() is actually a number) but this should get you going :)
cheers.