将for循环的输出保存为列表或元组

时间:2017-05-09 05:12:14

标签: python-3.x for-loop

如何将for循环的输出保存为列表或元组?

# finding prime numbers in given range
num_range = int(input("Enter a number: "))
print ("Below are the Prime Numbers")
for num in range(2,num_range+1):
#    print (num,"is taken as num")
    for i in range(2,num):
#        print (i, "is taken as i")
        if num % i == 0:
            break          
    else: 
        print (num)

1 个答案:

答案 0 :(得分:0)

要保存素数,请检查以下代码

num_range = int(input("Enter a number: "))
p_num = []
print ("Below are the Prime Numbers")
for num in range(2,num_range+1):
#    print (num,"is taken as num")
    for i in range(2,num):
#        print (i, "is taken as i")
        if num % i == 0:
            break          
    else:
        p_num.append(num)
        print (num)

在您找到或打印列表时打印数字

print p_num