[파이썬] 코드 조건문과 루프 스타일

Python is a versatile programming language that offers multiple ways to write conditionals and loops. These constructs allow you to control the flow of your code and execute specific actions based on certain conditions. In this blog post, we will explore different styles of conditionals and loops in Python and discuss their use cases.

Conditionals

if-else statement

The if-else statement is the most basic form of a conditional statement in Python. It allows you to perform different actions based on whether a certain condition is true or false. Here is an example:

num = 10

if num > 0:
    print("Positive")
else:
    print("Negative")

In this example, the code checks if num is greater than zero. If it is, the program prints “Positive”, otherwise it prints “Negative”.

elif statement

Sometimes you need to test multiple conditions in succession. In such cases, you can use the elif statement. It follows the if statement and allows you to specify additional conditions to be tested. Here is an example:

num = 0

if num > 0:
    print("Positive")
elif num < 0:
    print("Negative")
else:
    print("Zero")

In this example, the code checks if num is greater than zero first. If it’s not, it checks if it’s less than zero. If both conditions fail, it prints “Zero”.

Loops

for loop

The for loop in Python allows you to iterate over a sequence or collection of items. It repeatedly executes a block of code for each item in the sequence. Here is an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

In this example, the code iterates over the fruits list and prints each item on a separate line.

while loop

The while loop in Python allows you to repeatedly execute a block of code as long as a certain condition is true. It is useful when you don’t know the exact number of iterations beforehand. Here is an example:

count = 0

while count < 5:
    print(count)
    count += 1

In this example, the code prints the value of count and increments it by 1 until it becomes 5.

Conclusion

In this blog post, we covered the various styles of conditionals and loops in Python. The if-else statement and the elif statement are used to perform different actions based on conditions. The for loop allows you to iterate over a sequence, while the while loop is useful for executing code repeatedly as long as a condition is true. By understanding and utilizing these constructs effectively, you can write more efficient and expressive Python code.