Reputation:
The question is that
import math
f = 5.1
k = (math.ceil(f))
for num in range(k, 30):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)
then the result is
7
11
17
19
23
29
None
So, how do put those elements into a list? Just like
list = [ 7, 11, 13, 17, 19, 23, 29, "None" ]
Because I just want to print the first element of the list by using this way:
for i in x[:1]:
print (i)
7
Or is there any other way to solve?
Upvotes: 0
Views: 74
Reputation: 26600
Inside the part of your code you are doing a print, you can add a line to append to a list. Simply create a list outside of your loop, then append to it. Like this:
import math
your_list = [] # the new list you are going to use
f = 5.1
k = (math.ceil(f))
for num in range(k, 30):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)
your_list.append(num) # append the num to your list
If you are still looking to collect all numbers, but then when your calculations are complete you just want to print the first element in your list, just call print outside of your loop. So your code would now look like:
import math
your_list = [] # the new list you are going to use
f = 5.1
k = (math.ceil(f))
for num in range(k, 30):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)
your_list.append(num) # append the num to your list
print(your_list[0])
Upvotes: 1
Reputation: 318
Some additional points are math.ceil returns float so it should be coated with int. There is no need to print it using for loop.
import math
f = 5.1
required_list = []
k = int(math.ceil(f))
for num in range(k, 30):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
required_list.append(num)
print required_list[0]
Upvotes: 0
Reputation: 2338
To add to a list
, you must first create a list
, and then append
to it.
You can use [i]
to get the value at the desired index
myList = list() # Alternatively, myList = []
for i in range(0, 30):
myList.append(i)
print(myList[0])
Upvotes: 0