4. Python - Loops
For loop:
Loop through list
for element in listname:
print(element, end=' ') // print element and a space
Loop through string:
for element in stringname:
print(element, end=' ')
Normal I Loops:
for i in range(100):
do something 100 times
While Loops:
while panda:
print(1)
List comprehensions: (short way to write list loops)
squares = [n**2 for n in range(10)]
// puts each value after a loop into a list called squares.
// loop powers each n by 2
// LEFT = return value, MIDDLE = loop range, RIGHT = condition
short_planet = [planet for planet in planets if len(planet)<6]
// loop planet through planets list and see if its shorter than 6 characters and return if true
test = [True if n>givennumber else False for n in List]
// a if b else c
// takes in a list and a given number
ALT syntax:
[
planet.upper() + '!'
for planet in planets
if len(planet) < 6
]
Comments
Post a Comment