Functions and Blocks
How It Works In this program, we accept input from the user, but we process the input string only if it is at least 3 characters long. So, we use the built-in len function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the continue statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing we want to do here.
What Functions Really Are
A function is a reusable piece of a program. Instead of writing the same block of code over and over, you give that block a name and call it whenever you need it. Think of a function like a recipe: you write it once, and then you can follow it as many times as you want without rewriting all the steps each time. Functions are probably the most important building block of any nontrivial software in any programming language, because they let you organize your code, avoid repetition, and make your programs easier to understand and maintain.
You have already used many built-in functions such as len and range. These are functions that Python provides for you. Now you will learn how to create your own functions.
How Functions Are Defined
Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by a final colon that ends the line. Next follows the block of statements that are part of this function. The block of statements is indented to show that it belongs to the function.
Hello, Alice
Welcome to our program!
Hello, Bob
Welcome to our program!The indented statements under the def line form a block. This block is the body of the function. When you call the function by name (like greet("Alice")), all the statements in that block are executed in order.
Blocks and Conditional Flow
A block is a group of statements that belong together. Blocks are created by indentation and are used in functions, loops, and conditional statements. When a condition is true, the block of code under that condition runs. When it is false, that block is skipped. The continue statement is a special tool that lets you skip the rest of the current block and jump to the next iteration of a loop.
Imagine you are processing user input in a loop. You want to process only inputs that are at least 3 characters long. For shorter inputs, you want to skip the processing and ask for the next input. This is exactly where the continue statement helps: if the input is too short, continue skips the rest of the block and the loop moves to the next iteration.
Tracing Through Input Validation
Let us trace through a concrete program that validates user input. This program asks the user for input in a loop. It checks the length of the input using the len function. If the length is less than 3, it uses continue to skip the rest of the block. Otherwise, it processes the input.
In this program, the len function returns the number of characters in the input string. If that number is less than 3, the condition is true, and the block under the if statement runs. The continue statement then skips the print statements that follow and jumps back to the top of the loop for the next iteration.
Predicting Block Execution
What do you think happens?
What will happen when the user enters 'hi' in the program above?
Reveal answer
Answer: The program prints 'Too short! Try again.' and then loops back without printing 'You entered: hi'
When the user enters 'hi', len('hi') returns 2, which is less than 3. The condition is true, so the if block runs. It prints 'Too short! Try again.' and then the continue statement skips the remaining statements in the loop (the two print statements after the if block). The loop then goes back to the top and asks for input again.
Visualizing Control Flow with Continue
The flowchart shows two paths through the loop. When the condition is true (input is too short), the continue statement jumps directly to the next iteration, skipping the print statements that come after the if block. When the condition is false (input is long enough), all remaining statements in the loop run normally.
Tracing Loop Iterations Step by Step
Tracing Three Loop Iterations
Trace through the input validation program for three iterations: first the user enters 'hi', then 'ok', then 'hello'.
Iteration 1: User enters 'hi': user_input = 'hi'. len('hi') = 2. Is 2 < 3? Yes, so the if block runs. Print 'Too short! Try again.' Then continue skips the remaining statements and loops back.
Iteration 2: User enters 'ok': user_input = 'ok'. len('ok') = 2. Is 2 < 3? Yes, so the if block runs again. Print 'Too short! Try again.' Then continue skips the remaining statements and loops back.
Iteration 3: User enters 'hello': user_input = 'hello'. len('hello') = 5. Is 5 < 3? No, so the if block is skipped. The program prints 'You entered: hello' and then 'Processing complete.' Then the loop continues (or in this case, would loop back for another iteration).
In iterations 1 and 2, continue skips the processing statements. In iteration 3, the condition is false, so all statements after the if block run normally.
Common Mistakes with Blocks and Continue
Forgetting to indent the block under a function definition or if statement
Python uses indentation to determine which statements belong to the block. Without indentation, Python does not know that the print statement is part of the function, and you will get an IndentationError.
Fix:
def greet(name): print("Hello, " + name)Using continue outside of a loop
The continue statement only works inside a loop (while or for). If you use it in an if statement that is not inside a loop, Python will raise a SyntaxError.
Fix:
while True: if x > 5: continueThinking continue exits the entire program or function
continue only skips the rest of the current loop iteration and jumps to the next iteration. It does not stop the loop or exit the function.
Fix:
Use break to exit the loop, or use return to exit the function.Misunderstanding what len() returns for an empty string
Beginners sometimes expect len() to fail on empty input, but it simply returns 0. If you want to reject empty input, you must explicitly check if len(user_input) < 1.
Fix:
if len(user_input) < 1: print("Input cannot be empty.") continue
Best Practices for Functions and Blocks
Keep blocks short and focused. Each function should do one thing well. Use clear, descriptive names for your functions so that anyone reading your code understands what the function does. Indent consistently (usually 4 spaces per level in Python) to make your blocks easy to read. Use continue and break thoughtfully: continue is useful for skipping unnecessary processing in a loop, but overusing it can make your code hard to follow. When in doubt, use an if-else structure instead.
Practice: Write Your Own Validation Function
Write a program that repeatedly asks the user for a number. If the number is less than 10, use continue to skip the rest of the block and ask again. If the number is 10 or greater, print the number and exit the loop using break. Hint: You will need to convert the input string to an integer using int().
Hints
- Use a while True loop to keep asking for input.
- Use int(input(...)) to get a number from the user.
- Check if the number is less than 10 using an if statement.
- Use continue to skip the rest of the block if the number is too small.
- Use break to exit the loop when the number is large enough.
Summary
- Functions are reusable blocks of code that you define once and call many times. They are defined using the def keyword followed by a function name, parentheses, and a colon.
- A block is a group of indented statements that belong together. Blocks are used in functions, loops, and conditional statements.
- The continue statement skips the rest of the current loop iteration and jumps to the next iteration. It is useful for skipping unnecessary processing based on a condition.
- The len function returns the number of characters in a string. You can use it to validate input by checking if the length meets your requirements.
- Proper indentation is essential in Python. It determines which statements belong to a block and which do not.
Key Takeaways
- Functions are reusable blocks of code defined with def and called by name. They are the most important building block of nontrivial software.
- Blocks are groups of indented statements that belong together. Indentation determines which statements are part of a function, loop, or conditional.
- The continue statement skips the rest of the current loop iteration and jumps to the next one, useful for skipping unnecessary processing.
- Input validation patterns use len() to check string length and conditionals to decide which block of code runs.
- Proper indentation and clear function names make your code readable and maintainable.