Tutoriel Python - Ontrol Flow

DDD
Libérer: 2024-09-19 12:15:38
original
529 Les gens l'ont consulté

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.

Comparaison et opérateur logique

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)
Copier après la connexion

Sortie

False
True
True
Copier après la connexion

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
Copier après la connexion

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 in Python

Branching is a mechanism to execute a code based on a specific condition. There are many approaches to performing branching in Python.

Branching with if

This is the basic structure of branching with if.

if condition:
    code
Copier après la connexion

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')

Copier après la connexion

Output

even number
Copier après la connexion

Based on the code above, the code inside the if block is executed because the condition inside the if block is true.

Branching with if-else

This is the basic structure of branching with if-else.

if condition:
    code
else:
    other code
Copier après la connexion

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')
Copier après la connexion

Output

odd number
Copier après la connexion

Based on the code above, the condition inside the if block is false then the code inside the else block is executed.

Branching with if-elif-else

This is the basic structure of branching with if-elif-else.

if condition:
    code
elif condition:
    code
else:
    code
Copier après la connexion

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")
Copier après la connexion

Output

learn Java, Go and PHP
Copier après la connexion
Copier après la connexion

Based on the code above, the code is executed based on the role value.

Branching with match-case

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
Copier après la connexion

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")
Copier après la connexion

Output

learn Java, Go and PHP
Copier après la connexion
Copier après la connexion

Looping in Python

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.

Looping with for

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
Copier après la connexion

This is the sample code without using the for loop.

print(1)
print(2)
print(3)
print(4)
print(5)
Copier après la connexion

This is the modified code using the for loop.

for i in range(1,6):
    print(i)
Copier après la connexion

Output

1
2
3
4
5
Copier après la connexion
Copier après la connexion

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)
Copier après la connexion
  • start defines the start of the sequence.
  • end defines the end of the sequence. The end value is not included in the sequence.
  • step defines the step value for generating the next sequences. By default, the step value is 1 which means each sequence value is incremented by 1.

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)
Copier après la connexion

Output

2
4
6
8
10
Copier après la connexion

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.

Python Tutorial - ontrol Flow

break and continue keyword

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
Copier après la connexion

Output

stil running...
stil running...
done!
Copier après la connexion

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}")
Copier après la connexion

Output

value: 1
value: 2
value: 3
value: 4
skipped!
value: 6
Copier après la connexion

Based on the code above, the continue keyword skips to the next iteration if the condition is met.

Looping with while

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
Copier après la connexion

This is an example of while loop usage.

num = 1

while num <= 5:
    print(num)
    num += 1
Copier après la connexion

Output

1
2
3
4
5
Copier après la connexion
Copier après la connexion

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.

Example 1 - Grade Checking

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")
Copier après la connexion

Output

Python Tutorial - ontrol Flow

Example 2 - Palindrome Checking

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.

Python Tutorial - ontrol Flow

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")
Copier après la connexion

Output

Python Tutorial - ontrol Flow

Python Tutorial - ontrol Flow

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.

Python Tutorial - ontrol Flow

Python Tutorial - ontrol Flow

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)
Copier après la connexion

Output

Python Tutorial - ontrol Flow

Python Tutorial - ontrol Flow

Sources

  • Python Official Page.
  • Python Tutorial.
  • Control Flow in Python.

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!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!