Python’s Condition and Loop Structure

erizky ningtya
4 min readApr 1, 2021

Definition of the If Condition of the Python Language

In this section, we will discuss Python programming code commands for branching program code, also known as condition / logical structure. In Python, there are If, If Else, and If Else If (elif) conditions.

In programming, there are times when we need a branch, that is if a condition is met, run this program code, if not, run another program code.

Example of a simple if branching code :

Result

Definition of the If Else Condition of the Python Language

The If Else condition is an additional modification of the if the condition that we learned earlier.

The If program block of code will still run when acondition is True, but now there is an additional Else section that will be executed when the condition is False.

Result

Definition of the If Else if Condition of the Python Language

Basically, the If Else If condition is a program logic structure that can be obtained by connecting several If Else conditions into a unit.

If the first condition is not fulfilled or is False, the program code will continue to the If condition under it. If it is not fulfilled, it will continue to the If condition under it, etc. until the last Else block or there is an If the condition that is True.

Result

Python While Language Loops

The loop structure is a program code instruction that aims to repeat several lines of command.

In designing the loop, we must know at least 3 components:

  • The initial condition of the loop.
  • Condition at the time of looping.
  • The conditions that must be met for the loop to stop.

Result

The result will be repeated as inputted by while

Python For Language Loops

Unlike the majority of other programming languages, in Python, the for loop is more of a loop to process arrays. This is similar to a for each loop in PHP.

Result

Python Language Break Command Functions

When creating a loop, sometimes we want to exit the loop prematurely.

When creating a loop, sometimes we want to exit the loop prematurely.
For example, suppose you are coding a program to find a value in a list of 50 elements. If it turns out that the value has been found in the 25th position, then the rest of the loop is no longer needed. It would be more efficient if the loop stopped immediately, and this is what the break command does.

Inside the while loop, which is on line 4, there is a condition check if i == 5. If this condition is met (variable counter I have a value of 5) then run the break command. As a result, the loop stops immediately as soon as the variable I reaches the number 5.

Result

Inside the while loop, which is on line 4, there is a condition check if i == 5. If this condition is met (variable counter I have a value of 5) then run the break command. As a result, the loop stops immediately as soon as the variable I reaches the number 5.

--

--