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.
Related
When I want to quit my calculator it works, but when I want to keep using it there comes a problem:
File "main.py", line 54, in <module>
main()
NameError: name 'main' is not defined
I want to keep looping it from the start if I type y or Y so that I could keep using it.
And if I type 9 after I use it, I can't come to the closing screen. So I want it to show the close screen and stop looping.
here's my code:
print("calculator")
print("1.Pluss")
print("2.Minus")
print("3.Ganging")
print("4.Deling")
print("9.Avslutt")
chr=int(input("1-4 eller Avslutt: "))
while True:
if chr==1:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=b+a
print("sum = ", c)
elif chr==2:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a-b
print("sum = ", c)
elif chr==3:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a*b
print("sum = ", c)
elif chr==4:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a/b
print("sum = ", c)
elif chr==5:
print("1-4 idiot")
elif chr==6:
print("1-4 idiot")
elif chr==7:
print("1-4 idiot")
elif chr==8:
print("1-4 idiot")
else:
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
It works if I want to quit, but it can't keep looping from the start after it comes to.
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
If you are offering an option to terminate (9. Avslutt) you don't need to ask user for confirmation of iteration. Just repeat the input prompts.
There's no need to convert the user input to int as the values are not used in any arithmetic context - i.e., they're just strings.
You may find this pattern useful:
from operator import add, sub, mul, truediv
OMAP = {'1': add, '2': sub, '3': mul, '4': truediv}
while True:
print("calculator")
print("1. Pluss")
print("2. Minus")
print("3. Ganging")
print("4. Deling")
print("9. Avslutt")
if (option := input('1-4 eller avslutt: ')) == '9':
break
if (op := OMAP.get(option)) is None:
print('Ugyldig alternativ')
else:
x = float(input('Number 1: '))
y = float(input('Number 2: '))
print(f'Resultat = {op(x, y):.2f}')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new to Python. I tried to make a basic calculator, but i can't really find the problem. It returns with 0 exit code, but nothing appears, no input no nothing. Any help with this will greatly be appreciated. Thank You.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main()
Based on the code above, you are never actually running main(). Right now, you have said that the definition of main is to prompt the user, check if the input was correct, and then do the math. The main() at the end causes the program to repeat after doing all this (not sure if you want the loop or not).
If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main(), because right now the indentation means it is inside of def main(). Just move it to the left to be at the same indentation level as the def main(): and your program should run fine.
I think you are missing:
if __name__ == "__main__":
main()
Your call to main() inside main itself won't execute and that's probably why you aren't getting any input.
Other than that your code should work as expected (make sure you don't divide by zero ;) ).
Edit: to make my answer more obvious, you should have done:
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == "__main__":
main()
num1=float(input("enter the first number :"))
op = input("sellect the operation :")
num2 = float(input("enter the second number :"))
if op== "+" :
print(num1+num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1*num2)
elif op == "/":
print(num1 / num2)
else:
print("please enter a real operation ")
#this one is more simple
Basic Calculator:
Method 1:
# 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")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
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("Invalid input")
Method 2:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
print(num1,"+",num2,"=", num1+num2)
elif choice == '2':
print(num1,"-",num2,"=", num1-num2)
elif choice == '3':
print(num1,"*",num2,"=", num1*num2)
elif choice == '4':
print(num1,"/",num2,"=", num1/num2)
else:
print("Invalid input")
Happy Learning...:)
I was asked to write a calculator in Python, and I completed it, but there is only one issue that needs to be fixed.
What is the prerequisite? "Once the user inputs/selects an arithmetic operation, the program should ask the user to enter the two operands one by one, separated by Enter key. If the user made a mistake while entering the parameters, he can return to main menu by pressing ‘$’ key at the end of the input string, followed by the Enter key.
I'll give you the code I wrote here, and I'd appreciate it if you could make this to get the return function.
def Add(a, b):
return a + b
# Function to subtract two numbers
def Subtract(a, b):
return a - b
# Function to multiply two numbers
def Multiply(a, b):
return a * b
# Function to divide two numbers
def Divide(a, b):
return a / b
# Function to power two numbers
def Power(a, b):
return a ** b
# Function to remaind two numbers
def Remainder(a, b):
return a % b
def Reset(a,b):
return print(choice)
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 choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if choice == '#':
print("Done. Terminating")
break
a = input('Enter first number: ')
print(str(a))
b = input('Enter second number: ')
print(str(b))
if choice == '+':
print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(float(a), "-",float(b), "=", Subtract(float(a), float(b)))
elif choice == '*':
print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**",float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')
```
This kind of task is best (IMHO) handled in a so-called "table driven" manner. In other words, you create a table (in this case a dictionary) that has all the options built into it. Your core code then becomes much easier and the functionality is more extensible because all you need to do is add to or take away from the dictionary.
This structure also demonstrates how the user can be prompted for more input if/when something goes wrong.
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):
return a / b
def Power(a, b):
return a ** b
def Remainder(a, b):
return a % b
options = {'+': ('Add', Add, '+'),
'-': ('Subtract', Subtract, '-'),
'*': ('Multiply', Multiply, '*'),
'/': ('Divide', Divide, '/'),
'^': ('Power', Power, '**'),
'%': ('Remainder', Remainder, '%'),
'#': ('Terminate', None)}
while True:
print('Select operation: ')
for i, (k, v) in enumerate(options.items(), 1):
print(f'{i}. {v[0]:<10}: {k} : ')
option = input(f'Enter choice ({",".join(options.keys())}) : ')
if control := options.get(option):
_, func, *disp = control
if not func:
break
a = input('Enter first number: ')
b = input('Enter second number: ')
try:
a = float(a)
b = float(b)
print(f'{a} {disp} {b} = {func(a, b)}')
except (ValueError, ZeroDivisionError) as e:
print(e)
else:
print('Invalid option!')
Thank you so much for all your responses. With your help I was able to come to a decisive conclusion very quickly.
This is the end result I got after the changes I made:
def Add(a, b):
return a + b
# Function to subtract two numbers
def Subtract(a, b):
return a - b
# Function to multiply two numbers
def Multiply(a, b):
return a * b
# Function to divide two numbers
def Divide(a, b):
return a / b
# Function to power two numbers
def Power(a, b):
return a ** b
# Function to remaind two numbers
def Remainder(a, b):
return a % b
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 choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if choice == '#':
print("Done. Terminating")
break
a = input('Enter first number: ')
print(str(a))
if a.endswith('$'): continue
b = input('Enter second number: ')
print(str(b))
if b.endswith('#'):
print("Done. Terminating")
break
if b.endswith('$'): continue
if choice == '+':
print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(a, "-", b, "=", Subtract(a, b))
elif choice == '*':
print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**",float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')
```
I think I found a way to do this.
You want to loop back to the menu where you ask to choose among math symbols.
You can add a while based on a variable (bool) set to True.
You then get two while loops.
reset = True
while reset:
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 : $ ")
Therefor if you spot any "$"in either a, b or your choice you can just break. You will come out of the second while loop and go back to the first one, printing the menu again.
But then you have to modify the behaviour when you encounter "#" because breaking now brings you back to the top and doesn't exit the program. You first have to set reset to reset = False then you can break, therefore exiting both loops.
if choice == '#':
print("Done. Terminating")
reset = False
break
if '$' in a or '$' in b or '$' in choice :
print("Resetting.")
break
You can learn more about nested while loops here :
https://code4coding.com/nested-while-loop-in-python/
To add clarity to you code you might want to get rid of all your functions since python have already builtin functions done with the corresponding math symbol ^^
EDIT : FULL SNIPPET
reset = True
while reset:
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 choice in ('+', '-', '*', '/', '^', '%', '#', '$'):
if '$' == choice :
print("Resetting.")
break
if choice == '#':
print("Done. Terminating")
reset = False
break
a = input('Enter first number: ')
print(str(a))
if '$' in a :
print("Resetting.")
break
b = input('Enter second number: ')
print(str(b))
if '$' in a or '$' in b :
print("Resetting.")
break
if choice == '+':
print(float(a), "+", float(b), "=", Add(float(a), float(b)))
elif choice == '-':
print(float(a), "-", float(b), "=", Subtract(float(a), float(b)))
elif choice == '*':
print(float(a), "*", float(b), "=", Multiply(float(a), float(b)))
elif choice == '/':
if int(b) != 0:
print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
break
else:
print("float division by zero")
print(float(a), "/", float(b), "=", "None")
elif choice == '^':
print(float(a), "**", float(b), "=", Power(float(a), float(b)))
elif choice == '%':
print(float(a), "%", float(b), "=", Remainder(float(a), float(b)))
break
else:
print('Not a valid number,please enter again.')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
#for project 2
# division
def divide(a, b):
return (a / b)
# palindrome
def isPalindrome(s):
return s == s[::-1]
print("Select operation.")
print("1. Divide")
print("2. Palindrome")
print("3. Square root")
while True:
choice = input("Enter choice(1/2/3): ")
if choice == '1':
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(num1, "/", num2, "=", divide(num1, num2))
elif choice == '2':
def isPalindrome(s):
return s == s[::-1]
s = str(input("Enter word:"))
ans = isPalindrome(s)
if ans:
print (s+" "+"is a palindrome.")
else:
print (s+" "+"is not a palindrome.")
elif choice == '3':
threenumber = float(input("Enter a number: "))
sqrt = threenumber ** 0.5
print ("The square root of " + str(threenumber) + " is " + "sqrt", sqrt)
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
When testing it myself, in the beginning, if I entered any other input rather than 1, 2, or 3, it would jump to the "next_calculation" function. I want it to say "That's not an option, silly." instead.
When I select 1 or 3 if I enter anything other than a number the program will stop. I want it to say "That's not a valid number, silly."
How do I do this?
You can do that with continue to ignore the loop and return to the start after checking if the input is in your list of possible values
if choice not in ('1', '2', '3'):
print("Invalid input")
continue
Put that after the input
I'd add right after choice = input("Enter choice(1/2/3): "), this snippet:
while (choice not in ['1','2','3']):
print("That's not a valid number, silly.")
choice = input("Enter choice(1/2/3): ")
In this way, you won't reach the end of the cycle unless you give a correct number.
I think you should try to use Switch in this case, instead of if/elses.
Check out this answer.
Otherwise, #Icenore answer seems to be correct. Also, remember to correctly ident your code, your current else: code is being executed after your while True:
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new to Python. I tried to make a basic calculator, but i can't really find the problem. It returns with 0 exit code, but nothing appears, no input no nothing. Any help with this will greatly be appreciated. Thank You.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main()
Based on the code above, you are never actually running main(). Right now, you have said that the definition of main is to prompt the user, check if the input was correct, and then do the math. The main() at the end causes the program to repeat after doing all this (not sure if you want the loop or not).
If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main(), because right now the indentation means it is inside of def main(). Just move it to the left to be at the same indentation level as the def main(): and your program should run fine.
I think you are missing:
if __name__ == "__main__":
main()
Your call to main() inside main itself won't execute and that's probably why you aren't getting any input.
Other than that your code should work as expected (make sure you don't divide by zero ;) ).
Edit: to make my answer more obvious, you should have done:
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == "__main__":
main()
num1=float(input("enter the first number :"))
op = input("sellect the operation :")
num2 = float(input("enter the second number :"))
if op== "+" :
print(num1+num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1*num2)
elif op == "/":
print(num1 / num2)
else:
print("please enter a real operation ")
#this one is more simple
Basic Calculator:
Method 1:
# 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")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
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("Invalid input")
Method 2:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
print(num1,"+",num2,"=", num1+num2)
elif choice == '2':
print(num1,"-",num2,"=", num1-num2)
elif choice == '3':
print(num1,"*",num2,"=", num1*num2)
elif choice == '4':
print(num1,"/",num2,"=", num1/num2)
else:
print("Invalid input")
Happy Learning...:)