python - 如何在 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 语句运行时(用户输入与“是”或“否”不同的内容),我希望它在循环开始时重新启动(再次询问用户“做你喜欢苹果吗?”而不是继续第二项(“你喜欢香蕉”)。有没有办法将循环设置为回到开头?
希望问题足够清楚。
谢谢
解决方案
我认为这是你需要的:
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.
推荐阅读
- wordpress - woocommerce_coupon_get_discount_amount 的折扣金额不正确
- javascript - 当我单击 span 标签时,我的复选标记框不会被选中是有原因的吗?
- java - NoSuchElementException 无限循环与 pmd DD 异常
- django - http.client - ConnectionResetError: [WinError 10054] 现有连接被远程主机强行关闭
- java - JDK 17 Foreign Memory API - 什么是最好的应用程序?
- sql - 按记录 ID 仅选择最近的记录
- java - 使用 MockK 模拟 Spring Repository 时,类 java.lang.Object 不能强制转换为类 Task
- next.js - 如何根据主机名重写主页
- c# - c#:如何在windows中创建一个自定义(虚拟)文件夹并用任意文件填充它
- r - 选择要放入 feols - fixst 包中的虚拟对象