Python - is this loop correct? - python

def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print("\t\t\tCalculator App")
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
#invalid operation
print("You have entered an invalid key")
else:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
if(operation == "+"):
print("Answer is: ", add(var1, var2))
elif(operation == "-"):
print("Answer is: ", sub(var1, var2))
elif(operation == "*"):
print("Answer is: ", multi(var1, var2))
else:
print("Answer is: ", div(var1,var2))
main()
rerun = input("ReRun? (y/n)")
while(rerun == "y"):
main()
rerun = input("ReRun? (y/n) ")
else:
exit()
Reading books, watching videos, and self study has been challenging.
Please let me know if this is the correct way to loop this program, i'm sure there are alternatives.

If you mean the rerun loop down at the bottom, the following is probably cleaner:
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
It should be noted that it defaults to rerunning if the user enters something not expected.

I would have done something like
operators = dict()
operators['+'] = lambda x,y: x+y
operators['-'] = lambda x,y: x-y
operators['*'] = lambda x,y: x*y
operators['/'] = lambda x,y: x/y
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if operation in operators:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
print("Answer is: ", operators[operation](var1, var2))
else:
print("You have entered an invalid key")
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
Which I believe is more readeable and easier to expand (add new operators)

Related

How do I write a calculator in python? [duplicate]

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

Newbie Help Required

I am Trying to execute a script in which if non integer value is enter is should catch with except but it doesn't seem to work ..in my case print(message) in except block is showing in output while executing but errors also come
print('Answer is :', add(num1, num2))
NameError: name 'num1' is not defined
I'm using python 3.8... kindly assist :
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def into(num1, num2):
return num1 * num2
def by(num1, num2):
return num1 / num2
print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice in ["1", "2", "3", "4"]:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except NameError:
print('Only Integers Allowed')
except ValueError:
print('Only Integers Allowed ')
else:
print("Invalid Input")
exit()
def calci():
if choice == "1":
print('Answer is :', add(num1, num2))
elif choice == "2":
print('Answer is :', subtract(num1, num2))
elif choice == "3":
print('Answer is :', into(num1, num2))
elif choice == "4":
print('Answer is :', by(num1, num2))
calci()
You have to exit() the if statement block so that the program doesn't call the calc() function. If you don't exit the if statement block the program calls the calc() function which is responsible for the error message.
Also, you have to pass the parameters choice, num1 and num2 to the calc() function.
I have edited the code a little bit, which might be useful. You can iterate the input() statement so that the user can give it another try after entering an invalid input.
print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice in ["1", "2", "3", "4"] :
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except(TypeError, NameError, ValueError):
print('Only Numbers Allowed !!!')
exit()
else:
print("Invalid Input")
exit()
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):
try:
return a/b
except ZeroDivisionError:
print("Undefined (Can't be divided by zero)")
def calc(choice, num1, num2):
if choice == "1":
print('Answer is :', add(num1, num2))
elif choice == "2":
print('Answer is :', subtract(num1, num2))
elif choice == "3":
print('Answer is :', multiply(num1, num2))
else:
print('Answer is :', divide(num1, num2))
calc(choice, num1, num2)

Basic Calculator in Python [closed]

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

Type Error: Int object is not callable

I have an error with my code when I try to run it.
CODE
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = input()
num1 = input("Enter your first number: ")
num2 = input("Enter your second number: ")
def addition(num1, num2):
num1
num2
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
num1
num2
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
num1
num2
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
num1
num2
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == "1":
addition
elif choice == "2":
subtraction
elif choice == "3":
multiply
elif choice == "4":
division
else:
print("Invalid Input")
Everything works until python is called to print the answer.
I am aware of the possible duplicates but none of the code provided there works.
The issue is in the lines -
if choice == 1():
addition
elif choice == 2():
subtraction
elif choice == 3():
multiply
elif choice == 4():
division
I have no idea what you want 1() to do, seems like a typo. Also you should be calling the functions addition , etc , like - addition(num1, num2) .
And choice is string not int . And you should convert num1 and num2 to int.
More issues in your code -
Why are you doing - num1 and num2 in your functions , it does not do anything, you can remove the first two lines of each function.
Your print function in wrong, in Python 3.x , the %(ans) should be inside the function, not outside it.
Code -
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s' %(ans))
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s' %(ans))
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s' %(ans))
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s' %(ans))
if choice == '1':
addition(num1, num2)
elif choice == '2':
subtraction(num1, num2)
elif choice == '3':
multiply(num1, num2)
elif choice == '4':
division(num1, num2)
The problem is due to this
if choice == 1():
Where as it should be
if choice == 1:
And you have to convert num1 and num2 to integer types
And you should call the function just not declare them that is
if choice == 1:
addition(num1, num2)
And you have to do this for other things
And after doing all the changes your program would look like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
ans = num1 + num2
print('Your answer is %s') %(ans)
def subtraction(num1, num2):
ans = num1 - num2
print('Your answer is %s') %(ans)
def multiply(num1, num2):
ans = num1 * num2
print('Your answer is %s') %(ans)
def division(num1, num2):
ans = num1 / num2
print('Your answer is %s') %(ans)
if choice == 1:
addition(num1,num2)
elif choice == 2:
subtraction(num1,num2)
elif choice == 3:
multiply(num1,num2)
elif choice == 4:
division(num1,num2)
else:
print("Invalid Input")
My changes would be:
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans=None
if choice == 1:
ans = num1 + num2
elif choice == 2:
ans = num1 - num2
elif choice == 3:
ans = num1 * num2
elif choice == 4:
ans = float(num1) / num2
if ans:
print('Your answer is %s') %(ans)
else:
print("Invalid Input")
The error with your current code is just with the brackets in your print statements. if instead of having %ans outside of the print statement, the code works when it is like this
print('Your answer is %s' %ans)
A neater version of the same code you just wrote looks like this
print("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division")
print("^ Operation 'ID' please enter the id of your choice")
choice = int(input())
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
def addition(num1, num2):
return num1+num2
def subtraction(num1, num2):
return num1-num2
def multiply(num1, num2):
return num1*num2
def division(num1, num2):
return num1/num2
if choice == 1:
ans = addition(num1,num2)
elif choice == 2:
ans = subtraction(num1,num2)
elif choice == 3:
ans = multiply(num1,num2)
elif choice == 4:
ans = division(num1,num2)
else:
print("Invalid Input")
if choice in range(4):
print('Your answer is %s' %ans)
Ironically, this has ended up with me writing an answer to my own question with admittedly some help from # Vignesh Kalai, although hid code was a little off. So before anything else I will address the changes to my code.
Firstly, instead of defining every operation I have linked than with the choice of their "ID"'s.
Secondly, I am using "" + str(x) to print the answers out instead of the admittedly bad idea of using %s.
REVISED CODE
choice = int(input("Operations: \n1. Addition \n2. Subtraction \n3: Multiplication \n4. Division\n^ Operation 'ID' please enter the id of your choice\n"))
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
if choice == 1: #Addition
num1
num2
ans = num1 + num2
print("Your answer is " + str(ans))
elif choice == 2: #Subtraction
num1
num2
ans = num1 - num2
print("Your answer is " + str(ans))
elif choice == 3: #Miltiplication
num1
num2
ans = num1 * num2
print("Your answer is " + str(ans))
elif choice == 4: #Division
num1
num2
ans = float(num1) / float(num2)
print("Your answer is " + str(ans))

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