首页 > 解决方案 > def函数后如何运行for循环?

问题描述

我试图在 def 函数之后运行最后一个 for 循环,但它并没有像我想象的那样运行。

lst = [] 

print(lst)
print('The queue is now empty...')

MaxQueue = int(input('\nSet The Maximum Queue to: '))

for i in range(0, MaxQueue): 
    print(lst)
    inn = input('Enter Name: ')
    lst.append(inn)  
print('')   
print(lst) 
print('The Queue is full..')   

def get_answer(prompt):
    while True:
        answer = input(prompt)
        if answer not in ('yes','no'):
            answer = input(prompt)        
        if answer in ('yes'):
            break         
        if answer in ('no'):
            exit()
    
print(get_answer('Do you want to start seriving? '))

for i in range(MaxQueue,0):
    print(lst)
    de = input('press (enter) to serve')
    print(lst.pop(0))

标签: pythonpython-3.xloopsfor-loop

解决方案


开头超过结尾的范围是空的。您get_answer还包含一些错误。

lst = [] 

print(lst)
print('The queue is now empty...')

MaxQueue = int(input('\nSet The Maximum Queue to: '))

for i in range(MaxQueue): 
    print(lst)
    inn = input('Enter Name: ')
    lst.append(inn)  

print('')   
print(lst) 
print('The Queue is full..')   

def get_answer(prompt):
    answer = None # set initial value to make sure the loop runs at least once
    while answer not in ('yes', 'no'):
        answer = input(prompt)
    if answer == 'no': 
        exit()
    
get_answer('Do you want to start serving? ')

for i in range(MaxQueue):
    print(lst)
    input('press (enter) to serve')
    print(lst.pop(0))

对于较大的程序,在中间通常不是一个好主意exit(),因为您可能想做其他事情,所以我们可以使用布尔逻辑并做类似的事情

def get_answer(prompt):
    answer = None # set initial value to make sure the loop runs at least once
    while answer not in ('yes', 'no'):
        answer = input(prompt)
    return answer == 'yes'
    
if get_answer('Do you want to start serving? '):
    for i in range(MaxQueue):
        print(lst)
        input('press (enter) to serve')
        print(lst.pop(0))

推荐阅读