Python Conditional Statements and Loop Structures

Conditional Statements

Conditional statements execute code blocks based on boolean evaluation of expressions.

Basic Structures

# Single branch
if condition:
    execute_if_true()

# Dual branch  
if condition:
    execute_if_true()
else:
    execute_if_false()

# Multiple branches
if primary_condition:
    primary_execution()
elif secondary_condition:
    secondary_execution()
elif tertiary_condition:
    tertiary_execution()
else:
    default_execution()

Nested Conditionals

if outer_condition:
    outer_statement()
    if inner_condition:
        inner_statement()
    elif alternative_condition:
        alternative_statement()
    else:
        inner_default()
elif outer_alternative:
    outer_alternative_statement()
else:
    outer_default()

Authentication Example

user_input = input('Enter username:')
pass_input = input('Enter password:')

if user_input == 'admin' and pass_input == 'secure123':
    print('Access granted')
else:
    print('Invalid credentials')

Role-Based Access Example

user_identity = input('Enter username:')

if user_identity == 'admin':
    print('System administrator')
elif user_identity == 'guard':
    print('Security personnel')
elif user_identity == 'accountant':
    print('Finance department')
elif user_identity == 'driver':
    print('Transportation staff')
else:
    print('Unauthorized user')

Key considerations:

  • All conditions evaluate to boolean values
  • Idnentation defines code block hierarchy
  • Consistent indentation within blocks is mandatory
  • Not all code blocks require sub-blocks

Loop Structures

While Loops

# Sum calculation
maximum = 100
total = 0
current = 1

while current <= maximum:
    total += current
    current += 1

print(f"Sum from 1 to {maximum}: {total}")

Continuous Authentication

while True:
    user_name = input('Username:')
    user_pass = input('Password:')
    
    if user_name == 'admin' and user_pass == 'secret':
        print('Authentication successful')
        break
    else:
        print('Try again')

While-Else Construct

counter = 0
while counter < 5:
    if counter == 3:
        break
    print(counter)
    counter += 1
else:
    print('Loop completed without interruption')

Nested While with Break

while True:
    username = input('Enter username:')
    password = input('Enter password:')
    
    if username == 'admin' and password == 'pass123':
        print('Login successful')
        
        while True:
            command = input('Enter command:')
            if command == 'exit':
                break
            print(f'Executing: {command}')
        break
    else:
        print('Login failed')

Flag Control Pattern

active = True
while active:
    user_id = input('Username:')
    user_code = input('Password:')
    
    if user_id == 'admin' and user_code == '1234':
        print('Access granted')
        while active:
            instruction = input('Command:')
            if instruction == 'quit':
                active = False
            print(f'Processing: {instruction}')
    else:
        print('Access denied')

Continue Statement

# Print 0-9 excluding 6
num = 0
while num < 10:
    if num == 6:
        num += 1
        continue
    print(num)
    num += 1

For Loops

For loops iterate over iterable objects without manual counter management.

# Iterating through sequences
for element in [1, 2, 3, 4, 5]:
    print(element)

# Dictionary iteration
user_data = {'name': 'john', 'age': 30, 'role': 'developer'}
for key in user_data:
    print(f"{key}: {user_data[key]}")

Range Function

# Basic range
for index in range(5):
    print(index)

# Custom start
for num in range(3, 8):
    print(num)

# Step parameter
for value in range(0, 50, 10):
    print(value)

URL Generation Example

base_pattern = 'https://api.example.com/data?page=%s'
for page_num in range(0, 100, 10):
    print(base_pattern % page_num)

Loop Control Statements

# Break example
for idx in range(10):
    if idx == 7:
        break
    print(idx)

# Continue example  
for num in range(10):
    if num == 5:
        continue
    print(num)

# For-else construct
for val in range(8):
    if val == 6:
        break
    print(val)
else:
    print('Full iteration completed')

Nested Loops

for row in range(4):
    for col in range(6):
        print('*', end='')
    print()

Tags: python conditional-statements loops control-flow programming

Posted on Tue, 19 May 2026 06:51:55 +0000 by Nicholas