My code:
b="y"
ol=[]
#operations list
OPERATIONS = ["-", "+", "*", "/"]
op = input ("Please enter your first calculation\n")
while b=="y":
ops = op.split(" ")
#add arguments to list
for x in ops:
ol+=x
if ol[1] in OPERATIONS:
#make sure operator is an operator
print()
#make sure not dividing by zero
if ol[1] == "/" and ol[2] == "0":
print("Error")
b = input("Would you like to do another calculation (y/n)?\n")
if b == "y":
op = input("Please enter your calculation:\n")
continue
else:
break
else:
n1 = float(ol[0])
n2 = float(ol[2])
#calculations done here
if ol[1] == '-':
calc = n1-n2
if ol[1] == '+':
calc = n1+n2
if ol[1] == '/':
calc = n1/n2
if ol[1] == '*':
calc = n1*n2
print("Result: " + str(calc))
b = input("Would you like to do another calculation (y/n)?\n")
if b == "y":
op = input("Please enter your calculation:\n")
continue
else:
break
else:
print("Error")
How do I ensure that the program takes the new operation to the beginning of the loop instead of continuing to print the original calculation?
您需要在while循环中重置ol=[]
Your calculation is performed using a list of operations ol
generated from the variable ops
which is taken by splitting input ops
by a space.
You can achieve this by moving the ol=[]
into the loop:
b="y"
# Remove ol=[]
#operations list
OPERATIONS = ["-", "+", "*", "/"]
op = input ("Please enter your first calculation\n")
while b=="y":
ol = [] # Add here
However, there is a simpler approach. The variable ops
contains a list of operations from the split
( str.split
generates a list), and you're then copying this value into the list ol
. Instead you can split the string straight into the variable ol
as follows:
b="y"
#operations list
OPERATIONS = ["-", "+", "*", "/"]
op = input ("Please enter your first calculation\n")
while b=="y":
ol = op.split(" ")
This is neater, as you then don't require the extra ops
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.