1

我已经编写了一个代码并且它可以工作,现在因为代码中有变量我想在最后询问这个人是否希望退出/继续,他们说继续它一直回到第一个问题。还有一种方法可以在一开始就问问题要重复多少次。抱歉无法上传代码,因为它超过 150 行 ta Greggy D

4

4 回答 4

2
i = 0

def code_to_repeat():
    # whatever is your code
    print "I was repeated : " + str(i) +" times"

while(True):
    print "Do you want to run the code (Y/N) : "
    stri = raw_input()
    print "\n"
    if stri=="Y":
        i += 1
        code_to_repeat()
    elif stri=="N"
        print "exiting\n"
        break;
    else:
        print "Please Answer Y/N only.\n"
于 2012-05-12T13:05:03.663 回答
0

如果我正确理解你的问题,这样的事情可能会奏效。

def dostuff():
    ABC = raw_input("Enter Number (q exits): ")

    if(ABC.lower() == 'q'):  #Allow the user to enter q at this point to exit
       return False

    Product = int(raw_input("Enter Product:"))

    #do stuff to print out the cost of these items.

    #We could forgo the next lines and always return True here assuming the user
    #has more input if they didn't input 'q' for 'ABC'.  That's up to you.

    #return True

    print "Do you have more purchases [Y/N]?"
    answer=raw_input()
    return answer.upper() == 'Y'

while dostuff():
    pass

#same as:  
#while True:
#   if(not dostuff()): 
#      break
于 2012-05-12T13:00:16.340 回答
0

在 Python 中,while 循环应该可以让您完成目标。您可以使用这样的示例来解决您的问题:

while(raw_input()[0] != 'n'):
    print 'to exit print n'
于 2012-05-12T13:09:57.440 回答
0

while 循环应该适用于您的情况。

while(raw_input("to exit enter n ")[0] != 'n'):
        print("Doing some work in the loop, until user enters an 'n'.")

raw_input()

是询问用户输入的好方法,并允许您插入提示,例如

to exit enter n.

请记住,您应该检查多个“n”,例如用户是否按回车键。此外,执行简单的数据解析可能是有意义的,因此您可以做的不仅仅是响应是否有人输入了 n。

于 2012-05-13T12:07:11.113 回答