snakeIntro (Control Flow Statment)

Conditionals: Mengontrol alur eksekusi berdasarkan kondisi tertentu dengan if, elif, dan else.

Loops: Digunakan untuk mengulang kode; for digunakan untuk iterasi elemen dalam urutan, dan while digunakan selama kondisi masih terpenuhi.

Comprehensions: Memberikan cara yang lebih efisien dan singkat untuk membuat koleksi seperti list, set, atau dictionary, menggunakan satu baris kode.

Untuk versi 3.11 ke atas...

Control Flow Statements

The flow control statements are divided into three categories

  1. Conditional statements

  2. Iterative statements.

  3. Transfer statements


1. Conditional Statements

These statements are used to execute a block of code based on a condition.

Types of Conditional Statements:

  • if

  • if-else

  • if-elif-else

  • Nested if

Example:

The block of code inside the if statement executes only if the condition is True.

Syntax of the if statement

Example Code:

If – else statement

The if-else statement checks the condition and executes the if block of code when the condition is True, and if the condition is False, it will execute the else block of code.

Syntax of the if-else statement:

If the condition is True, then statement 1 will be executed If the condition is False, statement 2 will be executed. See the following flowchart for more detail.

In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one after another. This is useful when you need to check multiple conditions.

With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple conditions one by one and if the condition fulfills, then executes that code.

Syntax of the if-elif-else statement:

2. Iterative Statements

These statements are used to execute a block of code repeatedly.

Types of Iterative Statements:

  • for loop

  • while loop

  • Nested loops

Example: for loop

Example: while loop

These loops continue executing until a condition is met.


3. Transfer Statements

These statements are used to control the flow of execution by breaking, skipping, or stopping loops and functions.

Types of Transfer Statements:

  • break → Terminates the loop

  • continue → Skips the current iteration and moves to the next

  • pass → Acts as a placeholder

  • return → Exits a function and returns a value

Example: break

Example: continue

Example: pass

Example: return


Summary

Category
Statements
Purpose

Conditional Statements

if, if-else, if-elif-else

Decision making

Iterative Statements

for, while, nested loops

Repeating execution

Transfer Statements

break, continue, pass, return

Controlling execution flow

Sumber: https://pynative.com/python-control-flow-statements/arrow-up-right

Last updated