I'm trying to make a calculator that will either restart the script or stop it using "continue" and "break". Yet when I try to run it, it says continue is not in loop, can someone help please?
Here's the code:
import os
import sys
def add (x, y):
return x + y
def subtract (x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x ,y):
return x / y
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 > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
while True:
print ("Invalid Input")
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
if answer == "y":
continue
if answer == "n":
break
num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid Input")
Below works for me, #busybear is right, the indentation was off.
import os
import sys
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
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 > "4": # (REFER TO TAG 1) : Seeing if this would work ( something to compare to )
while True:
print("Invalid Input")
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
if answer == "y":
continue
if answer == "n":
break
num1 = (input("Enter first number: ")) # Got rid of float() before input
num2 = (input("Enter second number: ")) # Got rid of float() before input
if choice == "1": # Changed single speech mark to double.
print(num1,"+",num2,"=", add(num1,num2))
elif choice == "2": # Changed single speech mark to double.
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == "3": # Changed single speech mark to double.
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == "4": # Changed single speech mark to double.
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid Input")
Related
I am still new to programming and I wanted to do a simple calculator in python. However, I could only reach this point of my code:
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
float(variableA)
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
float(variableB)
break
else:
print("Incorrect input. Please try again.")
continue
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
Not sure why my if statement is not executing after all the correct inputs from the user. I mostly focused on the error handling part and after everything going well, the if statement is just not executing after that. There could probably be a simple mistake but even I can't understand what's going on here.
You have an issue with type casting. So when you are taking input from the user all the userInput is str not int, so you need to cast it like userInput = int(userInput) before doing further calculator operations.
Also, you need to assign the float casting to a variable like this variableA = float(variableA) and variableB = float(variableB) otherwise your add/sub/divide/multiply etc. will not do expected operations.
For example add will do concatenation i.e '2' + '4' = 24 not 2 + 4 = 6.0
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
variableA = float(variableA) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
variableB = float(variableB) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
userInput = int(userInput) # <-- fix this line
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
If the user input is supposed to be an int, convert it early and fail fast.
while True:
userInput = input(...)
try:
userInput = int(userInput)
except ValueError:
print("Not an integer, try again")
continue
if userInput in range(1, 7):
break
print("Number out of range, try again")
and similarly for the operands
while True:
variableA = input("Enter the first value: ")
try:
variableA = float(variableA)
break
except ValueError:
print("not a float")
There's little reason to convert the menu choice to an integer, though. You could simply write
while True:
userInput = input(...)
if userInput in "123456": # ... in ["1", "2", "3", "4", "5", "6"]
break
print("Invalid choice, try again")
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 a step away from completing my binary converter, though it keeps on repeating, it's and endless loop.
def repeat1():
if choice == 'B' or choice == 'b':
while True:
x = input("Go on and enter a binary value: ")
try:
y = int(x, 2)
except ValueError:
print("Please enter a binary value, a binary value only consists of 1s and 0s")
print("")
else:
if len(x) > 50:
print("The number of characters that you have entered is", len(x))
print("Please enter a binary value within 50 characters")
z = len(x)
diff = z - 50
print("Please remove", diff, "characters")
print(" ")
else:
print(x, "in octal is", oct(y)[2:])
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y)[2:])
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again? ")
print("")
if r == '1':
repeat1()
print("")
elif r == '2':
loop()
print("")
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
print("")
tryagain1()
I'm looking for a way to break the loop specifically on the line of code "elif r== '3':. I already tried putting 'break', but it doesn't seem to work. It keeps on asking the user to input a binary value even though they already want to stop. How do I break the loop?
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
return 0
else:
print("You didn't enter any of the choices! Try again!")
choice = try again()
if choice == 0:
return 0
print("")
tryagain1()
return is suppose to be used at the end of the Function or code when you have nothing else to do
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 would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if there is a way to let a user do another operation instead of having to restart the application.
If any importing is required (if you can) please list if it is compatible with cx_Freeze.
Source code:
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
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")
you can use something like this for input
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
Take a look at the changes I have made to your code as follows:
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
def input_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That was not a number")
# Keep going around the loop until the user chooses 5 to quit
while True:
print
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Quit")
choice = input("Enter choice(1/2/3/4/5):")
# Do they want to quit?
if choice == 5:
break
num1 = input_number("Enter first number: ")
num2 = input_number("Enter second number: ")
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("%s - Invalid input" % choice)
In order to ask for more input, you needed to wrap your prompts in a loop. You would then need to add an option to the user to allow them to quit.
Also, you can move the prompting for numbers to a function. This would keep asking for number if the user typed in a character.
This code snippet should help :-
def is_string(test_data):
if type(test_data) is str:
return True
else:
return False