首页 > 解决方案 > 如何在 Python 3 的 for 循环中获取一项并专门做某事?

问题描述

这是代码:

ls = ['apple', 'banana', 'pear']


for z in ls:
    x = input("Do you like %s ?" %z)
    if x == 'yes':
        print('Cool, ' + z + ' is very good.')
        break
    elif x == 'no':   
        continue
    else:
        print('I am not sure what you want')

使用此代码,我想做两件事:

1 - 在它第二次循环之后(你喜欢香蕉吗?)我想打印一条消息。但只有在“你喜欢香蕉”之后,而不是在其他时间它循环。那么有没有办法只为其中一个循环打印一条消息?因为如果我这样尝试:

elif x == 'n':   
    print('are you sure you do not like it?')
    continue

它将打印列表中所有 3 个项目(苹果、香蕉和梨)的消息。

2 - 另一件事是设置当 else 语句运行时(用户输入与“是”或“否”不同的内容),我希望它在循环开始时重新启动(再次询问用户“做你喜欢苹果吗?”而不是继续第二项(“你喜欢香蕉”)。有没有办法将循环设置为回到开头?

希望问题足够清楚。

谢谢

标签: pythonpython-3.xlistloopsfor-loop

解决方案


我认为这是你需要的:

ls = ['apple', 'banana', 'pear']
i = 0
flag = True
while i<len(ls) :

    x = input("Do you like %s ?" %ls[i])
    if x == 'yes':
        print('Cool, ' + ls[i] + ' is very good.')
        flag = True
        break

    elif x == 'no':   
        if i >=1 and flag:
            print('are you sure you do not like it?')
            i = i -1
            flag = False
    else:
        i = -1
        flag = True
    i+=1

输出:

1.

Do you like apple ?no
Do you like banana ?no
are you sure you do not like it?
Do you like banana ?no
Do you like pear ?no

2.

Do you like apple ?yes
Cool, apple is very good.

3.

Do you like apple ?no
Do you like banana ?yes
Cool, banana is very good.

推荐阅读