I am trying to make an exit function in my calculator, I tried many ways but it does not work. I don't understand how to loop my code and no website explains what to do.
Here is my code:
#Variables:
about = (" + Addition, - Subtraction, * Multiplication, / Division, ** Exponent, % Remainder")
print( )
print(about)
print( )
#Functions:
#Returns the sum of num1 + num2
def add(num1, num2):
return num1 + num2
#Returns the difference of num1 - num2
def sub(num1, num2):
return num1 - num2
#Returns the product of num1 * num2
def mul(num1, num2):
return num1 * num2
#Returns the quotient of num1 / num2
def div(num1, num2):
return num1 / num2
#Returns the power of num1 ** num2
def px(num1, num2):
return num1 ** num2
#Returns the remainder of num1 % num2
def rem(num1, num2):
return num1 % num2
#Main area where all the magic happens
#Wrong operation
def main():
operation = input("What do you need me for? (+,-,*,/,**,%): ")
if(operation != '+' and operation != '-' and operation != '*'
and operation != '/' and operation != '**' and operation != '%'):
#invalid operation
print("Sorry, but that's not an operation")
#What the operations should do
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(round(add(var1, var2), 2))
elif(operation == '-'):
print(round(sub(var1, var2), 2))
elif(operation == '*'):
print(round(mul(var1, var2), 2))
elif(operation == '/'):
print(round(div(var1, var2), 2))
elif(operation == '**'):
print(round(px(var1, var2), 2))
elif(operation == '%'):
print(round(rem(var1, var2), 2))
#Exit function
close = input ("Do you want to exit?: ")
if(close == 'Yes' and close == 'yes'):
close()
elif(close == 'No' and close == 'no'):
main()
main()
Can someone explain to me why it's not working?
close can't be 'No' and 'no' at the same time, so it is always false.
So you probably meant close == 'No' or close == 'no'. But better way to do it is close.lower() == 'no'
And what you are doing is not a loop but a recursion (function main calls itself). If you need loop then try this:
while True:
# your code
close = input ("Do you want to exit?: ")
if close.lower() == 'yes':
break; # escapes the loop
Replace your main() function with the following one:
def main():
close = 'no'
while close.lower() == 'no':
print "inside while"
operation = input("What do you need me for? (+,-,*,/,**,%): ")
if operation not in ['+', '-', '*', '/', '**', '%']:
print("Sorry, but that's not an operation")
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(round(add(var1, var2), 2))
# ...
elif(operation == '%'):
print(round(rem(var1, var2), 2))
close = input ("Do you want to exit?: ")
close is initialized with 'no', so the loop is executed at least one time.
Instead of close == 'no' or close == 'No', you can use lower() like this: close.lower() == 'no'
You should use:
if operation not in ['+', '-', '*', '/', '**', '%']:
Instead of:
operation != '+' and operation != '-' and operation != '*' ...
I would like to exit even if the user said 'yea' or just 'y'
while True:
operation = input("What do you need me for? (+,-,*,/,**,%): ")
if operation not in ['+', '-', '*', '/', '**', '%']:
print("Sorry, but that's not an operation")
continue
....
close = input ("Do you want to exit?: ")
if close and close[0].lower() == 'y':
print('Bye')
return
It should deal with the empty string as well, when the user just hit enter.
Related
def main():
num1 = input("Write a number: ")
op = input("* or / or + or -: ")
num2 = input("Write another number: ")
result = None
if op == "+":
result = float(num1) + float(num2)
print(result)
elif op == "-":
result = float(num1) - float(num2)
print(result)
elif op == "*":
result = float(num1) * float(num2)
print(result)
elif op == "/" and num2 == 0:
result = None
print("You can't divide by zero")
main()
elif op == "/" and num2 != 0:
result = float(num1) / float(num2)
print(result)
while True:
main()
ans = input("Would you like to do another equation: ")
if ans == "yes":
main()
ans = input("Would you like to do another equation: ")
elif ans == "no":
exit()
I get this error even though i already had an elif statement for that case
File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 26, in
main()
File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 21, in main
result = float(num1) / float(num2)
ZeroDivisionError: float division by zero
The reason you're not catching the zero case is that num hasn't been converted to a float. Consider using try/except instead -- that way you don't need to try to predict whether the operation will fail, you can just let the operation itself tell you. This will also let you catch things like inputs that aren't valid numbers, or operations that aren't one of the valid options.
You can also save time by doing the float conversion as soon as possible -- if you use try/except, this lets you immediately re-prompt the user for valid input. If you return the answer (and let the caller print it) rather than assigning it to a result which you then print, you can easily break the loop once the function succeeds while also making each if block a single concise line.
Note that explicitly re-calling main() isn't necessary as long as it's in a while loop that continues until it's time to break.
def main() -> float:
while True:
try:
num1 = float(input("Write a number: "))
op = input("* or / or + or -: ")
num2 = float(input("Write another number: "))
if op == "+":
return num1 + num2
elif op == "-":
return num1 - num2
elif op == "*":
return num1 * num2
elif op == "/":
return num1 / num2
else:
raise ValueError(f"Invalid operation {op}")
except ZeroDivisionError:
print("You can't divide by zero")
except ValueError as e:
print(e)
while True:
print(main())
ans = input("Would you like to do another equation: ")
if ans == "no":
break
Convert num2 to a float, either before you test it or when you test it:
### ...
elif op == "/" and float(num2) == 0.0:
result = None
print("You can't divide by zero")
main()
elif op == "/" and float(num2) != 0.0:
result = float(num1) / float(num2)
print(result)
I am new to Python. I tried to make a simple calculator, but what is the problem?
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()
You call main from inside itself. Set this outside the function like this:
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() # Added main outside the function
Your main() has a Tab behind (before) it.
It didn't run for me at first.
The other things seem fine to me.
You could also have it in a loop if you want to make it nicer.
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))
if __name__ == '__main__':
while(True):
main()
if input('If you are done with calculating, type q: ') == 'q':
break
Just like how num1 will only except an integer, I want op to only except the symbols "/*-+" and if the person inputs something otherwise I can then throw up an "invalid operator" message right after they input something other than those 4 symbols.
try:
num1 = float(input("enter a number"))
op = input(("enter a operator"))
num2 = float(input("enter another number"))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
except ValueError:
print("invalid operator")
except:
print("invalid")
You can do a while loop and check the string each time user enters a value.
while True:
user_input = input('Operation: ')
if len(user_input) == 1 and user_input in '+-*/': break
else: print('Invalid operation!')
I took a different approach and only allowed the user to continue after entering valid information.
import operator
def get_int_only(s: str):
while True:
in_str = input(s)
try:
out = int(in_str)
except ValueError:
continue
else:
return out
def get_str_in_list_only(s: str, ls: list):
while True:
in_str = input(s)
if in_str in ls:
return in_str
table = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"//": operator.floordiv,
"^": operator.pow
}
num1 = get_int_only("Number 1: ")
num2 = get_int_only("Number 2: ")
op = get_str_in_list_only("Operator: ", table.keys())
print(table.get(op)(num1, num2))
Operator module
Dictionary datatype
You can try to make an array with all the operators, like so: operators = ['+', '-', '*', '/'] and then loop over each item and compare.
operators = ['+', '-', '*', '/']
for operator in operators:
if op == operator:
# Do something...
else:
print("Invalid operator")
break
I just want to start off by saying I know this code is wrong, I'm just testing
this is meant to be a calculator, as you may be able to see from the code I am trying to make the number they end with e.g.
10 + 10 = 20, they will keep the number 20 and can carry on with 20, I want to keep repeating that option
Code:
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main():
operation = input("Do you want to(+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
num2 = float(input("Choose another number: "))
if(operation == "+"):
answer = (add(num1, num2))
print(answer)
elif(operation == "-"):
answer = (sub(num1, num2))
print(answer)
elif(operation == "*"):
answer = (mul(num1, num2))
print(answer)
elif(operation == "/"):
answer = (div(num1, num2))
print(answer)
else:
print("Syntax error!")
def multiple(multiple):
multiple = input("would you like to carry the number(Y or N): ")
if(multiple == "Y" or multiple == "y"):
carry = input("(+,-,*,/): ")
num3 = int(input("choose a number: "))
if(carry == "+"):
print(answer + num3)
elif(carry == "-"):
print(answer - num3)
elif(carry == "*"):
print(answer * num3)
elif(carry == "/"):
print(answer / num3)
else:
print("Syntax Error!")
multiple = True
while multiple == True:
multiple()
choice = input("would you like multiple calculations? (Y or N): ")
while(choice == "y" or choice == "Y"):
main()
multiple()
multiple()
main()
error message:
line 56, in <module>
multiple()
NameError: name 'multiple' is not defined
p.s There may be some indentation errors in this as it pasted strange
You're trying to call the function multiple outside of the scope of the main function while it is only defined in it. Assuming that your indentation is as presented here, you need to move the definition of multiple outside of main so that it can be called.
Additionally, you're defining a variable named multiple which might create some problems. You should change it to something else.
I optimized your code a little and fixed it. It works fine so take a look at it.
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main(carry):
operation = input("Do you want to (+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
if carry == None:
num2 = float(input("Choose another number: "))
else:
num2 = carry
if(operation == "+"):
answer = add(num1, num2)
elif(operation == "-"):
answer = sub(num1, num2)
elif(operation == "*"):
answer = mul(num1, num2)
elif(operation == "/"):
answer = div(num1, num2)
print(answer)
return answer
if input("would you like multiple calculations? (Y or N): ") in ("y", "Y"):
domultiple = True
else:
domultiple = False
carry = None
while 1:
carry = main(carry)
if domultiple:
if input("would you like to carry the number (Y or N): ") in ("n", "N"):
break
else:
break
#Returns the sum of num1 and num2
while True:
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
#*, -, /, +
#remember brackets work like normal
def main ():
operation = input("What type of calculation would you like to make? +,-,/,*")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*'):
#operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(input("Enter num1:"))
var2 = int(input("Enter num1:"))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '*'):
print(mul(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
#Restarts the calculator
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == "y":
continue
else:
print ('Goodbye')
break
main(add)
Hi, beginner here. I am getting IndentationError: unindent does not match any outer indentation level. Any help would be nice. If I put the continue down any further, I get IndentationError: expected an indented block. Not sure what to do.
I got it on
File "", line 24
continue
^
IndentationError: expected an indented block
Your function should be like the below
def main ():
operation = input("What type of calculation would you like to make? +,-,/,*")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*'):
#operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(input("Enter num1:"))
var2 = int(input("Enter num1:"))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '*'):
print(mul(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
#Restarts the calculator
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == "y":
continue
else:
print ('Goodbye')
break
There were numerous misaligned chunks of code that I corrected for you. Also corrected other errors as well. Try to avoid while True: loops altogether as your program can easily get stuck in one and cause unintended consequences.
# Returns the sum of num1 and num2
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
# *, -, /, +
# remember brackets work like normal
def main():
operation = raw_input("What type of calculation would you like to make? +,-,/,*")
if (operation != '+' and operation != '-' and operation != '/' and operation != '*'):
# operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(raw_input("Enter num1:"))
var2 = int(raw_input("Enter num1:"))
if (operation == '+'):
print(add(var1, var2))
elif (operation == '/'):
print(div(var1, var2))
elif (operation == '*'):
print(mul(var1, var2))
elif (operation == '-'):
print(sub(var1, var2))
# Restarts the calculator
main()
answer = raw_input('Run again? (y/n): ')
while answer == "y":
main()
answer = raw_input('Run again? (y/n): ')
The error occurs due to bad indentation. In Python, bad indentation means odd number of spaces. For example, 0, 1 or 3 spaces is bad indentation.
For example
def main():
pass
Is valid indentation, as the statement pass under main function is having 4 spaces; instead if the statement pass is having 0, 1 or 3 spaces under main. Valid indentation includes even number of spaces 2, 4 etc.
Well, in short, indentation in Python should be 2 or 4 spaces.