Tutorial by Examples

To iterate through a list you can use for: for x in ['one', 'two', 'three', 'four']: print(x) This will print out the elements of the list: one two three four The range function generates numbers which are also often used in a for loop. for x in range(1, 6): print(x) The res...
for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection. for i in [0, 1, 2, 3, 4]: print(i) The above for loop iterates over a list of numbers. Each iteration sets the value of i to the next element of the list. So f...
break statement When a break statement executes inside a loop, control flow "breaks" out of the loop immediately: i = 0 while i < 7: print(i) if i == 4: print("Breaking from loop") break i += 1 The loop conditional will not be evaluated a...
The for and while compound statements (loops) can optionally have an else clause (in practice, this usage is fairly rare). The else clause only executes after a for loop terminates by iterating to completion, or after a while loop terminates by its conditional expression becoming false. for i in r...
Considering the following dictionary: d = {"a": 1, "b": 2, "c": 3} To iterate through its keys, you can use: for key in d: print(key) Output: "a" "b" "c" This is equivalent to: for key in d.keys(): print(key) ...
A while loop will cause the loop statements to be executed until the loop condition is falsey. The following code will execute the loop statements a total of 4 times. i = 0 while i < 4: #loop statements i = i + 1 While the above loop can easily be translated into a more elegant fo...
pass is a null statement for when a statement is required by Python syntax (such as within the body of a for or while loop), but no action is required or desired by the programmer. This can be useful as a placeholder for code that is yet to be written. for x in range(10): pass #we don't want t...
Suppose you have a long list of elements and you are only interested in every other element of the list. Perhaps you only want to examine the first or last elements, or a specific range of entries in your list. Python has strong indexing built-in capabilities. Here are some examples of how to achie...
Unlike other languages, Python doesn't have a do-until or a do-while construct (this will allow code to be executed once before the condition is tested). However, you can combine a while True with a break to achieve the same purpose. a = 10 while True: a = a-1 print(a) if a<7: ...
If you want to loop over a list of tuples for example: collection = [('a', 'b', 'c'), ('x', 'y', 'z'), ('1', '2', '3')] instead of doing something like this: for item in collection: i1 = item[0] i2 = item[1] i3 = item[2] # logic or something like this: for item in collec...

Page 1 of 1