Control structure and loops in Python

Tram Ho

Like the previous post, I went to learn about variables in Python. If you have not seen it, see here . In this part, I will continue on control structure and iteration in Python. Let’s go.

Python supports several common control constructs. Most control constructs rely on 4 spaces to form one process block, instead of using {…} like other languages ​​(PHP, Javascript).

1. Boolean and logical operator

In python there are also many common logical operators in other languages.

  • Arithmetic operators
OperatorDescription
+An addition operator with 2 values
Operator subtracts 2 values
*The operator multiplies 2 values
/Operator divides 2 values ​​(divides a decimal number)
%The operator divides 2 values ​​to get the remainder
//The operator divides 2 values, rounding down
**Exponential operator
  • Relational operator
OperatorDescription
==Compare the values ​​of the arguments to see if they are equal or not
! =Compare the values ​​of the arguments to see if they differ.
<The <symbolic sign allows for smaller math
>The> symbol allows for larger math
> =The> represent sign allows math to be less than or equal to
<=The> represent sign allows for math greater than or equal to
  • The assignment operator
OperatorDescription
=Operator assigned to another variable
+ =This operator adds and then reassigns the variable
– =This operator subtracts and reassigns the variable
* =This operator multiplies and reassigns it to that variable
/ =This operator divides and reassigns it to that variable
% =This operator divides the remainder and reassigns it to that variable
** =This operator calculates exponential and then reassigns that variable
// =This operator divides rounding down and then reassigns to that variable
  • Logical operators
OperatorDescription
andLike the && operator, true if both sides of end are True and the rest are False
orLike the operator ??, true if one of the two sides of or is True and the other is False
notLike operator!, Is negative
printIf an argument belongs to a set, it returns True and False otherwise
not inContrast of print
isThis operator returns if the two sides of the operator are: a == b
not isThe opposite of is
  • Bit operators: &, |, ^, ~, <<, >>
  • Three-person operator: (…? …: ….)

2. Conditional statements if

  • The if statement is used to check a condition: if the condition is true, it runs a block of statements (called an if-block).

  • The else block will be executed if the condition in if is false

  • When we have to check one more condition if the if is false we can use elif

  • We can place nested if blocks:

3. Switch

  • There is one thing special than other languages ​​that Python does not have a Switch case. Instead, we can use if … elif …. else to replace the switch case structure (a bit inconvenient, so if there are 8-10 cases then if else this would be difficult to read. ?)
  • In addition to using if else above can use the following way:

  • The code above the key is similar to the input of the switch function. If the key satisfies a certain value, it will return the correct value. If the key doesn’t exist, nothing is returned by default.

Other examples:

4. Loop structure

In python supports loop structure: for and while.

For loop: The for loop in Python has the effect of looping data variables with data type list, tuple or string, … Using the following syntax:

The for statement in Python is a bit different from other familiar languages ​​like C, PHP, … Instead of repeating the steps, it gives dev to define the iteration steps and pause conditions like C, PHP, …. Python’s for statement iterates over the elements of an passed list ~ similar to foreach – it loops all elements.

The range () function: helps us to create a list quickly. With the syntax:

With this syntax, 1 list starts at 0 continuously and ends with enough elementNumbers:

The range () function has 3 parameters:

  • start: integer start, string will start with this parameter. Default value is 0.
  • stop: the integer ends, the string will end with this parameter.
  • step: integer specifying the distance between numbers inside the string. Default value is 1.

Combining range with for allows for easier loops:

  • While loops in python are similar to that in other languages, looping when a given condition is met. Syntax:

  • break and continue: Similar to PHP, break allows to exit the loop, while continue allows to skip the current run of the loop and continue running.

  • else in the loop: different from other languages, in Python there is else in for. When used with a loop, the else clause occurs when no break statement is run in the loop – when the loop is finished, and vice versa if there is a break in the loop then no else will run.

5. Exception in python

Exception is an error that occurs during the execution of a program, when executing a certain piece of code, an error can occur during the run that we can not determine in advance, it can make the program is dead, the page is dead, … or when saving to the db, there may be an error that causes the saved data to be interrupted, creating error data. In this TH we use try-catch to catch display errors. Syntax:

The code in the try block will be run, if an error occurs, then run except, and the code in the finally block will always run regardless of error or not.

The exceptions available in Python can be found here .


So I went through loops in Python. Thank you for your interest

Share the news now

Source : Viblo