ACCFIN5277 Chap.11 Loops, Conditionals and Functions in Python
Loops, Conditionals and Functions in Python
Loops, Conditionals and Functions in Python covers the control structures that turn single calculations into automated routines. A for loop visits each element of a known sequence, which suits converting consecutive prices into returns or nominal amounts into real ones.
A while loop keeps going until a condition stops being true, which suits searches with an unknown number of steps, such as compounding until a target is reached or iterating until a model converges, and it needs a guard against running forever. Conditional statements written with if, elif and else let data choose the path, whether that means acting when a price crosses a threshold or placing an asset in a risk category.
Combining the two gives the common pattern of visiting every observation and classifying it. Functions then wrap a tested routine behind a name and a set of parameters, can return several values at once as a tuple, and may import libraries and loop internally.
The chapter traces a compounding loop pass by pass, converts gross returns to log returns in a function, and drills the ordering mistakes that make an elif chain misclassify data.
What this chapter covers
- 01
For loops over lists, arrays and ranges
- 02
While loops, stopping conditions and safety limits
- 03
If, elif and else branching and test order
- 04
Classifying returns into volatility buckets
- 05
Defining functions with parameters and return values
- 06
Returning several results as a tuple
Worked example · free
Count the years for a deposit to double
- 1Set value to 1,000 and a year counter to zero; loop while value is below 2,000.
- 1After eight passes the value is 1,992.56, still short of the target, so the loop runs again.
- 2After the ninth pass the value is 2,171.89, the test fails and the loop stops with the counter at 9.
Key terms
- Loop guard
- An extra condition, such as a maximum number of passes, that forces a while loop to end even when data misbehaves.
- Elif branch
- An additional test checked only when every earlier test in the same if statement was false.
- Function parameter
- A named input listed in a function definition that receives a value each time the function is called.
- Tuple unpacking
- Assigning the several values a function returns to separate variables in one statement.
Loops, Conditionals and Functions in Python FAQ
When should I use a while loop rather than a for loop?
Use a for loop when you know the sequence to visit, such as every price in a column. Use a while loop when the number of passes depends on the data, such as compounding until a target is met or repeating a calculation until it converges. In the second case always add a maximum pass count so a bad input cannot hang the program.
Why does the order of elif tests change the result?
Python checks the tests from top to bottom and runs only the first one that is true, skipping the rest. If a broad condition such as an absolute return above one per cent comes before a narrow one such as above two per cent, every large return is captured by the broad branch and the narrow label is never assigned.
How can one function give back several numbers?
List them after the return keyword separated by commas, and Python packs them into a tuple. The caller can unpack the tuple into separate names in a single assignment, as in the course example that returns a sum, a product and a difference together. Keep the order documented, because unpacking assigns values strictly by position.
Can a function import a library and contain its own loop?
Yes. The course shows functions that import numpy inside their body and use loops internally, for example to build a matrix of zeros of a requested size. Importing at the top of the notebook is the more usual style, but either way the function stays reusable: call it with different arguments and it repeats the whole routine.
How do I find the bug when a loop returns the wrong total?
Shrink the input to three or four values whose answer you can compute by hand, then print the loop variable and the running total on every pass. Typical culprits are a range that starts at the wrong index, an accumulator reset inside the loop, or an update that happens after the loop has already decided to stop.
Assessment move
Write each loop on paper as a short trace table first: the pass number, the condition, the branch taken and the updated value. Then code it and compare against the table. Turn every routine you repeat into a function with clear parameters and a one-line description, and test it on a case you can verify by hand before applying it to real data.
Practise elif chains by deliberately reversing the test order and predicting which labels change. Finally, pass a function into a loop over several scenarios, as the course material suggests, and check one scenario by hand.
Working through Loops, Conditionals and Functions in Python in ACCFIN5277? Sia is AskSia’s AI Finance tutor — ask any ACCFIN5277 Loops, Conditionals and Functions in Python question and get a clear, step-by-step explanation grounded in how ACCFIN5277 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.