我正在研究一个计算器程序,要求用户输入执行程序的问题是我只希望程序循环的次数与输入的值一样多。不幸的是,程序只是继续循环。如何修复它以便它只在用户输入时运行x次?
loop=1
choice=0
while loop == 1:
print("Welcome to Calculator Function!")
n =input("How many operations do you want to do?: ")
for n in xrange(6):
print("Your options are:")
print(" ")
print("1) Addition")
print("2) Subtraction")
print("3) Multiplication")
print("4) Division")
print("5) Quit CalculatorFunction.py")
print(" ")
choice = input("Choose your option: ")
if choice == 1:
add1 = input("Add what: ")
add2 = input("To what: ")
print add1, "+", add2, "=", add1+add2
elif choice == 2:
sub2 = input("Subtract what: ")
sub1 = input("From what: ")
print sub1, "-", sub2, "=", sub1-sub2
elif choice == 3:
mult1 = input("Multiply what: ")
mult2 = input("To what: ")
print mult1, "*", mult2, "=", mult1*mult2
elif choice == 4:
div2= input("Divide what: ")
div1= input("From what: ")
print div1, "/", div2, "=", div1/div2
elif choice == 5:
loop = 0
print"Thank you for using CalculatorFunction.py have a good day!"
else:
print"No selection made, please try again."
return[n() for n in xrange(6)]
答案 0 :(得分:1)
你需要在n
范围内循环并在该循环之外突破
choice = 0
while True: # while True will keep going until we break
print("Welcome to Calculator Function!")
n = input("How many operations do you want to do?: ")
for _ in xrange(n): # how many times user want to use the calc
print("Your options are:")
print(" ")
print("1) Addition")
print("2) Subtraction")
print("3) Multiplication")
print("4) Division")
print("5) Quit CalculatorFunction.py")
print(" ")
choice = input("Choose your option: ")
if choice == 1:
add1 = input("Add what: ")
add2 = input("To what: ")
print add1, "+", add2, "=", add1+add2
elif choice == 2:
sub2 = input("Subtract what: ")
sub1 = input("From what: ")
print sub1, "-", sub2, "=", sub1-sub2
elif choice == 3:
mult1 = input("Multiply what: ")
mult2 = input("To what: ")
print mult1, "*", mult2, "=", mult1*mult2
elif choice == 4:
div2= input("Divide what: ")
div1= input("From what: ")
print div1, "/", div2, "=", div1/div2
elif choice == 5:
loop = 0
print"Thank you for using CalculatorFunction.py have a good day!"
else:
print"No selection made, please try again."
break # end after "n" loops
或者只是在没有while的情况下循环输入n
的范围:
loop=1
choice=0
print("Welcome to Calculator Function!")
n = input("How many operations do you want to do?: ")
for _ in xrange(n):
print("Your options are:")
print(" ")
print("1) Addition")
print("2) Subtraction")
print("3) Multiplication")
print("4) Division")
print("5) Quit CalculatorFunction.py")
print(" ")