Clever use of Python for in

Time:2021-8-31

import random
Ou = “even”
Ji = “odd”
a = range(1,11)
x = 0
while x < 10:
list = random.sample(a,10)
print(list)
if list[0] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[1] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[2] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[3] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[4] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[5] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[6] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[7] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[8] % 2 != 0:
print(ji, end=”,”)
else:
print(ou, end=”,”)
if list[9] % 2 != 0:
print(ji)
else:
print(ou)
X + = 1 # first code

Code after using for in

import random
Ou = “even”
Ji = “odd”
a = range(1,11)
x = 0
while x < 10:
list = random.sample(a,10)
print(list)
for y in list:
if y %2 == 0:
print(ou,end=”,”)
else :
print(ji,end=”,”)
Print() # line breaks. If you don’t add this, it will become a long strip
x +=1

The functions implemented by the two pieces of code are the same, but after using the for in loop, the efficiency is much improved and the code is much simpler

Recommended Today

Detailed steps for installing Perl and Komodo IDE for windows

Perl official website: https://www.perl.org/Perl document: https://perldoc.perl.org/Download address: https://www.perl.org/get.html The installation package of Perl Windows version is divided into activestate Perl and strawberry Perl. For the difference between the two, see: http://www.zzvips.com/article/202134.htm Note: the download speed of activestate Perl is slow. You may need KX to surf the Internet I have uploaded all the versions of […]