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

2024-10-03 23:21:39 发布

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

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

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])

嗨:所需输出如下: 哦,德拉雷!哦,德拉雷!算命先生! 财富预测!幸运符! 嗯……未来是多云的。你的名字叫什么?莱娅·奥加纳 哦,迪雷利!多刺激啊!你今天想得到多少财富?5 你今天的课程总数是:10.8455 我来给你算命。莱娅·奥加纳,输入你的幸运整数。300 哦,莱娅奥加纳。除非你输入一个有效的数字,否则我不能给你算命 莱娅·奥加纳!今天是你的幸运日! 你的名字将被载入史册 我来给你算命。莱娅·奥加纳,输入你的幸运整数 哦,莱娅奥加纳。除非你输入一个有效的数字,否则我不能给你算命 莱娅·奥加纳!今天是你的幸运日! 你注定要成为一名程序员 我来给你算命。莱娅·奥加纳,输入你的幸运整数。0 莱娅·奥加纳!今天是你的幸运日! 你将掌握Python 我来给你算命。莱娅·奥加纳,输入你的幸运整数 哦,莱娅奥加纳。除非你输入一个有效的数字,否则我不能给你算命 莱娅·奥加纳!今天是你的幸运日! 您将经常测试您的代码 我来给你算命。莱娅·奥加纳,输入你的幸运整数。50000 哦,莱娅奥加纳。除非你输入一个有效的数字,否则我不能给你算命 莱娅·奥加纳!今天是你的幸运日! 你将掌握Python 您输入了以下幸运数字: [99, 3, 0, 7, 100] 进程已完成,退出代码为0 地址:


Tags: tomasteryouforwith数字整数be
2条回答

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

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

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])

我希望这有帮助

相关问题 更多 >