Command Palette

Search for a command to run...

AI Programming

Control Flow

Loop Control Statements

Python provides several special statements to control the execution flow in loops. These statements allow you to control when loops should stop, continue, or perform certain actions.

Break, Continue, Pass, and Else

The break statement is used to stop a loop completely when a certain condition is met. Think of it like an emergency button that immediately stops a machine.

Pythonbreak_example.py
# Finding number divisible by 15 and 25x = 0while True:  x += 1  if not (x % 15 or x % 25):      breakprint(x, 'is divisible by 15 and 25')# Output: 75 is divisible by 15 and 25

The continue statement skips the rest of the code in the current iteration and continues to the next iteration. This is different from break which stops the entire loop.

Pythoncontinue_example.py
# Printing only even numbersfor i in range(1, 11):  if i % 2:      continue  print(i, 'is even.')# Output:# 2 is even.# 4 is even.# 6 is even.# 8 is even.# 10 is even.

The pass statement does nothing but is useful as a placeholder for code that hasn't been written yet. Python requires at least one statement in every code block.

Pythonpass_example.py
# Using pass to skip certain numbersfor i in range(1, 11):  if i == 6:      pass  # Do nothing for number 6  if not i % 3:      print(i, 'is divisible by 3')# Output:# 3 is divisible by 3# 6 is divisible by 3# 9 is divisible by 3

The else block in loops will be executed when the loop ends normally, not because of a break. This is useful for providing special actions when the loop completes without interruption.

Pythonloop_else_example.py
# Searching for negative numbers in listnumbers = [0, 4, 2, 5]for i in numbers:  if i < 0:      breakelse:  print('no negative number in list')# Output: no negative number in list

Enumerate Function

The enumerate() function is very useful when you need both the index and value of each element during iteration. This function takes an iterable object and returns tuples containing (index, value) pairs.

Pythonenumerate_basic.py
# Using enumerate to get index and valuefruits = ['apple', 'banana', 'mango', 'melon']for i, fruit in enumerate(fruits):  print(i, ':', fruit)# Output:# 0 : apple# 1 : banana# 2 : mango# 3 : melon

By default, enumerate() starts counting from 0, but you can set the starting value with the second parameter.

Pythonenumerate_custom_start.py
# Setting custom start index for enumeratefruits = ['apple', 'banana', 'mango', 'melon']for i, fruit in enumerate(fruits, 5):  print(i, ':', fruit)# Output:# 5 : apple# 6 : banana# 7 : mango# 8 : melon

It's important to remember that each tuple (item, count) in the for loop will be automatically unpacked into variables i and fruit.

While Loop

The while loop executes a code block as long as the given condition is True. Unlike for loops where the number of iterations is known, while loops are used when the number of iterations is unknown at the start.

Pythonwhile_loop_example.py
# Example while loop with mathematical calculationz = 1while abs(z) < 100:  z = z**2 + 1print(z)# Output: 677

The while loop is suitable when you need to iterate until a certain condition is met and don't know how many iterations are required.

Mermaidmermaid
Loading

Zip Function

The zip() function allows you to iterate over multiple iterables simultaneously. Think of it like a zipper that combines two sides into one.

Basic Zip Usage

Pythonzip_basic.py
# Combining two lists with zipp = [1, 2, 3, 4]q = ['a', 'b', 'c', 'd']for pair in zip(p, q):  print(pair)# Output:# (1, 'a')# (2, 'b')# (3, 'c')# (4, 'd')

The zip() function returns an iterator containing tuples. Each tuple contains the i-th element from each input iterable. The iterator stops when the shortest iterable is exhausted.

Converting Zip Results

Pythonzip_conversion.py
# Converting zip results to list or tuplep = [1, 2, 3, 4]q = ['a', 'b', 'c', 'd']zipped = zip(p, q)print(list(zipped))  # Convert to list# Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]# Zip object already consumed, create new onezipped_new = zip(p, q)print(tuple(zipped_new))  # Convert to tuple# Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))

Unzipping with Operator *

You can reverse the zip process using the unpacking operator (*).

Pythonzip_unpacking.py
# Separating data that has been zippedpairs = [(1, 'a'), (2, 'b'), (3, 'd')]numbers, letters = zip(*pairs)print(numbers, letters)# Output: (1, 2, 3) ('a', 'b', 'd')

This process is called "unzipping" because it separates data that has been combined.

Range and For Loop

The range() function creates a sequence of numbers that can be iterated. This is very useful for loops with numeric indices.

Range Syntax

Pythonrange_syntax.py
# Various ways to use range# range(stop) - from 0 to stop-1for i in range(4):  print(i)# Output: 0, 1, 2, 3print()# range(start, stop) - from start to stop-1  for i in range(2, 6):  print(i)# Output: 2, 3, 4, 5print()# range(start, stop, step) - with specific stepfor i in range(8, 4, -1):  print(i)# Output: 8, 7, 6, 5

Range follows an arithmetic formula where each i-th element is start + i * step for all i from 0 to n-1.

Range vs List Efficiency

Range is more efficient than creating a list containing all numbers because range generates numbers on-demand, rather than storing them all in memory.

Pythonrange_efficiency.py
# Comparing range vs list efficiencyn = 10000k = 10# Inefficient - creates complete list in memoryindex = [0, 1, 2, ..., n]  # Memory wastefulfor i in index:  if i < k:      print(i)  else:      break# More efficient - using rangefor i in range(n):  # Doesn't store all numbers in memory  if i < k:      print(i)  else:      break

Conditional Statements

Conditional statements allow programs to make decisions based on certain conditions. Python uses indentation (spaces or tabs) to determine which code blocks belong to conditions.

If/Elif/Else Syntax

Pythonconditional_syntax.py
# Complete if/elif/else structureage = 20if age <= 5:  print("free entrance")elif age <= 14:  print("15.00 EUR")elif age <= 65:  print("30.00 EUR")else:  print("20.00 EUR")# Output: 30.00 EUR

Conditions don't need to be wrapped in parentheses, and a colon (:) after the condition is mandatory. Statement blocks must be indented with the same number of spaces.

Nested If Statement

Pythonnested_if.py
# Determining quadrant from coordinate pointx = (-1, -3)if x[0] >= 0:  if x[1] >= 0:      print('first quadrant')  else:      print('fourth quadrant')elif x[1] >= 0:  print('second quadrant')else:  print('third quadrant')# Output: third quadrant

Nested if is useful for making more complex decisions with multiple levels of conditions.

For Loop Syntax

For loops in Python are used to iterate elements in iterable objects like lists, tuples, strings, or ranges.

Pythonfor_loop_syntax.py
# Example list iterationfruit_list = ['apple', 'banana', 'mango']for fruit in fruit_list:  print(fruit)# Output:# apple# banana  # mango# Example string iterationtext = 'hi'for char in text:  print(char)# Output:# h# i

Iterable objects are ordered sequences of items, where each item can be taken one by one. The in operator is used for membership testing, colons mark the beginning of statement blocks, and statement blocks must be indented with spaces.