How can I make a while Loop for the operators? - python

I spent 3+ hours, trying to make it work, but I failed so far. I couldn't make a while loop run for the operators. I added a while loop for the operator, but then it only returns to the second while loop which asks me to input the first and second number again while I already inputted the correct first and second number. I hope my question makes sense. Thanks very much!
# a better way
#stackOverFlow Reference Page:
# https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response
print("My first p calculator")
print("+ for Addition")
print("- for subtraction")
print("* for Multiplication")
print("/ for Division")
print("% for remainder")
while True:
result = 0
while True:
try:
first_num = float(input("Enter first number:"))
except ValueError:
print("Sorry, enter a number:")
continue
else:
break
while True:
try:
second_number = float(input("Enter 2nd number: "))
except ValueError:
print("Sorry, enter a number: ")
continue
else:
break
# How to create a while loop for the below operator to
# ask to input the correct operator, if I keep inputting wrong operators.
# Thanks Very Much!
operation = input("Enter Operator: ")
if operation == "+":
result = first_num + second_number
elif operation == "-":
result = first_num - second_number
elif operation == "*":
result = first_num * second_number
elif operation == "/":
result = first_num / second_number
elif operation == "%":
result = first_num % second_number
# This will RUN, but when operator is inputted WRONG, it will go back
# to ask me to enter first number and second number.(the 2nd While Loop I guess).
# I want it to ask for the input of Operator Again and Again UnTil the input is the correct operator.
# NOT go back to ask first number and second number.
# I tried to create the third while loop for the operators
# but I couldn't get it to run. only when back to 2nd while Loop.
#I thought it was indentation error, but I tried, still couldn't get it to work.
print(result)

I would use another while loop as follows:
while True
operation = input("Enter Operator: ")
if operation == "+":
result = first_num + second_number
elif operation == "-":
result = first_num - second_number
elif operation == "*":
result = first_num * second_number
elif operation == "/":
result = first_num / second_number
elif operation == "%":
result = first_num % second_number
else:
continue
break
You can also make the code simpler by using the operator module.
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
while True
operation = input("Enter Operator: ")
try:
result = ops[operation](first_num, second_number)
except KeyError:
continue
else:
break

You are missing a break command to end the parent while:
print("My first p calculator")
print("+ for Addition")
print("- for subtraction")
print("* for Multiplication")
print("/ for Division")
print("% for remainder")
while True:
result = 0
while True:
try:
first_num = float(input("Enter first number:"))
except ValueError:
print("Sorry, enter a number:")
continue
else:
break
while True:
try:
second_number = float(input("Enter 2nd number: "))
except ValueError:
print("Sorry, enter a number: ")
continue
else:
break
# How to create a while loop for the below operator to
# ask to input the correct operator, if I keep inputting wrong operators.
# Thanks Very Much!
operation = input("Enter Operator: ")
if operation == "+":
result = first_num + second_number
elif operation == "-":
result = first_num - second_number
elif operation == "*":
result = first_num * second_number
elif operation == "/":
result = first_num / second_number
elif operation == "%":
result = first_num % second_number
# This will RUN, but when operator is inputted WRONG, it will go back
# to ask me to enter first number and second number.(the 2nd While Loop I guess).
# I want it to ask for the input of Operator Again and Again UnTil the input is the correct operator.
# NOT go back to ask first number and second number.
# I tried to create the third while loop for the operators
# but I couldn't get it to run. only when back to 2nd while Loop.
#I thought it was indentation error, but I tried, still couldn't get it to work.
print(result)
break

From what I understood from your question one solution would be to create a array with all the operators and check if the operation entered by the user is inside that array, if not, then loop again asking for a new input, and if the operator is found inside the array, then just go through the if statements to perform the operation.
operators = ["+", "x", "-", "/", "%"]
operation = input("Enter Operator: ")
while(operation not in operators):
operation = input("Enter Operator: ")
#If loops here

I'd create a dict of the operators and then have my while ... input loop check to make sure the entered string is in the dict:
operators = {
'+': float.__add__,
'-': float.__sub__,
'*': float.__mul__,
'/': float.__truediv__,
'%': float.__mod__,
}
while True:
operator = input("Enter Operator: ")
if operator in operators:
break
result = operators[operator](first_num, second_number)

Related

Calculator not working if you enter a letter instead of a number

