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
Operator | Description |
---|---|
+ | 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
Operator | Description |
---|---|
== | 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
Operator | Description |
---|---|
= | 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
Operator | Description |
---|---|
and | Like the && operator, true if both sides of end are True and the rest are False |
or | Like the operator ??, true if one of the two sides of or is True and the other is False |
not | Like operator!, Is negative |
If an argument belongs to a set, it returns True and False otherwise | |
not in | Contrast of print |
is | This operator returns if the two sides of the operator are: a == b |
not is | The 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).
1 2 3 | if condition: statements |
- The else block will be executed if the condition in if is false
1 2 3 4 5 | if 1 > 2: print("1 is greater than 2") else: print("1 is not greater than 2") |
- When we have to check one more condition if the if is false we can use elif
1 2 3 4 5 6 7 8 | numberInput = int(input('Nhap vao 1 so: ')) if numberInput == 1: print("numberInput is one") elif numberInput == 2: print("numberInput is two") else: print("numberInput is not one or two") |
- We can place nested if blocks:
1 2 3 4 5 6 7 8 | if numberInput == 1: print("numberInput is one") else: if numberInput == 2: print("numberInput is two") else: print("numberInput is not one or two") |
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:
1 2 3 4 5 6 7 8 9 10 | switcher = { 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6 } switcher.get(key, "nothing") |
- 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.
1 2 3 | switcher.get('A', "nothing") => 1 switcher.get('G', "nothing") => nothing |
Other examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def one(): return 'January' def two(): return 'February' def three(): return 'March' def four(): return 'April' switcher = { 1: one, 2: two, 3: three, 4: four, } func = switcher.get(key, lambda: ‘nothing’) print func() |
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:
1 2 3 | for variable in data: # code |
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.
1 2 3 4 5 6 7 8 | words = ['cat', 'dog', 'bird']; for w in words: print(w) # cat # dog # bird |
1 2 3 4 5 6 7 8 | for c in 'Hello': print(c) #H #e #l #l #o |
The range () function: helps us to create a list quickly. With the syntax:
1 2 | range(elementNumbers) |
With this syntax, 1 list starts at 0 continuously and ends with enough elementNumbers:
1 2 | range(5) |
1 2 | range(start, stop [, step]) |
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:
1 2 3 4 5 6 7 8 9 | for number in range(5): print(number) #0 #1 #2 #3 #4 |
- While loops in python are similar to that in other languages, looping when a given condition is met. Syntax:
1 2 3 | while <condition>: # code |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 | i = 0 while (i <= 10): print(i) if i == 5: break i += 1 for i in ‘i am a robot’: if i == ‘ ’: continue print(i, end=’’) |
- 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.
1 2 3 4 5 6 7 8 9 10 11 | for x in range(5): print(x) else: print('else') #1 #2 #3 #4 #else |
1 2 3 4 5 6 7 8 9 | for x in range(5): print(x) if x % 2 == 0: break else: print('else') #0 |
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:
1 2 3 4 5 6 7 | try: // code except: // ngoai le finally: // run every time |
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