1.8. Formatting code#
It is good programming practice to format your code using spaces, blank lines and commands so that it can be easily read. Guidelines for formatting Python code can be found in the PEP style guide for Python code and this section covers some of the basics.
1.8.2. Spaces#
In a Python program spaces are ignored, however it is common practice to use spaces either side of the arithmetic operators so that it is more readable. It is also advisable to separate blocks of code with a blank line.
For example the code
1*2+3*4+5/6
is equivalent to the code
1 * 2 + 3 * 4 + 5 / 6
1.8.3. Exercise#
The repayments for a loan can be calculated using the formula
where
\(P\) is the monthly repayment
\(V\) is the value of the loan
\(r\) is the interest rate per period
\(n\) is the number of periods
The program below calculates the monthly repayments for a mortgage of value £200,000 taken out over 20 years with a fixed annual interest rate of 4%.
# Exercise 1.5
a=200000
b=20
c=4
d=12*20
e=c/100/12
f=e*a/(1-(1+e/100)**(-d))
print(a)
print(b)
print(c)
print(f)
Copy and paste this program into your Python file and edit it to do the following:
Replace variables
a
tof
with suitable descriptive variable namesUse spaces to improve the code formatting
Add comments to briefly explain what the program is doing
Edit the print commands so that the program outputs the loan details and the monthly repayment amount in the following format
Loan repayment calculator
-------------------------
Loan amount : £xxxxxx.xx
Loan duration : xx years
Annual interest rate : xx%
Monthly repayment : £xxxx.xx
1.8.1. Comments#
A comment in a program is text that is ignored by Python when the code is executed and are useful to helping people understand the program. Comments in Python can be entered in two ways. The first is to use the
#
symbol# this is a comment
Here any text on the same line to the right of
#
is ignored. These are useful for short comments. For longer comments that span multiple lines we can use"""
to start and end a comment.Comments are useful for telling someone (and yourself) what a program and individual lines of a program do. Add some comments to your program similar what is shown below.