How can i make this part of my new code loop? - python

i want to make it so when you get your answer it automatically asks for another operator and another number until you type stop
like real calculators
from math import*
info = input("Would you like information? : ")
if info == "yes":`enter code here`
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
num1 = float(input("Enter your first number: "))
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")

from math import *
info = input("Would you like information? : ")
if info == "yes":
print("+ = add")
print("- = subtract")
print("* = multiplication")
print("/ = division")
print("pow/power/p = raise to power")
while True:
num1 = input("Enter your first number: ")
if num1 == "stop":
break
num1 = float(num1)
op = input("Enter your operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "pow" or "power" or "p":
print(pow(num1, num2))
else:
print("Something went wrong please try again")
print("Code finished")
It obviously does not take edge cases into concideration (like division by zero, making sure that the stuff that you pass to float() is actually a number) but this should get you going :)
cheers.

Related

Do while loop in Python 3

I wanted to have some sort of thing that if the user inputs "Quit", the program breaks. I think that I could achieve that with a do while loop but I don't understand how to implement it. Please help me.
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter second number: "))
op = input("Enter Operator: ")
if op == "*":
print(num1 * num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "%":
print(num1 % num2)
else:
print("Invalid Operator")
while True:
try:
#insert your "loop" here
[.....]
except ValueError:
#restart the loop
continue
else:
#exit the loop
break
while True:
while True:
num1 = input("Enter First Number: ")
if num1.lower() == "quit":
quit()
try:
num1 = int(num1)
break
except ValueError:
print(f"{num1} is not an integer.")
while True:
num2 = input("Enter second number: ")
if num2.lower() == "quit":
quit()
try:
num2 = int(num2)
break
except ValueError:
print(f"{num2} is not an integer.")
op = input("Enter Operator: ")
if op.lower() == "quit":
quit()
if op == "*":
print(num1 * num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "%":
print(num1 % num2)
else:
print("Invalid Operator")

I build a calculator and I want to give error if they didn't type any number

Code works pretty well if you enter an actual number and operator and it actually gives u an error code if you enter an invalid operator but I want to give same error code with numbers but I dont know how I use python 3.9 help plz
num1 = float(input('Enter First Number:'))
op = input('Enter operator:')
num2 = float(input('Enter Second Number:'))
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
else:
print('enter an operator plz')
You want to use try/catch statements and/or while loops around each step.
flag1,flag2,operator =True,True,True
while flag1:
try:
num1 = float(input('Enter first Number:'))
flag1 = False
except ValueError:
print("Enter a valid first number please")
while operator:
op = input('Enter operator:')
if not (op=='+' or op =='-' or op =='*' or op=='/'):
print('Enter a valid operator please')
else:
operator=False
while flag2:
try:
num2 = float(input('Enter second Number:'))
flag2 = False
except ValueError:
print("Enter a valid second number please")
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
Maybe try something along the lines of this:
invalid = True
while invalid:
try:
num1 = float(input('Enter First Number:'))
op = input('Enter operator:')
num2 = float(input('Enter Second Number:'))
invalid = False
except ValueError:
print("Please enter a valid number")
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
else:
print('enter an operator plz')

it is keep on printing [duplicate]

This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 2 years ago.
when i run this code it keeps on giving me the answer
here is my code
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
while True:
if operation == "+":
print num1 + num2
elif operation == "-":
print num1 - num2
elif operation == "*":
print num1 * num2
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
What you might want is to put the input taking code into the while loop:
while True:
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
`while True:` means Infinite Loop.
You can take input inside while loop or you can change the condition of while loop.
remove the while True: and it will only print out the answer once. while loops continue running as long as the argument is true and True is always true :P
What you probably want is for the application to keep calculating input from the user.
Try this
def calculate():
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
while True:
calculate()

How to store result of simple python calculator in variable

I am a beginner to Python and have just started learning recently.
After learning about if, elif and else statements I decided to try and make a simple calculator.
Now, a few hours later I was wondering how I could improve it and make it more complex.
I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.
I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.
I'd really appreciate any help at all, Thank you!
Python code:
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1 == "yes" or "Yes":
operator1 = num4 = float(input("Please enter second number: "))
else:
print("Fatal error")
input("please enter operator")
if operator == "/":
print(num3 / num4)
elif operator == "+":
print(num3 + num4)
elif operator == "-":
print(num3 - num4)
elif operator == "*":
print(num3 * num4)
else:
print("Please press enter to close.")
input("Press Enter to Exit")
In the first part, just assign to a variable (and then print it if you want):
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
print(num3)
Regarding the second part of your question, in your statement:
if continue1 == "yes" or "Yes":
this is wrong because or is an operator which will combine the two things on either side of it (typically used where each of these two things is something that evaluates to True or False), so you could have for example:
if continue1 == "yes" or continue1 == "Yes":
You can also add brackets to control the order of execution, as shown below. In this case they do not affect the result, because it is already the case that the == operators are evaluated before the or, but they may make it clearer to read.
if (continue1 == "yes") or (continue1 == "Yes"):
You can also do this instead:
if continue1 in ("yes", "Yes"):
The details of what is going wrong with your original form of the conditional statement are perhaps not important at this stage, but I mention them for sake of completeness. If you enter "No" then the whole expression will actually evaluate to "Yes" (the continue1 == "yes" evaluates to False, and then False or "Yes" evalues to "Yes"). The if statement then treats the value "Yes" (a non-empty string) as a true value and so executes the code which depends on the condition.
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
keepCalculate=True
while keepCalculate:
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1== "yes" or "Yes":
keepCalculate=True
else:
keepCalculate=False
The most simple way todo what you want
simply use
num3 = num1 + num2
to store the codes
"or" in programming doesn't work like or in rel life, it is ussed to separate 2 different conditions, hence use:
if continue1 == "yes" or continue1 == "Yes":
I recreated your code now it's working:
def op(operator,num1,num2):
global num3
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
op(operator,num1,num2)
print(num3)
continue1 = input ("Would you like too continue? [Yes/No]").lower()
if continue1 in ["yes", "y"]:
num4 = float(input("Please enter second number: "))
operator = input("please enter operator")
op(operator,num3,num4)
print(num3)
else:
print("Fatal error")
input("Press Enter to Exit")
Whatever you do, this code will keep as result, the value of num3 = num1 * num2. You should put these lines in each if, elif

what's wrong with my simple calculator, it doesn't error and doesn't execute

I can't quite figure out why my code won't work.
Whenever I click run, it doesn't follow back with a traceback error, it just says process finished with exit code 0.
I thought it might be the casefold but then when I applied it to "Y". casefold it wouldn't work full stop.
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
Just add calculate() at the very end to call the function.
Put function calling calculate() at the end without any indent. Your function isn't even getting called, thus giving no error.
You need to call this calculate() function first (at least it's not being executed in your code sample).
def calculate()
# func code here
#Exec this function
calculate()
I guess it should be like this:
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
calculate()

Categories

Resources