返回开始或重复原始输入多次

2024-05-14 14:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法代码灰色助教
3条回答
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"

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

while(raw_input()[0] != 'n'):
    print 'to exit print n'

如果我正确地理解了你的问题,这样的方法可能会奏效。

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

相关问题 更多 >

    热门问题