University of Glasgow · FACULTY OF FINANCE

ACCFIN5277 Chap.11 Loops, Conditionals and Functions in Python

- one subject, every graph, every model, every mark
6 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 11 of 12 · ACCFIN5277

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.

In this chapter

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

Q [4 marks]. A deposit of 1,000 grows at 9% a year. Using a while loop that multiplies by 1.09 each pass, work out how many years it takes to reach at least 2,000 and the value at that point. The marks shown are an original practice weighting, not a university allocation.
The flowchart compounds a starting value year by year until it reaches a target; inside each pass an if, elif, else test files the year's rate into one of threeThe flowchart compounds a starting value year by year until it reaches a target; inside each pass an if, elif, else test files the year's rate into one of three bands before the value grows and control returns to the target test.start: value 1000value below target?which rate band?fast: above 6%steady: 2% to 6%slow: below 2%grow value, year+1report years neededyesno
The flowchart compounds a starting value year by year until it reaches a target; inside each pass an if, elif, else test files the year's rate into one of three bands before the value grows and control returns to the target test.
  • 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.
Nine years are needed; the deposit is worth 2,171.89 when the loop ends, because eight years leave it at 1,992.56.
Sia tip — Print the counter and value inside the loop on a short run, and confirm the last two passes straddle the target.
Glossary

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.
FAQ

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.

Study strategy

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.

A+Everything unlocked
Unlocks this Bible + all 26 of your subjects at University of Glasgow, plus 1,000+ more Bibles across the AskSia library.
Sia - your ACCFIN5277 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works
ACCFIN5277 · Finance Programming in Python and Databases - independent study guide on the AskSia Library. More University of Glasgow subjects · Microeconomics across all universities