简体   繁体   中英

Make list with while loop ? python3

I'm trying to make list contain (even numbers) with using while loop :

a=0
while a<8:
    a=a+2
    print(a,end=' ')
    t=list(a)
    print (t)

and how do I can make a code to division the numbers from the first list into two list: one for(even numbers) and the other for (odd numbers) ?

You can just create a list directly from each variable

>>> a = list(a)
>>> a
[1, 2, 3]

>>> b = list(b)
>>> b
['C', 'i', 't', 'y']

To make a list of even numbers using a while loop, you can do something like this

a = 0
t = []
while a < 8:
    t.append(a)
    a += 2

>>> print(t)
[0, 2, 4, 6]

Note that the above is just for learning purposes, this can be done using Python's range function more easily

>>> list(range(0, 8, 2))   # Evens
[0, 2, 4, 6]

>>> list(range(1, 8, 2))   # Odds
[1, 3, 5, 7]

Use list to convert.

In [1]: a=(1,2,3)

In [2]: list(a)
Out[2]: [1, 2, 3]

In [3]: b=('City')

In [4]: list(b)
Out[4]: ['C', 'i', 't', 'y']

Here is my answer to your question:

List = []
ListEven = []
ListOdd = []
Count = 0
while(Count < 11):
    print(Count, end = ' ')
    List.append(Count)
    if(Count % 2 == 0):
        ListEven.append(Count)
    elif(Count % 2 != 0):
        ListOdd.append(Count)
    Count += 1
print("\n""This is the main list:")
print(List)
print("This is the even list:")
print(ListEven)
print("This is the odd list:")
print(ListOdd)

I fixed the Count from Count += 2 to Count += 1 because you asked for a list of odds . The code you had would only produce even numbers . I hope this helped answer your question. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM