Backend••10 min read•7 views

Python Fundamentals: A Guide to the if, elif, else, for, and while Control Structures

Dizzy with nested ifs and infinite loops? Learn how to properly use if, elif, else, for, and while in Python complete with tips from senior engineers.

Here, pull up your chair. Is your coffee ready? Don't worry, today we won't immediately discuss complex microservices architecture or how to scale a database to millions of users. Before you can run fast on our project, you have to be able to walk properly first. In the world of programming, "going the right way" means you really understand the fundamentals.

As an engineer who has experienced various errors in production from 2 am until sunrise, I want to tell you one secret: no matter how good your system architecture is, in the end it is all built on the basics. And today, we will talk at length about the "brains" of every Python code you will write: Control Structure.

If you write code without a control structure, your code is just a stupid calculator. He just walked straight from the first row to the last row, no matter what happened in the outside world. In fact, applications in the real world are dynamic. We need code that can think, "Oh, if the user is not logged in, kick him to the login page," or "Please send an email to these 1000 users one by one."

Well, in Python, we have three main weapons for managing this flow: if/elif/else, for, and while. Sounds really easy, right? It's easy, but believe me, I still often reject Pull Requests (PR) from mid level programmers because the way they write control flow is messy, hurts the eyes, and is prone to bugs.

So, listen carefully, take notes if necessary. I will explain this from the point of view of best practice in the industry, not just printed book theory.

1. Decision Making: if, elif, else

In the real world, you make decisions every day. "If it rains today, I'll ride by car. If it's cloudy, I'll bring a raincoat. If it's sunny, I'll ride a motorbike." In Python, we translate logic like this using if, elif (short for else if), and else.

 

Try looking at this code:

 

Python
user_age = 20

if user_age>= 18:
    print("Yes, you can enter the system.")
    print("Welcome!")
else:
    print("Sorry bro, you're still underage.")
One thing that really makes Python different from other languages like Java or C++ is Indentation (space at the start of a line). In Python, we don't use curly braces {} to wrap blocks of code. We use spaces (usually 4 spaces). If your indentation is wrong, your code will be error or worse, the logic will be stupid. Python forces us to write neat code.

 

Now, what if there are many conditions? We use elif.

 

Python
gopay_balance = 50000
coffee_price = 35000
bread_price = 20000

if balance_gopay>= (coffee_price + bread_price):
    print("Buy coffee and bread! Today is great.")
elif gopay_balance>= coffee_price:
    print("Just enough for coffee. That's enough.")
elif balance_gopay>= bread_price:
    print("Just buy bread to make your stomach upset.")
else:
    print("Balance is dying, just drink water in the pantry.")
Senior Tips:
This is where many novice programmers fall into the abyss of what I call "Nested If Hell" or nested if hell. They really like writing if inside if inside if until the shape of the code curves like an arrow. This makes the code really hard to read.

 

Bad example (don't copy):

 

Python
def payment_process(user, balance, item):
    if user.is_active:
        if balance>= item.price:
            if goods.stok> 0:
                print("Payment successful")
            else:
                print("Out of stock")
        else:
            print("Insufficient balance")
    else:
        print("User is inactive")
As a senior, I always advise the kids on the team to use the Guard Clauses or Early Return. The idea is: first check the conditions that make the process fail, and immediately return or exit the function. If all checks fail to pass, then we run the main logic below without needing to indent deeply.

 

Elegant example:

 

Python
def elegant_payment_process(user, balance, item):
    if not user.is_active:
        print("User is inactive")
        return
        
    if balance "Insufficient balance")
        return
        
    if goods.stok == 0:
        print("Out of stock")
        return
        
    # If you get to this line, it means everything is safe
    print("Payment successful, transaction processing...")
See the difference, right? Much easier to read and easier tomaintain.

 

One more thing, in Python we have the concept of Truthy and Falsy. You don't need to always check something with == True or == 0. For example, you want to check whether a list is empty or not.

 

Instead of writing: if len(data_user) == 0:
You just write: if not data_user:

 

Python already understands if list is empty, string is empty, the number is 0, and None is considered False (Falsy). Additionally, everything is considered True (Truthy). This makes your code look very "Pythonic" aka idiomatic.

 

2. Definite Looping: for

Now we enter the for loop. If you have to send notifications to 10,000 customers, you can't possibly write the send_notif() function 10,000 times, right? You need a loop.


The

for loop in Python is very different from the old C or Java languages. In Python, for is created to iterating (tracing) a collection, like list, tuple, dictionary, or string. You no longer need to worry about index manually, adding i++, and thinking about the final limit. Python takes care of it all.

 

Most examples basic:

 

Python
list_name = ["Budi", "Andi", "Siti", "Joko"]

for name in name_list:
    print(f"Hello {name}, please check your email!")
It's that simple. Python will take the first element ("Budi"), put it in the variable name, run print, then automatically continue to the second element, and so on until listis exhausted.

 

What if I just need to repeat the code 5 times without a list?
Well, here we use a built-in function called range().

 

Python
for i in range(5):
    print(f"This is the {i}")
(Important note: range(5) starts from 0, stops at 4. So there are still 5 repetitions, but the numbers are 0, 1, 2, 3, 4. This standards in computer science).

 

Senior Tips for for loop:
I often see junior from background C++ or Java writing code like this to get the index and also get the value:

 

Python
# CODE SMELL (C-style loop in Python)
fruit = ["Apple", "Mango", "Banana"]
for i in range(len(piece)):
    print(f"{i} is {fruit[i]}")
Please, if you're on my team, don't write like this. It really looks like you don't understand the Python ecosystem. If you need both index and value, use a magic function called enumerate().

 

Python
# ELEGANT CODE (Pythonic)
fruit = ["Apple", "Mango", "Banana"]
for index, fruit_name in enumerate(fruit):
    print(f"{index} is {fruit_name}")
Cleaner, faster to read, and less likely to hit IndexError.

 

If you want to loop two list simultaneously? Don't use manual indexes. Use zip()!

 

Python
user_name = ["Budi", "Siti"]
role_user = ["Admin", "Member"]

for name, role in zip(user_name, user_role):
    print(f"{name} login as {role}")
This is the reason why many people fall in love with Python. The syntax is designed to think about "what is going to be done", not "how is the machine going to do this".

 

3. Looping By Condition: while

Well, if the for loop we use is when we know exactly how many times we have to repeat (because the amount of data is clear), while loop we use when we don't know when to stop, but we know the stopping condition.

 

while is like combining if with a loop. "As long as this condition is True, just continue running the code. If it is False, then stop."

 

The easiest example is waiting for service or database to turn on, or a program that continues until user presses the exit button.

 

Python
server_capacity = 0
max_limit = 5

print("The system is powered on...")

while server_capacity f"Server is still going strong. Current capacity: {server_capacity}")
    server_capacity += 1 # Don't forget this, or you'll die!
    
print("Capacity full! Stop accepting requests.")
War Story from Senior:
I have to warn you from now on. while loop is a place where Infinite Loop often occurs. See the line server_capacity += 1 above? If you forget to write that line, the value server_capacity will always be 0. The condition 0 <5 will always be True. The result? Your program will continue playing there millions of times per second, your server's CPU will increase to 100%, memory runs out, the server crash, downtime, and your boss will call you at 3 in the morning angry. I've experienced this, that's why I'm fussy.



In loops (for or while), sometimes we need to control the flow in more detail. This is where we come across two keyword lifesavers: break and continue.

 

  • break: Swerve! Exit the loop RIGHT NOW, no matter if the condition is still True or whether the data is still remaining.
  • continue: Skip the rest, but don't exit. Jump straight to the next iteration.
For example, you are looking for data user that banned in a list, but you want to skip the active user. If you find banned user, you want to report it, but only a maximum of 1 person as an example, then stop searching.

 

Python
status_users = ["active", "active", "banned", "active", "banned"]

for status in status_users:
    if status == "active":
        continue # Skip the line below, go to the next user
        
    if status == "banned":
        print("Found a bad user! Report it!")
        break # Found one, straight out of the loop
        
print("Checking complete.")
If this code is executed, it will skip the first two user because continue. Pas ketemu "banned" di index ke-2, dia bakal nge-print laporannya, lalu ketemu break dan perulangannya mati total. "banned" yang terakhir nggak akan pernah dicek.

 

4. Fitur Ajaib Python: for...else dan while...else

Sebelum gue tutup sesi ngopi kita, gue mau kasih satu ilmu rahasia yang bahkan mid-level engineer sering nggak tau.

 

Di bahasa pemrograman lain, else itu cuma pasangannya if. Tapi di Python, lo bisa nulis else sebagai pasangan dari for atau while! Strange, right? Tapi ini berguna banget.

 

Kapan blok else di perulangan ini dieksekusi? Jawabannya: Ketika perulangan selesai secara natural TANPA kena break.

 

Sering banget kan kita bikin logika nyari barang. Kalau ketemu, kita break. Kalau perulangan habis dan nggak ketemu, kita mau print "Barang tidak ditemukan". Biasanya orang pakai variabel flag (penanda) kayak is_found = False. Di Python, lo nggak butuh itu!

 

Python
keranjang = ["buku", "pulpen", "tas"]
yang_dicari = "laptop"

for barang in keranjang:
    if barang == yang_dicari:
        print("Sip, laptop ada di keranjang!")
        break
else:
    # Blok else ini cuma jalan kalau for-nya habis dan nggak pernah nge-break
    print("Wah, laptopnya nggak ketemu nih bro.")
Ini bikin kode pencarian lo jadi sangat elegan dan bersih. Nggak ada variabel sampah kayak is_found = True bertebaran di mana-mana.

 

Kesimpulannya

Gimana? Lumayan kan pencerahannya?

 

Struktur kontrol itu ibarat fondasi bangunan. Kalau lo cuma hafal sintaks if, for, while doang tapi nggak tau kapan harus pakai yang mana, atau nulis kodenya belepotan pake nested if sampai 5 tingkat, bangunan sistem lo bakal gampang rubuh.

 

Yang membedakan Junior dan Senior bukan dari seberapa banyak bahasa pemrograman yang dia hafal, tapi dari seberapa rapi, efisien, dan elegan dia menyelesaikan masalah dengan alat-alat dasar ini.

 

  • Gunakan if/elif/else dengan bijak, hindari percabangan terlalu dalam pakai Guard Clauses.
  • Gunakan for kalau lo ngadepin collection atau iterasi dengan jumlah pasti. Manfaatkan enumerate dan zip.
  • Gunakan while untuk event-driven atau kondisi tidak pasti, dan awasi baik-baik supaya nggak jadi infinite loop.
Udah, itu dulu aja. Pahami bener-bener apa yang gue omongin hari ini. Habis ini coba lo cek repo project kita, cari beberapa file trus analisis gimana senior-senior lo nulis kontrol bloknya. Lo pasti bakal nemuin semua pola yang baru aja gue ceritain.

 

Semangat ngoding-nya. Kalau nanti kode lo nge-bug, jangan panik. Baca error-nya, cek kondisi if-nya, liat ujung loop-nya. Semua jawaban biasanya ada di logika fundamental ini. 
Sigit Wasis Subekti

Sigit Wasis Subekti

Software Engineer & Tech Educator

Software Engineer and Tech Educator sharing insights on web development and software architecture.