My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
It's printing the calculated value, but if you enter a letter instead of a number.
For example:
Enter a first number: 5
Enter a second number: f
Now it should print "enter a number". But im getting this message istead
ValueError: invalid literal for int() with base 10: 'a'
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
**else:
print("Enter a number.")**
You have lines like these:
if operator == '+':
result = int(number1) + int(number2)
Before lines like these:
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
So, if operater is indeed a +, Python will try to evaluate int(number1) + int(number2) and fail if number1 or number2 is not the string representation of a number.
This raises a ValueError (as it should) and a raised exception that isn't caught in a try .. except .. block will cause your program to terminated. You cannot continue with uncaught exceptions.
Either you should check first and then try to convert these strings, or you should catch the exception.
Also, you seem to expect your code to continue running after the mistake is made, so you'll need some sort of loop that keeps the program running until the user enters some input that makes sense.
I am not sure that I understood what you what but I think this solves the problem
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if number1.isdigit() == True and number2.isdigit() == True:
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
print (result)
else:
print("Enter a number.")
If you are just starting on coding, I suggest you to use this as a reason to search and learn on some few important concepts that will help you to get going.
First, you must validate your inputs before doing anything else with them. In your case, validate that your first and second numbers are actually valid integers, right after they are input. As it is the same validation to be done on both, you can create a function so you can reuse the logic.
def input_number():
num = input("Enter a number: ")
if num.isdigit():
return int(num)
else:
print("Invalid number.")
return input_number()
Here, I check if the input is valid (isdigit is true), and then I return the value already converted to int. If it is not, I call the same function again, and repeat the process. This is called recursion.
You should also validate the operator, because it is only valid among a few options.
def input_operator():
while True:
op = input("Enter the operation character: ")
if op in ["+", "-", "*", "/"]:
return op
else:
print("Invalid operator.")
Here I used a different technique. It is called while statement, and it will repeat the execution inside it until the condition is not True, or until it is explicitly broken (in this case, with a return statement).
Now, you have to add both function definitions on top of your code, then adjust you logic accordingly.
number1 = input_number()
operator = input_operator()
number2 = input_number()
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
elif operator == "*":
result = number1 * number2
elif operator == "/":
result = number1 / number2
print (result)

ZeroDivisionError: float division by zero even though i had a specific elif statement for that case

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)

Python Functions not being called. Only able to print the questions in my print statements

history = []
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
def main():
def summation():
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
first_num = str(input(":ype the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
print("The Previous result is: " + str(history()))
def exits():
print("Exiting...")
while True:
x = str(input("Type your option: "))
if x == "1" or x == "2" or x == "3" or x == "4":
break
if x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
else:
exits()
main()
The indentation of your while is wrong. It should be inside of your main function.
Try removing the main function and just let your script run the while loop.
Also break only during the input that you want to exit the loop. If nothing is after the loop, it exits the script; with your current logic, the while loop exits for every option, nothing is printed beyond your first line and your input prompt, then the main function gets ran, but nothing runs because the main function is actually empty (only defines other functions)
history = []
def summation():
global history
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
global history
first_num = str(input("Type the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
global history
print("The Previous result is: " + str(history))
def exits():
print("Exiting...")
while True:
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
x = str(input("Type your option: "))
if x == "4":
exits()
break
elif x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
Note: input() always returns a str type, so there's no reason to cast it

Calculator to execute loop until "exit"

I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.

One line, three variables

I am here trying to just make a simple calculator in python, and I wonder if its possible to make the 3 first lines in to one line when command run. What I mean with that is; I don't have to press enter to type the next number/operator but press space instead (in the input section).
while True:
import operator
num1 = int(input("Whats the first number:"))
oper = input("Which operator would you like to use: (+,-,/,*,**,^) :")
num2 = int(input("Whats the second number:"))
if oper == "+":
x = operator.add
elif oper == "-":
x = operator.sub
elif oper == "*":
x = operator.mul
elif oper == "/":
x = operator.__truediv__
elif oper == "**":
x = operator.pow
elif oper == "^":
x = operator.xor
else:
print("invalid input")
print(num1,oper,num2,"=",x(num1,num2))
You can use the split method of Python strings to accomplish this. Note that this code depends on three objects, separated by spaces, being entered. If more or fewer are entered or the spaces are forgotten, or either "number" is not actually an integer, there will be an error.
print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
Rory's answer and comments pointed on the right direction, but here's a practical example:
operators = ["+","-","/","*","**","^"]
msg = f"Example query: 8 * 4\nAllowed operators: {', '.join(operators)}\nType your query and press enter:\n"
x = input(msg)
cmd_parts = [y.strip() for y in x.split()] # handles multiple spaces between commands
while len(cmd_parts) != 3: # check if lenght of cmd_parts is 3
x = input(msg)
cmd_parts = [y.strip() for y in x.split()]
# verification of command parts
while not cmd_parts[0].isdigit() or not cmd_parts[2].isdigit() or cmd_parts[1] not in operators :
x = input(msg)
cmd_parts = [y.strip() for y in x.split()]
num1 = cmd_parts[0]
oper = cmd_parts[1]
num2 = cmd_parts[2]
res = eval(f"{num1} {oper} {num2}")
print(num1,oper,num2,"=", res)
Python Example (Enable Interactive mode)
calc=input("type here:- ").split()
# type belove with space between
num1,operatoe,num2=calc[:]
# if length of calc doesn't equal to three you can continue with while loop
print(num1,operator,num2)
An improved working calculator which handles some errors based on other answers:
import operator
x = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.__truediv__,
"**": operator.pow,
"^": operator.xor
}
while True:
print("Enter a number, a space, an operator, a space, and another number.")
try:
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)
print(num1,oper,num2,"=",x[oper](num1,num2))
except:
print("invalid input")

Categories