Maison >développement back-end >Tutoriel Python >Tutoriel Python - Ontrol Flow
Le flux de contrôle est une partie essentielle de la programmation. Il existe deux types de flux de contrôle, à savoir le branchement et le bouclage.
Les opérateurs de comparaison et logiques sont couramment utilisés dans le mécanisme de flux de contrôle. Voici la liste des opérateurs de comparaison pouvant être utilisés en Python. L'opérateur de comparaison renvoie une valeur booléenne.
Operator | Description |
---|---|
== | Equals to |
!= | Not equals to |
> | Greater than |
>= | Greater than or equals |
< | Less than |
<= | Less than or equals |
Ceci est un exemple d'utilisation d'opérateur de comparaison en Python.
first = 5 second = 6 print(first > second) print(first < second) print(first != second)
Sortie
False True True
L'opérateur and est un opérateur qui renvoie vrai si les deux conditions renvoient vrai.
Condition | Condition | Result |
---|---|---|
False | False | False |
False | True | False |
True | False | False |
True | True | True |
L'opérateur ou est un opérateur qui renvoie vrai si une ou deux conditions renvoient vrai.
Condition | Condition | Result |
---|---|---|
False | False | False |
False | True | True |
True | False | True |
True | True | True |
This is an example of logical operator usage.
first = 6 second = 7 result_1 = first != 0 and first > second result_2 = second > 5 or second == first print(result_1) print(result_2) <p>Output<br> </p> <pre class="brush:php;toolbar:false">False True
Based on the code above, the and operator returns False because there is a condition that returns False which is first > second.
The or operator returns True because there is a condition that returns True which is second > 5.
and returns true if all conditions are true.
or returns true if one of the other conditions is true.
Branching is a mechanism to execute a code based on a specific condition. There are many approaches to performing branching in Python.
This is the basic structure of branching with if.
if condition: code
The code inside the if block is executed if the condition inside the if block is true.
This is an example of branching using if.
num = 24 if num % 2 == 0: print('even number')
Output
even number
Based on the code above, the code inside the if block is executed because the condition inside the if block is true.
This is the basic structure of branching with if-else.
if condition: code else: other code
The code inside the if block is executed if the condition inside the if block is true. Otherwise, the other code is executed inside the else block.
This is the example of branching with if-else.
num = 35 if num % 2 == 0: print('even number') else: print('odd number')
Output
odd number
Based on the code above, the condition inside the if block is false then the code inside the else block is executed.
This is the basic structure of branching with if-elif-else.
if condition: code elif condition: code else: code
The if-elif-else is useful to perform branching with many conditions. This is an example of if-elif-else usage.
role = "Back-end" if role == "Front-end": print("learn HTML, CSS and JS") elif role == "Back-end": print("learn Java, Go and PHP") else: print("learn any related topics")
Output
learn Java, Go and PHP
Based on the code above, the code is executed based on the role value.
The match-case branching works like the switch-case in other programming languages. This is the basic structure.
match value: case condition: code case condition: code case condition: code case _: default code
This is the example of branching with match-case.
role = "Back-end" match role: case "Front-end": print("learn HTML, CSS and JS") case "Back-end": print("learn Java, Go and PHP") case _: # default condition print("learn any related topics")
Output
learn Java, Go and PHP
Looping is a mechanism to execute a code repeatedly. Looping is an essential tool for completing repetitive tasks like reading a record in a file, basic calculations, and so on. There are many approaches to performing looping in Python.
The for loop is suitable for executing repetitive tasks within an exact amount of time. For example, a certain task has to be completed 10 times. This is the basic structure of the for loop.
for value in iterables: code
This is the sample code without using the for loop.
print(1) print(2) print(3) print(4) print(5)
This is the modified code using the for loop.
for i in range(1,6): print(i)
Output
1 2 3 4 5
Based on the code above, the for loop code is executed with the range() function. The range() function returns a sequence of numbers based on the given start and end of the range. This is the basic structure of the range() function.
range(start,end,step)
The range(1,6) means generating a sequence of numbers from 1 up to but not including 6.
This is another example of a for loop with a custom range (range(2,11,2)) to display even numbers.
for i in range(2,11,2): print(i)
Output
2 4 6 8 10
Based on the code above, the even numbers from 2 up to but not including 11 are displayed. The range(2,11,2) generates sequence from 2 up to but not including 11 with the step value equals 2 which means each sequence value is incremented by 2.
The break keyword stops the code execution. This keyword is usually used inside the loop. This is an example of break usage.
num = 10 while num != 0: if num % 4 == 0: print("done!") break # stops the execution print("stil running...") num -= 1 # decrement the value by 1
Output
stil running... stil running... done!
Based on the code above, the break keyword stops the execution if the condition is met.
The continue keyword continues the code execution into the next phase or skips to the next iteration. This is an example of continue keyword usage.
for i in range (1,7): if i == 5: print("skipped!") continue print(f"value: {i}")
Output
value: 1 value: 2 value: 3 value: 4 skipped! value: 6
Based on the code above, the continue keyword skips to the next iteration if the condition is met.
The while loop is suitable for executing repetitive tasks within an uncertain amount of time. For example, a certain task has to be completed until a specific condition is met. This is the basic structure of the while loop.
while expression: code
This is an example of while loop usage.
num = 1 while num <= 5: print(num) num += 1
Output
1 2 3 4 5
Based on the code above, the code inside the while loop is executed while the condition (in this case num <= 5) is true. If the condition is not met, then the loop is stopped. The += operator increments the num value by 1.
The num += 1 is equals to num = num + 1. The ++ and -- operator is not supported in Python.
When working with a loop, ensure the implementation and applied condition are correct to avoid an infinite loop.
Let's create a Python program to check the grade based on the given score. For example, this table is used to check the grade based on the given score.
Score | Grade |
---|---|
81-100 | A |
65-80 | B |
50-64 | C |
30-49 | D |
0-29 | E |
The solution is using branching. This is the complete example:
score = int(input("enter a score: ")) if score >= 81 and score <= 100: print("A") elif score >= 65 and score <= 80: print("B") elif score >= 50 and score <= 64: print("C") elif score >= 30 and score <= 49: print("D") elif score >= 0 and score <= 29: print("E") else: print("invalid score")
Output
Let's create a program to check if the given word is a palindrome. Palindrome is a word that can be read equally forward and backward.
The naive solution is to compare the original word and the reversed word. If both of them are equal, then the given word is a palindrome. The naive solution walkthrough is illustrated in the picture below.
This is the naive solution implementation using a while loop.
# get the word input from the user word = input("insert a word: ") # sanitize the input word = word.lower() # create a variable to store reversed word reversed = "" # create a variable to store the index idx = len(word) - 1 # generate reversed word while idx >= 0: reversed += word[idx] idx = idx - 1 # compare the original and reversed word if word == reversed: print("palindrome") else: print("not palindrome")
Output
Another approach is to create two indices for iterating through each character from forward and backward. If two characters from forward and backward are not equal, then the given word is not palindrome. The walkthrough of this approach is illustrated in the picture below.
This is the implementation of using two indices.
# get the word input from the user word = input("insert a word: ") # sanitize the input word = word.lower() # create two indices front = 0 # forward tracking back = len(word) - 1 # backward tracking # store result result = "palindrome" # track each characters forward and backward while front < len(word): if word[front] != word[back]: result = "not palindrome" break front += 1 back -= 1 # display the check result print(result)
Output
I hope this article helps you learn Python. If you have any feedback, please let me know in the comment section.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!