Python Conditions and Python Loops with Examples
Table of Contents
Python Conditions and Python Loops:
Python Conditions and Python Loops with Examples- Conditions and loops are the key building elements of any programming language. In this article you will learn how to use the basic if else conditions, Logical conditions using “and” and “or” operators, and how to use “for” and “while” loops. I will explain everything with examples.
Amazon Purchase Links:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!
Python If Statement:
if statement, I have already used it in many examples and projects based on Raspberry Pi which explains the practical use in an advance way. Beginners may find it confusing, so, I decided to write a very basic article about the python conditions and loops. We are going to start with the “if” condition. The syntax is easy to understand and can be summarized as follows:
Python If Statement Syntax:
1 |
if condition1 : |
block1, this can consists of multiple lines of code. You can also call functions, etc.
1 2 3 4 5 6 7 8 9 10 11 |
elif condition2 : block2 elif condition3 : block3 else: block4 |
Any number of elif conditions are allowed, even zero. The else block is optional. Python goes through the entire design to the first true condition.
The statements associated with this condition are then executed; Then the code continues after the last elif or else block. Do not forget the colons that are used in terms of both the conditions and the to be put to else! Unlike other programming languages, Python has no switch or case constructions.
Python Conditions
Conditions are usually formed with comparison operators, i.e. x==3. Multiple conditions can be linked logically using “and” and “or” conditions.
1 2 3 |
if x >0 and (y >0 or z ==1) : ... |
Python performs a so-called short circuit evaluation at “and” and “or”:
- If the first partial expression results in false in an “and” link, the second is no longer evaluated because the result is definitely false
- If the first sub-expression is true in an “or” operation, the second becomes no longer evaluated because the result is definitely true.
Instead of a<x and x<b, the short form a<x <b is allowed. Conditions can also be formulated without a comparison operator, for example in this form:
1 2 3 |
if x: ... |
This condition is met if:
- x is a number other than 0
- x is a non-empty string
- x is the Boolean value 1 (true)
- x is a list, a tuple, or a set with at least one element
- x is an initialized object (not None)
if-Short-notation:
Sometimes you only need if designs to assign a variable:
1 2 3 4 5 6 7 |
if condition: x= value1 else x= value2 |
For such constructions there is a space-saving shorthand:
1 |
x = value1 if condition else value2 |
Python Loops (for and while)
Loops in Python are mostly formed with for var in elements. The loop variable accepts each of the specified elements in turn.
Python for loop Syntax:
1 2 3 |
for var in elements: instructions |
The loop variable var can also be used in code after the end of the loop and then contains the last assigned value:
1 2 3 4 5 |
for i in [7, 12, 3]: instructions print (i) # issue 3 |
Alternatively, loops can be formulated with while. The indented instructions are then executed as long as the condition is met.
Python while loop Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
while condition: instructions break ends for and while loops prematurely: for var in elements: instruction1 if condition: break # break the loop instruction2 |
continue skips the remaining statements for the current loop pass, continues the loop:
1 2 3 4 5 6 7 |
for var in elements: instruction1 if condition: continue # skip statement2 instruction2 |
Python also knows an else block for loops and is different from that most other programming languages. The else block is executed after in a for loop all elements have been run through or if in a while loop the loop condition is no longer fulfilled.
1 2 3 4 5 6 7 8 9 |
for var in elements: instruction1 instruction2 else: instruction3 |
Loops over number ranges (range)
For loops over a given number range, the elements in the Rule generated by range (start, end), whereby the end value is exclusive. The following loop therefore runs through the values from 1 to 9 (not 10!). The end = ” option in print has the effect that there is no line break after each output, only one Space is output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
for i in range (1, 10): print (i, end = '') # Output: 1 2 3 4 5 6 7 8 9 The step size can be specified in the optional third parameter: for i in range (0, 20, 3): print (i, end = '') # Issue: 0 3 6 9 12 15 18 for i in range (100, 0, -10): print (i, end = '') # Output: 100 90 80 70 60 50 40 30 20 10 |
Note:
range in Python 2 and Python 3: range is implemented very differently in Python 2 and Python 3. In Python 2 range creates a list. This is stored in the memory and can then e.g. in processed in a for loop. In Python 3, however, range is a so-called Generator that creates the elements only when required. Especially with loops over one large number of elements saves a lot of storage space. In Python 2, it’s in such cases, however, it is advisable to work with xrange instead of range.
range can only be used for whole numbers, not for floating point numbers. If you want to loop from 0 to 1 with an increment of 0.1, you can i.e. proceed as follows:
1 2 3 |
for i in range (0, 11): x = i /10.0; print (x, end = '') # Output 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 |
Of course, you can also create loops over number ranges with while. This is particularly advantageous when the numbers are irregularly spaced should.
1 2 3 4 5 6 7 8 9 |
i = 1 while i <100000: print (i, end = '') i + = i * i # Edition: 1 2 6 42 1806 |
Loops over the characters in a string
This is how you can process a character string character by character:
1 2 3 4 5 6 7 |
for c in 'abc': print (c) # Output: a # b # c |
It may be more useful to convert the character string into a list with list, whose elements each contain a character. Then you can use all list functions.
1 2 3 |
>>> list ('abc') ['a', 'b', 'c'] |
Loops over lists, tuples and sets
You can easily process the elements of lists, tuples and sets with for:
1 2 3 4 5 6 7 8 9 10 11 |
for i in (17, 87, 4): print (i, end = '') # Edition: 17 87 4 for s in ['Python', 'is', 'fun!']: print (s) # Output: Python # power # Fun! |
Often the goal of such loops is a new list, a new tuple, or a new one Set to form. Then it is usually more elegant and efficient to use List / Tupel / Set Comprehension to use. Behind this technical term there is a special one Variant of the for loop, which is formed in a list, a tuple or a set. The following examples all relate to lists, but can also be used for Tuples or sets can be formulated. In its simplest form, the syntax is [expression for var in list]. Be there all list elements inserted into the variable. The evaluated expressions result in a new list. Optionally, the list can set a condition for the loop variable with if be adjusted: Then only the list elements are taken into account for which the condition applies.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> l = [1, 2, 3, 10] >>> [x * x for x in l] # Square of all list elements # form [1, 4, 9, 100] >>> [x * x for x in l if x% 2 == 0] # only even numbers # consider [4, 100] |
The expression itself can of course be a list, a set or a tuple – then
the result is a nested expression:
1 2 3 |
>>> [[x, x * x] for x in l] [[1, 1], [2, 4], [3, 9], [10, 100]] |
Use to create a dictionary from a list, a tuple or a set Use the notation {k: v for x in list}, where k and v are expressions for the key (Key) and the value (Value) of each dictionary element.
1 2 3 |
>>> {x: x * x for x in l} {1: 1, 2: 4, 3: 9, 10: 100} |
Loops through Python dictionaries
The comprehension syntax described above can also be used for dictionaries. In its simplest form, this is a loop over the key of the dictionary elements. Depending on whether you use square or place curly brackets, the result is a list or a set.
1 2 3 4 5 6 7 8 9 |
>>> d = {'a': 12, 'c': 78, 'b': 3, 'd': 43} >>> {x for x in d} {'a', 'c', 'b', 'd'} >>> [x for x in d] ['a', 'c', 'b', 'd'] |
If you need two variables for the key / value pair in the loop, use The items method or iteritems in Python 2:
1 2 3 4 5 6 7 |
>>> {k for k, v in d. items ()} {'a', 'c', 'b', 'd'} >>> {v for k, v in d. items ()} {43, 3, 12, 78} |
To make the result of the expression itself a dictionary again, you create the Result expression in the form key: value:
1 2 3 |
>>> {k: v * 2 for k, v in d. items ()} {'a': 24, 'c': 156, 'b': 6, 'd': 86} |
Loops through all script parameters
If you pass parameters to a Python script, you can use them in the script with evaluate the instruction sys.argv. sys is one of many Python modules; it must can be read with import so that the functions contained therein can be used. argv is a list, the first element of which is the file name of the script. The others List elements contain the transferred parameters. Since the script name seldom is required, it is eliminated with the expression [1:].
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#! / usr / bin / python3 import sys if (len (sys. argv) <= 1): print ("No parameters were passed.") else: for x in sys. argv [1:]: print ("Parameter:", x) |
A possible call of the script could now look like this:
1 2 3 4 5 |
./ test .py two parameters Parameters: two Parameter: parameter |
Bash usually runs in the terminal window. This evaluates expressions like * .txt immediately and then transfers the list of those found to the called command Files. So if the three files readme.txt, copyright.txt and gpl.txt are saved, then with ./test.py * .txt the Pass the names of all three files:
1 2 3 4 5 6 7 |
./ test .py *. txt Parameter: copyright. txt Parameter: gpl. txt Parameter: readme .txt |
Loops across the lines of a text file
Quite often, you need to process a text file line by line. Python therefore accepts file objects in for loops and passes one line at a time to the loop variable. With the print statement, end = ” prevents that after each a blank line appears. The ones inserted into the loop variable Strings already contain the line break codes from the text file.
1 2 3 4 5 6 7 8 9 10 11 |
f = open ('readme.txt', 'r') cnt = 0 for line in f: cnt + = 1 print ("line", cnt, ":", line, sep = '', end = '') close () |
Loops across all files in a directory
The os.listdir function returns an unordered list of all files and subdirectories in a directory. With “for” you can easily create a loop educate about it. When processing the files, however, you must note that listdir supplies the file names without path information, e.g. readme.txt, not /home/pi/readme.txt. For further processing, you therefore, usually have to use os.path.join form the full file name, as shown in the following listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import os startdir = os. path. expanduser ("~") print (startdir) for filename in os. listdir (startdir): fullname = os. path. join (startdir, filename) if os. path. isfile (fullname): print ("file:", fullname) elif os. path. isdir (fullname): print ("Directory:", fullname) |
In the example above, os.path.expanduser (“~”) returns the path of the home directory. If you are only interested in * .pdf files in this directory, go as follows:
1 2 3 4 5 6 7 8 9 10 11 |
import os startdir = os. path. expanduser ("~") print (startdir) for filename in os. listdir (startdir): if not filename. lower (). endswith ('. pdf'): continue fullname = os. path. join (startdir, filename) |