首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中仅打印for循环中的某些条件

如何在python中仅打印for循环中的某些条件
EN

Stack Overflow用户
提问于 2019-02-18 12:38:01
回答 2查看 547关注 0票数 0

所以我尝试创建一个for循环来打印某个条件,但它一直打印所有的条件。如何让它停止并打印出我想要的结果?以下是我到目前为止所做的工作:

代码语言:javascript
复制
f_list = ['nothing','You will get an A', 'You will learn to program','You are destined to become a master coder','May the force be with you \n',
    'Wow. You look like a programmer','The code is strong with this one','You will be testing your code often','Taco cat spelled backwards is taco cat','Your name will go down, down, down in history \n',
    'You will master python']

for luckyInt in range(1 ,len(f_list)):
    if (luckyInt == 1):
        print(f_list[1])
    elif luckyInt == 2:
        print(f_list[2])
    elif luckyInt == 3:
        print(f_list[3])
    elif luckyInt == 4:
        print(f_list[4])
    elif luckyInt == 5:
        print(f_list[5])
    elif luckyInt == 6:
        print(f_list[6])
    elif luckyInt == 7:
        print(f_list[7])
    elif luckyInt == 8:
        print(f_list[8])
    elif luckyInt == 9:
        print(f_list[9])
    elif luckyInt == 10:
        print(f_list[10])

嗨:所需的输出是这样的:哦-de-la-lay!哦-德-拉-雷!算命先生!财运预告!幸运符!嗯,…未来是阴云密布的。你叫什么?Leia Organa Oo-dee-lally!多么激动人心啊!你今天希望得到多少财富?5今天你的总数将是: 10.8455,我会给你算命。莱娅·奥加纳,输入你的幸运数字300天哪,莱娅·奥加纳。我不能给你算命,除非你输入一个有效的数字。99莱娅·奥加纳!今天是你的幸运日!你的名字将被载入史册,我将为你算命。莱娅·奥加纳,输入你的幸运数字-3天哪莱娅·奥加纳。除非你输入一个有效的数字,否则我无法给你算命。3莱娅·奥加纳!今天是你的幸运日!你注定要成为一名编程高手,我会给你算命的。莱娅·奥加纳,输入你的幸运整数。0莱娅·奥加纳!今天是你的幸运日!你会成为巨蟒大师,我会给你算命的。莱娅·奥加纳,输入你的幸运数字-7天哪莱娅·奥加纳。除非你输入一个有效的数字,否则我无法给你算命。7莱娅·奥加纳!今天是你的幸运日!你会经常测试你的代码,我会给你算命的。莱娅·奥加纳,输入你的幸运数字。50000天哪。我不能给你算命,除非你输入一个有效的数字。100莱娅·奥加纳!今天是你的幸运日!你将掌握python你输入的幸运数字: 99,3,0,7,100进程结束,退出代码为0:

EN

回答 2

Stack Overflow用户

发布于 2019-02-18 12:52:26

我将打印所有内容,因为对于每个循环,它将输入一个条件..第一个循环将打印1,第二个循环将打印2,依此类推。请提供所需输出样本的详细信息

票数 1
EN

Stack Overflow用户

发布于 2019-02-18 13:08:16

我能够修复你的程序,现在它工作得很好。看起来已经很接近了,但是您需要给luckyInt一个值,然后在循环中将该值与索引进行比较;而不是使用luckInt作为索引。我添加了一个随机数生成器:

代码语言:javascript
复制
import random


def random_num(hi):
    lo = 0
    hi = hi-1
    return random.randint(lo, hi)


f_list = ['nothing', 'You will get an A', 'You will learn to program', 'You are 
destined to become a master coder \n',
'May the force be with you', 'Wow. You look like a programmer', 'The code is 
strong with this one \n',
'You will be testing your code often', 'Taco cat spelled backwards is taco cat \n',
'Your name will go down, down, down in history', 'You will master python']

luckyInt = random_num(len(f_list))

for i in range(len(f_list)):
    if luckyInt == i:
        print(f_list[i])

我希望这能帮到你

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54740566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档