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")
Related
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...:)
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))
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))
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'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.