Many programs need to repeat a block of code many times. Writing the same lines again and again is wasteful and makes programs long and full of errors. Python provides loops to repeat actions automatically. The two main types of loops are the for loop, which repeats a fixed number of times or once for each item in a collection, and the while loop, which repeats as long as a condition remains true. Loops are one of the most powerful features of programming.
Functions are another powerful tool. A function is a named block of code that performs a specific task and can be used again and again. Instead of writing the same calculation many times, we write it once in a function and call it whenever needed. Python has many built-in functions, and we can also create our own. This chapter explains for loops, while loops, the range function, break and continue, defining functions, parameters and arguments, and the return statement.
The for loop repeats a block of code for each item in a sequence. It is very useful when we know how many times we want to repeat, or when we want to go through each item of a string, list or tuple. For example, the code:
for i in range(5): print(i)
prints the numbers 0, 1, 2, 3 and 4. The loop variable i takes each value one by one, and the indented block runs once for each value. The for loop can also go through a list directly, such as:
for fruit in ['apple', 'mango', 'banana']: print(fruit)
which prints each fruit in the list. The for loop ends when all the items have been used, and then the program continues with the next statement after the loop.
The range() function is used with for loops to generate a sequence of numbers. range(5) generates the numbers 0, 1, 2, 3 and 4, starting at 0 and stopping before 5. We can also give two arguments, such as range(1, 6), which generates 1, 2, 3, 4 and 5. With three arguments, the third is the step, so range(0, 10, 2) generates even numbers 0, 2, 4, 6 and 8.
The range function is very flexible. It can count upwards, downwards with a negative step, and can be used to repeat an action a fixed number of times even when the loop variable is not needed. For example, print("Hello") can be repeated three times using for i in range(3). The stop value is always excluded from the generated sequence, which is an important detail to remember. Using range() correctly gives us precise control over how many times a loop runs.
The while loop repeats a block of code as long as a condition is True. The condition is checked before each repetition, and when it becomes False, the loop stops. For example:
count = 1 while count <= 5: print(count) count = count + 1
prints the numbers 1 to 5. Inside the loop, the value of count increases by 1 each time, so the condition eventually becomes False. This increasing of the loop variable is very important; if we forget it, the condition never becomes False and the loop runs forever, which is called an infinite loop.
While loops are used when we do not know exactly how many times the loop should run, such as reading input until a certain value is entered. Compared to the for loop, the while loop gives more control but also puts more responsibility on the programmer to update the condition correctly. Choosing between for and while depends on whether we know the number of repetitions in advance.
Sometimes we want to stop a loop early or skip one repetition. The break statement immediately stops the loop and jumps to the statement after it. For example, a loop that searches for a number can stop as soon as it finds it. The continue statement skips the rest of the current repetition and moves to the next one. For example, a loop can skip even numbers and print only odd numbers.
Both break and continue are used inside loops, usually after a condition check. Break is useful to exit a loop when the goal has been reached, and continue is useful to skip unwanted values. These statements give us fine control over loops and help us write efficient programs that do not do unnecessary work.
A function is a reusable block of code that performs a specific task. Python has built-in functions such as print(), input(), len() and type(). We can also create our own functions with the def keyword. A function definition starts with def, followed by the function name, parentheses, a colon, and the indented body. For example:
def greet(): print("Hello!")
After defining a function, we call it by writing its name with brackets, such as greet(). The function does not run when it is defined; it runs only when it is called. Naming a function with a meaningful name makes the program easy to understand, and using functions avoids repeating code.
Functions can accept data so that they can work on different values each time they are called. The variables written in the parentheses of the function definition are called parameters. The values passed when we call the function are called arguments. For example:
def add(a, b): print(a + b)
Here a and b are parameters, and add(5, 3) passes the arguments 5 and 3, printing 8. A function can return a value to the calling code using the return statement. For example:
def add(a, b): return a + b
result = add(5, 3)
Now the returned value 8 is stored in the variable result. The return statement ends the function immediately. Functions can be combined with loops and conditions to build complex programs, and they make code shorter, clearer and easier to reuse.
| Loop | Use | Example |
|---|---|---|
| for loop | Repeats for each item or fixed times | for i in range(5) |
| while loop | Repeats while a condition is True | while count <= 5 |
| break | Stops the loop immediately | if x == 5: break |
| continue | Skips to the next repetition | if x % 2 == 0: continue |
| Keyword / Concept | Purpose |
|---|---|
| def | Defines a new function |
| Function name | The name used to call the function |
| Parameter | Variable in the function definition |
| Argument | Value passed when calling |
| return | Sends a value back to the caller |
| Built-in functions | print(), input(), len(), type() |
The key to mastering loops is to trace a small example by hand before running it on the computer. Consider the for loop that prints numbers from 1 to 10 using range(1, 11). On the first pass, the loop variable i takes the value 1 and the body runs; then i becomes 2, and the body runs again. This process continues until i has taken every value in the range, and it stops just before the value 11 is reached, because the stop value is always excluded. Tracing a loop in this way makes it clear that a for loop is simply a compact way of writing a long list of repeated statements, and it also reveals exactly how many times the loop will execute.
A while loop is traced in a similar but slightly different way, because its repetitions depend on a condition rather than on a list. Before each pass, the condition is evaluated; if it is true, the body runs and the loop variable is updated, and then the condition is checked again. The moment the condition becomes false, the loop ends. This is why the update statement inside the body is so critical. If we forget to increase count inside the loop, the condition stays true forever and the program never stops, which is called an infinite loop. Beginners should therefore always ask two questions about a while loop: does the condition eventually become false, and which statement inside the body makes it do so?
Functions deserve the same careful treatment. When a function is defined with the def keyword, Python only stores the definition; it does not execute the body. Execution begins only when the function is called. At the moment of a call, the arguments written in the call are copied into the parameters of the definition, and the body runs using those values. If the function contains a return statement, the computed value is handed back to the place where the function was called, and the function stops immediately. Understanding this flow of data into and out of a function is the single most important step towards writing clean, reusable code, because it explains why a function can be written once and used many times with different values.
The choice between break and continue also follows from this understanding of flow. A break statement stops the whole loop immediately and sends control to the first statement after the loop, which is useful when the goal of the loop has been reached and further repetitions would be wasted. A continue statement, on the other hand, ends only the current repetition and jumps back to the top of the loop, so the loop continues with the next item or condition check. Combining these two tools with well-chosen conditions gives a programmer precise control over exactly which repetitions are performed and which are skipped.
Loops and functions make programs shorter, smarter and more powerful. The for loop repeats a fixed number of times, the while loop repeats while a condition is true, and range() controls the sequence of numbers. The break and continue statements give us control inside loops. Functions, defined with the def keyword, package a task into a reusable block that can take parameters and return values. With loops, conditions, data types and functions, we now have all the core tools of Python programming to build real and useful programs.