Loop to user prompt - python

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

Related

it is keep on printing [duplicate]

This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 2 years ago.
when i run this code it keeps on giving me the answer
here is my code
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
while True:
if operation == "+":
print num1 + num2
elif operation == "-":
print num1 - num2
elif operation == "*":
print num1 * num2
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
What you might want is to put the input taking code into the while loop:
while True:
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
`while True:` means Infinite Loop.
You can take input inside while loop or you can change the condition of while loop.
remove the while True: and it will only print out the answer once. while loops continue running as long as the argument is true and True is always true :P
What you probably want is for the application to keep calculating input from the user.
Try this
def calculate():
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
while True:
calculate()

My Python code will not run and I am not sure why, I have tried changing the kernel from 3.6 to 3.0

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

I want to make calculator using switch case statement in python

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

Trying to make a calculator, but code isn't working. How to fix?

This program is supposed to be a calculator. When I run the program it prints operation as this
I'm not sure how to fix this. I have been trying to make a simple calculator that runs in terminal for a few days now but nothing seems to work. I think I need to re-define the operation var to print it. I'm not sure how to do that.
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = input ("Number 1: ")
num2 = input ("Number 2: ")
operation = input ("Operation: ")
###The if statements of this program ###
if operation == "add":
(num1 + num2)
elif operation == "sub":
(num1 - num2)
elif operation == "mul":
(num1 * num2)
elif operation == "div":
(num1 / num2)
####The final code to print the product ####
print operation
You didn't call your functions in your if statements
if operation == "add":
print(add(num1, num2))
elif operation == "sub":
print(sub(num1, num2))
elif operation == "mul":
print(mul(num1, num2))
elif operation == "div":
print(div(num1, num2))
Also note that you can use a dict to grab the function and evaluate it
ops = {'add': add,
'sub': sub,
'mul': mul,
'div': div}
if operation in ops:
print(ops[operation](num1, num2))
else:
print('Invalid operator requested')
There are some issues in your code:
You're not calling the functions you defined.
You're not printing the result, you're printing the operator (and not even correctly).
You're applying the operations on string not numbers (input returns a string).
Use raw_input instead of input in Python-2.x.
A solution:
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = float(raw_input("Number 1: ")) # convert the input to float
num2 = float(raw_input("Number 2: ")) # convert the input to float
operation = raw_input("Operation: ")
# The result variable, it holds an error message, in case the use inputs another operation
result='Unsupported operation'
###The if statements of this program ###
if operation == "add":
result = add(num1, num2)
elif operation == "sub":
result = sub(num1, num2)
elif operation == "mul":
result = mul(num1, num2)
elif operation == "div":
result = div(num1, num2)
####The final code to print the product ####
print result
Here is what you need .............
python 3 and the following code
Make sure you are using python3 and not python
e.g. root#Windows-Phone:~$ python3 anyName.py
#The functions of this program
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
#The variables of this program
num1 = int(input ("Number 1: "))
num2 = int(input ("Number 2: "))
operation = input ("Operation: ")
#The if statements of this program
if operation == "add":
print(add(num1, num2))
if operation == "sub":
print(sub(num1 ,num2))
if operation == "mul":
print(mul(num1,num2))
if operation == "div":
print(div(num1,num2))

Simple python calculator converted from 3 to 2.7

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.

Categories

Resources