Python_Chap_5 Cheat Sheet

A Programming › Python cheat sheet in English by Theo666

Boucles & Comparaisons

2,502 views 730 downloads 25 Sep 2023 History

Iteration

In Python, iterable is a type of object that can be looped over using a for loop or other iterable methods. Examples of iterable objects include lists, tuples, dictio­naries, sets, and strings.

For loop: to iterate over a sequence of values such as a list, tuple, or string. The loop body is executed once for each value in the sequence.

While loop: to execute a block of code repeatedly as long as a condition is true. The loop body is executed repeatedly until the condition becomes false

break, continue : The break statement is used to terminate the loop immedi­ately, while the continue statement is used to skip the current iteration of the loop and move on to the next iteration. Both can be used with both for and while loops.

Comparison Operators

x == y
x != y
x >= y
x > y
x < y
x <= y
Many other types, such as str, list, tuple, dict, support also comparison operat­ions. Str are compared with alphabetic order. For those container with multiple elements, the comparison process is compli­cated. Except for the equality, we don't recommend to apply directly comparison operators to lists, sets, tuples (same type & length)

Boolean Operators

not x
x and y
x or y
x in y
x not in y
all([x, y, z])
those operators usually combine with if and while

Examples

# iteration by elements or index (by elements more efficient)

for index, element in enumerate(list):
    bloc of instruction

for i in range(len(list)):
    bloc of instruction

for k,v in dict.items():
    bloc of instruction

#while loop

while condition :
    bloc of instruction

#etc

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.