Python Conditions and Python Loops with Examples

(Last Updated On: September 11, 2021)

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:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*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:

block1, this can consists of multiple lines of code. You can also call functions, etc.

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.

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:

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:

For such constructions there is a space-saving shorthand:


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:

The loop variable var can also be used in code after the end of the loop and then contains the last assigned value:

Alternatively, loops can be formulated with while. The indented instructions are then executed as long as the condition is met.

Python while loop Syntax:

continue skips the remaining statements for the current loop pass, continues the loop:

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.


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.

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:

Of course, you can also create loops over number ranges with while. This is particularly advantageous when the numbers are irregularly spaced should.

Loops over the characters in a string

This is how you can process a character string character by character:

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.


Loops over lists, tuples and sets

You can easily process the elements of lists, tuples and sets with for:

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.

The expression itself can of course be a list, a set or a tuple – then

the result is a nested expression:

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.



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.

If you need two variables for the key / value pair in the loop, use The items method or iteritems in Python 2:

To make the result of the expression itself a dictionary again, you create the Result expression in the form key: value:

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:].

A possible call of the script could now look like this:

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:

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.


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:

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:

 

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

%d bloggers like this: