Heim > Backend-Entwicklung > Python-Tutorial > Python-Tutorial – Kontrollfluss

Python-Tutorial – Kontrollfluss

DDD
Freigeben: 2024-09-19 12:15:38
Original
565 Leute haben es durchsucht

Der Kontrollfluss ist ein wesentlicher Bestandteil der Programmierung. Es gibt zwei Arten von Kontrollflüssen, einschließlich Verzweigung und Schleife.

Vergleich und logischer Operator

Vergleichs- und logische Operatoren werden häufig im Kontrollflussmechanismus verwendet. Dies ist die Liste der Vergleichsoperatoren, die in Python verwendet werden können. Der Vergleichsoperator gibt einen booleschen Wert zurück.

Operator Description
== Equals to
!= Not equals to
> Greater than
>= Greater than or equals
< Less than
<= Less than or equals

Dies ist ein Beispiel für die Verwendung von Vergleichsoperatoren in Python.

first = 5
second = 6

print(first > second)
print(first < second)
print(first != second)
Nach dem Login kopieren

Ausgabe

False
True
True
Nach dem Login kopieren

Der UND-Operator ist ein Operator, der „true“ zurückgibt, wenn die beiden Bedingungen „true“ zurückgeben.

Condition Condition Result
False False False
False True False
True False False
True True True

Der ODER-Operator ist ein Operator, der „true“ zurückgibt, wenn eine oder zwei Bedingungen „true“ zurückgeben.

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
Nach dem Login kopieren

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
Nach dem Login kopieren

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

Nach dem Login kopieren

Output

even number
Nach dem Login kopieren

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
Nach dem Login kopieren

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')
Nach dem Login kopieren

Output

odd number
Nach dem Login kopieren

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
Nach dem Login kopieren

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")
Nach dem Login kopieren

Output

learn Java, Go and PHP
Nach dem Login kopieren
Nach dem Login kopieren

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
Nach dem Login kopieren

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")
Nach dem Login kopieren

Output

learn Java, Go and PHP
Nach dem Login kopieren
Nach dem Login kopieren

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
Nach dem Login kopieren

This is the sample code without using the for loop.

print(1)
print(2)
print(3)
print(4)
print(5)
Nach dem Login kopieren

This is the modified code using the for loop.

for i in range(1,6):
    print(i)
Nach dem Login kopieren

Output

1
2
3
4
5
Nach dem Login kopieren
Nach dem Login kopieren

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)
Nach dem Login kopieren
  • 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)
Nach dem Login kopieren

Output

2
4
6
8
10
Nach dem Login kopieren

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
Nach dem Login kopieren

Output

stil running...
stil running...
done!
Nach dem Login kopieren

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}")
Nach dem Login kopieren

Output

value: 1
value: 2
value: 3
value: 4
skipped!
value: 6
Nach dem Login kopieren

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
Nach dem Login kopieren

This is an example of while loop usage.

num = 1

while num <= 5:
    print(num)
    num += 1
Nach dem Login kopieren

Output

1
2
3
4
5
Nach dem Login kopieren
Nach dem Login kopieren

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")
Nach dem Login kopieren

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")
Nach dem Login kopieren

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)
Nach dem Login kopieren

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.

Das obige ist der detaillierte Inhalt vonPython-Tutorial – Kontrollfluss. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage