I need to make a list of random numbers than separate each number, odd or even.
Here is my current progress.
import random
def main():
for x in range(20):
number=list(random.randint(1,101))
for number in number:
list=number
for x in list:
if (number % 2) == 0:
print("{0} is Even number".format(num))
else:
print("{0} is Odd number".format(num))
Use this code.
import random
L_odd = []
L_even = []
for x in range(20):
number = random.randint(1, 101)
if number % 2 == 0:
L_even.append(number)
else:
L_odd.append(number)
In this code, append
is a method to append element to the list (for example, L_even.append(number)
means to append number to the list L_even
)
As the comments from @Harshal Parekh and @PM 77-1, you need to know the importance of indent of Python, and I think you need to study python basic.
I think too much terms like number in number will make you confused, so I modified your code like this, I think this will help you to understand comprehensively.
import random
def main():
ls = [] #define a space list
ls_e = [] #even number
ls_o = [] #odd number
for x in range(20): #for loop 0-20
number=random.randint(1,101) #create random number between 1-101
ls.append(number) #put number into ls
print(ls)
for x in range(len(ls)): #for numbers in ls
if (ls[x] % 2) == 0: #check logic
print("{0} is Even number".format(ls[x]))
ls_e.append(ls[x]) #put into even list
else:
print("{0} is Odd number".format(ls[x]))
ls_o.append(ls[x]) #put into odd list
main()
You could use list comprehension to keep it simple. Hope this helps!
from random import randint
rand_nums = [randint(0, 101) for i in range(20)]
rand_odds = [i for i in rand_nums if i % 2 == 1]
rand_evens = [i for i in rand_nums if i % 2 == 0]
print(rand_nums)
print(rand_evens)
print(rand_odds)
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.