I am able to make calculator using the If and elsif statement but I am unable to make it with the switch case statement.
I create basic for switch case but I stacked in how to take argument and how to call that.
Please anyone can help me.
Thank you in advance
Python switch case allowing optional arguments
I tried this but not working
def addition(num1,num2):
num1 += num2
return num1
def subtraction(num1,num2):
num1 -= num2
return num1
def mul(num1,num2):
num1 *= num2
return num1
def division(num1,num2):
num1 /= num2
return num1
def module(num1,num2):
num1 %= num2
return num1
def default(num1,num2):
return "Incorrect day"
switcher = {
1: addition,
2: subtraction,
3: mul,
4: division,
5: module
}
def switch(operation):
return switcher.get(operation, default)()
print('''You can perform operation
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Module ''')
#Take input from user
choice = int(input("Select operation from 1,2,3,4 : "))
print (switch(choice))
Good news for you, if you are still interested in using the switch case in Python.
you can now use match with Python 3.10
like this:
match operation:
case 'Addition':
return num1+num2
case 'Subtraction':
return num1-num2
case 'Multiplication':
return num1*num2
case 'Division':
return num1/num2
case 'Module':
return num1%num2
For more details read click here to read this python documentation
# ...
def switch(operation, num1, num2):
return switcher.get(operation, default)(num1, num2)
# ...
Another option is to return a function from switch and call it
# ...
def switch(operation):
return switcher.get(operation, default) # <- no () here, i.e. no calling the function
# ...
print(switch(operation)(num1, num2)) # call the returned function here
You just need to get two numbers as input to perform operation on. Try this
def addition(num1, num2):
num1 += num2
return num1
def subtraction(num1, num2):
num1 -= num2
return num1
def mul(num1, num2):
num1 *= num2
return num1
def division(num1, num2):
num1 /= num2
return num1
def module(num1, num2):
num1 %= num2
return num1
def default(num1, num2):
return "Incorrect day"
switcher = {
1: addition,
2: subtraction,
3: mul,
4: division,
5: module
}
def switch(operation, num1, num2):
return switcher.get(operation, default)(num1, num2)
print('''You can perform operation
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Module ''')
# Take input from user
choice = int(input("Select operation from 1,2,3,4 : "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print (switch(choice, num1, num2))
Try this
def switch(operation):
return switcher.get(operation, default)
print (switch(choice)(6,2))
Related
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()
My code will not run and i'm not sure whats wrong.
I have changed the kernel multiple times, but it is still not running.
This is the addition function of a calculator
def add(num1, num2):
sum = num1 + num2
return sum
This is the subtraction function of a calculator
def subtract(num1, num2):
difference = num2 - num2
return difference
This is the multiplication function of a calculator
def multiply(num1, num2):
product = num1 * num2
return product
This is the division function of a calculator
def divide(num1, num2):
if num1 != 0:
quotient = num2 / num1
return quotient
else:
return 0
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
if operator == "+":
answer = add(num1, num2)
elif operator == "-":
answer = subtract(num1, num2)
elif operator == "*":
answer = multiply(num1, num2)
elif operator == "/":
answer = divide(num1, num2)
else:
print("This is not a valid operation!")
print(str(answer))
I have not gotten any error messages at all. It just won't run.
Your print output was inside the division function.
You could do this as Short version:
def calc(operator, x, y):
return {
'+': lambda: x + y,
'-': lambda: x - y,
'*': lambda: x * y,
'/': lambda: x / y,
}.get(operator, lambda: "This is not a valid operation!")()
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
print(calc(operator, num1, num2))
it seems like you mistakenly put your "main" stuff (i.e the bit that actually controls
the flow your program) inside of your divide(num1, num2) function. Which is why when you run your program nothing seems to happen.
To fix it, try the following (note that indentation level!)
def add(num1, num2):
sum = num1 + num2
return sum
def subtract(num1, num2):
difference = num2 - num2
return difference
def multiply(num1, num2):
product = num1 * num2
return product
def divide(num1, num2):
if num1 != 0:
quotient = num2 / num1
return quotient
else:
return 0
#Here is the code that actually runs the program, takes input, calls the functions, etc.
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
if operator == "+":
answer = add(num1, num2)
elif operator == "-":
answer = subtract(num1, num2)
elif operator == "*":
answer = multiply(num1, num2)
elif operator == "/":
answer = divide(num1, num2)
else:
print("This is not a valid operation!")
print(str(answer))
our class recently got into defining functions but I'm having trouble with a specific block of code. Upon running, my code yields a 'opChoose' is not defined. The traceback faults this line of code:
calc(opChoose,num1, num2)
The code below is the entirety of my code, only a few lines of code.
def greeting():
print("Welcome to the calculator app!")
def menu():
opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
return opChoose
def numbers():
num1=float(input("Enter your first value"))
num2=float(input("Enter your second value"))
return num1, num2
def calc(opChoose,num1, num2):
if opChoose == "1":
ans = num1 + num2
elif opChoose == "2":
ans2 = num1 - num2
elif opChoose == "3":
ans3 = num1 * num2
elif opChoose == "4":
ans4 = num1 / num2
return ans, ans2, ans3, ans4,
def display(ans, ans2, ans3, ans4):
if opChoose == "1":
print(ans)
elif opChoose == "2":
print(ans2)
elif opChoose == "3":
print(ans3)
elif opChoose == "4":
print(ans4)
greeting()
menu()
numbers()
calc(opChoose,num1, num2)
display(ans,ans2,ans3,ans4)
I would try to simplify this code into a smaller block for you guys to troubleshoot but I simply don't know if the other bits of code is incorrect too, any help you guys could give me would be much appreciated, thanks!
You're doing the right thing in returning the value from the function menu() but you need to then assign that returned value to a variable to be able to pass it to the calc() function. Alternatively you can pass the function call directly to the calc() function itself.
Either this:
opChoose = menu()
calc(opChoose ,num1, num2)
or this:
calc(menu(),num1, num2)
Know that it is going to throw errors for the same reason on num1 and num2 but I think from the above you can solve that issue. Good luck and happy coding!
Having the calculation return a lot of None variables for paths not taken seems like an ... odd design. Perhaps look at this instead.
def greeting():
print("Welcome to the calculator app!")
def menu():
opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
return opChoose
def numbers():
num1=float(input("Enter your first value"))
num2=float(input("Enter your second value"))
return num1, num2
def calc(opChoose, num1, num2):
# opChoose is an int; don't compare it to a string
if opChoose == 1:
ans = num1 + num2
elif opChoose == 2:
# The answer goes to the same variable in each case
ans = num1 - num2
elif opChoose == 3:
ans = num1 * num2
elif opChoose == 4:
ans = num1 / num2
return ans
# Very tempted to comment out this gratuitous verbosity
greeting()
# Capture the value from the function call
op = menu()
# Capture the values from the function call
n1, n2 = numbers()
# Capture the value from the function call
value = calc(op, n1, n2)
# No need for a separate function for this really
print(value)
I used different variable names in the main flow to emphasize that the variables inside the function calls are entirely different, and you cannot access variables inside a function from outside, or vice versa, without making additional explicit arrangements.
Making functions which do only one thing is a good idea in general, but perhaps this is still taking it a bit too far. Functions which don't do anything useful in isolation are just obscuring the flow of the code.
Here is a refactoring of your code.
def greeting():
print("Welcome to the calculator app!")
def menu():
opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
return opChoose
def numbers():
num1=float(input("Enter your first value"))
num2=float(input("Enter your second value"))
return num1, num2
def calc(opChoose,num1, num2):
ans=0
ans2=0
ans3=0
ans4=0
if opChoose == 1:
ans = num1 + num2
elif opChoose == 2:
ans2 = num1 - num2
elif opChoose ==3 :
ans3 = num1 * num2
elif opChoose == 4:
ans4 = num1 / num2
return ans, ans2, ans3, ans4
def display(opChoose,ans, ans2, ans3, ans4):
if opChoose == 1:
print(ans)
elif opChoose == 2:
print(ans2)
elif opChoose ==3:
print(ans3)
elif opChoose == 4:
print(ans4)
greeting()
opChoose=menu()
num1, num2=numbers()
ans,ans2,ans3,ans4=calc(opChoose,num1, num2)
display(opChoose,ans,ans2,ans3,ans4)
In your code you call menu() and other functions but you don't save the data they return. You need to assign to a variable for further processing or otherwise save the value.
You created opChoose as int but you are comparing it with a string ("1") variable -- int 1 and "1" can never be the same.
a=1
if(a=="1"):
print("this will never be printed")
I am a beginner in python programming and I encountered an issue with my code.
When a user types an invalid operation, it notifies the users but exits the program (line 33). How can I get it to ask user to enter a math operation again?
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
#Ask what math operation to perform
operation = input("What do you want to do? (+, -, *, /): ")
#If the operation is not +, -, *, or /, invalid operation
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print("You must enter a valid operation!")
#If valid, perform specified operation
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
main()
Simply ask the user to input it again:
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
#Ask what math operation to perform
operation = input("What do you want to do? (+, -, *, /): ")
#If the operation is not +, -, *, or /, invalid operation
while (operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print("You must enter a valid operation!")
operation = input("What do you want to do? (+, -, *, /): ")
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
main()
In case you are using Python2, you can't use input here because input() evaluates the input in the execution context. So, you should be using raw_input(). In case of Python-3.x, you can use input().
As far as your question is concerned, you can put it into a while loop.
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
while True:
#Ask what math operation to perform
operation = raw_input("What do you want to do? (+, -, *, /): ")
print "operation is ", operation, type(operation)
#If the operation is not +, -, *, or /, invalid operation
if operation != '+' and operation != '-' and operation != '*' and operation != '/':
print("You must enter a valid operation!")
#If valid, perform specified operation
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
return 0
main()
I'm trying to get convert this from python 3 to 2.7 and I think I may have messed up with the indentation. The shell provides an error message of:
line 20, if(operation == '+'), IndentationError: unexpected indent
I'd like to keep the code as intact as possible but I cannot see the bug! Ugh!
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else(operation == '/'):
print div(var1, var2)
main()
PEP8 recommends using 4 space indentation, here is the code of your calculator reformatted to 4 spaces:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and
operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else:
print div(var1, var2)
main()
The IndentationError exception on compilation, happened because you had the 20th line and those appearing after it overindented.
After that I found the else (else(operation == '/'):) which is invalid, because it does not need a condition, I replaced it by and else, because at this stage we are really sure the operation is '/'.
Side note:
As #Jkdc proposes we can also check operator strings using this approach, which is more readable, in my opinion:
if(operation not in ['+', '-', '*', '/']):
print "you must enter a valid operation"
else:
#Rest of the code
Basically, it checks if the operation string is not found in the list of operators, instead of comparing them separately on 4 conditions.