ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

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.

2. The for Loop

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.

3. The range() Function

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.

4. The while Loop

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.

5. Break and Continue

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.

6. Functions and the def Keyword

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.

7. Parameters, Arguments and Return

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.

Quick Revision Tables

Table 1: Loops in Python

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

Table 2: Functions in Python

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()

Mind Map

flowchart TD A["Loops and Functions"] --> B["for Loop"] A --> C["while Loop"] A --> D["range()"] A --> E["break and continue"] A --> F["Functions"] B --> B1["Fixed number of times"] C --> C1["While condition is True"] D --> D1["range(5), range(1,6)"] E --> E1["break stops"] E --> E2["continue skips"] F --> F1["def keyword"] F --> F2["Parameters and arguments"] F --> F3["return statement"]

Important Diagrams (SVG)

Diagram 1: Flow of a while Loop

Flow of a while Loop count = 1 count <= 5 ? False END True print(count) count = count + 1 Golden Rule: A while loop checks its condition before each run and stops when the condition is False. Always update the loop variable, or the loop will run forever.

Diagram 2: How a Function Works

How a Function Works def add(a, b): result = a + b return result FUNCTION DEFINITION x = add(5, 3) Arguments 5 and 3 are passed Result 8 is returned FUNCTION CALL Parameters a and b hold the arguments The return statement sends the value back to the caller The function is defined once but can be called many times Golden Rule: Define a function with def, give it parameters, and use return to send back a result. Arguments are the actual values; parameters are the names that receive them.

8. Detailed Concept Explanation

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.

Common Mistakes

  1. Creating an infinite loop by forgetting to update the loop variable in a while loop.
  2. Forgetting the colon at the end of the for or while line.
  3. Believing that range(5) includes 5. It generates 0, 1, 2, 3 and 4, stopping before the stop value.
  4. Confusing parameters with arguments. Parameters are in the definition, arguments are passed at the call.
  5. Calling a function before defining it. The function must be defined before it is called in the code.
  6. Forgetting the brackets when calling a function, such as writing greet instead of greet().
  7. Using break instead of continue. Break stops the whole loop, while continue skips only the current repetition.
  8. Believing that a function runs when it is defined. A function runs only when it is called.
  9. Writing a return statement at the wrong place. return ends the function immediately.
  10. Using a for loop where a while loop with a changing condition is more suitable, and vice versa.

Exam Tips

  1. Learn the difference between for and while loops and when to use each.
  2. Remember that range(n) gives 0 to n-1, and range(a, b) gives a to b-1.
  3. Understand break (stops the loop) and continue (skips a repetition).
  4. Be able to write a for loop that prints numbers 1 to 10 and a while loop that counts down.
  5. Know how to define a function with def, use parameters and return a value.
  6. Give examples of built-in functions: print(), input(), len() and type().
  7. Be able to write a function that returns the sum of two numbers and call it.

Conclusion

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.