> 백엔드 개발 > 파이썬 튜토리얼 > Python 튜토리얼 - 흐름 제어

Python 튜토리얼 - 흐름 제어

DDD
풀어 주다: 2024-09-19 12:15:38
원래의
576명이 탐색했습니다.

제어 흐름은 프로그래밍의 필수적인 부분입니다. 제어 흐름에는 분기와 루프 등 두 가지 유형이 있습니다.

비교 및 논리 연산자

비교 연산자와 논리 연산자는 제어 흐름 메커니즘에서 일반적으로 사용됩니다. Python에서 사용할 수 있는 비교 연산자 목록입니다. 비교 연산자는 부울 값을 반환합니다.

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

파이썬에서 비교연산자를 사용하는 예입니다.

first = 5
second = 6

print(first > second)
print(first < second)
print(first != second)
로그인 후 복사

출력

False
True
True
로그인 후 복사

and 연산자는 두 조건이 모두 true일 경우 true를 반환하는 연산자입니다.

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

or 연산자는 하나 또는 두 개의 조건이 true를 반환하면 true를 반환하는 연산자입니다.

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 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
로그인 후 복사

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.

Branching with if-else

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.

Branching with if-elif-else

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.

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
로그인 후 복사

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 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
로그인 후 복사

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)
로그인 후 복사
  • 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)
로그인 후 복사

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.

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
로그인 후 복사

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.

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
로그인 후 복사

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.

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")
로그인 후 복사

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")
로그인 후 복사

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)
로그인 후 복사

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.

위 내용은 Python 튜토리얼 - 흐름 제어의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