Module 1
Module 1
MODULE-1
THE WAY OF THE PROGRAM, VARIABLES, EXPRESSIONS, STATEMENTS,
ITERATION, AND FUNCTIONS
SYLLABUS:
The way of the program: The Python programming language, what is a program? What is debugging? Syntax errors,
Runtime errors, Semantic errors, Experimental debugging.
Variables, Expressions and Statements: Values and data types, Variables, Variable names and keywords, Statements,
Evaluating expressions, Operators and operands, Type converter functions, Order of operations, Operations on
strings, Input, Composition, The modulus operator.
Iteration: Assignment, updating variables, the for loop, the while statement, The Collatz 3n + 1 sequence, tables,
two-dimensional tables, break statement, continue statement, paired data, Nested Loops for Nested Data.
Functions: Functions with arguments and return values.
CHAPTERS: 1.1-1.7, 2.1-2.12, 3.3, 4.4, 4.5
TEXT BOOK: Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers- How to think like a computer
scientist: learning with python 3. Green Tea Press, Wellesley, Massachusetts, 2020
➢ The >>> is called the Python prompt. The interpreter uses the prompt to indicate that it is ready for
instructions. For example, typed 2 + 2, and the interpreter evaluated our expression, and replied 4, and
on the next line it gave a new prompt, indicating that it is ready for more input.
➢ Alternatively, you can write a program in a file and use the interpreter to execute the contents of the
file. Such a file is called a script. Scripts have the advantage that they can be saved to disk, printed, and
so on.
➢ Working directly in the interpreter is ideal for testing short code as it provides immediate feedback,
similar to using scratch paper for problem-solving. For longer code, use a script.
➢ To write a script, a text editor is essential, a program on your computer that changes text files, not a
word processor like MicrosoftWord or LibreOffice Writer. Examples include Notepad, Notepad++, vim,
emacs, and sublime.
➢ Python and other programming languages have development environments, which include a text editor
and interpreter interaction. Examples include Spyder, Thonny, and IDLE. Some development
environments run in the browser, like Jupyter Notebook. These environments, sometimes called
Integrated Development Environments or IDEs, are essential for efficient programming.
➢ The choice of development environment is quite personal. The important thing to remember is that
Python itself does not care in what editor is used to write your code. As long as you write correct syntax
(with the right tabs and spaces) Python can run your program. The editor is only there to help you.
WHAT IS A PROGRAM?
➢ A program is a sequence of instructions that specifies how to perform a computation. The computation
might be something mathematical, such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching and replacing text in a
document or (strangely enough) compiling a program.
➢ The details of a task may vary across different languages, but basic instructions are generally present in
almost all languages:
• Input: Get data from the keyboard, a file, or some other device such as a sensor.
• Output: Display data on the screen or send data to a file or other device such as a motor.
• Math: Perform basic mathematical operations like addition and multiplication.
• Conditional Execution: Check for certain conditions and execute the appropriate sequence of
statements.
• Repetition: Perform some action repeatedly, usually with some variation.
➢ Programming is the process of breaking down a complex task into smaller subtasks until they are simple
enough to be performed using sequences of basic instructions. Every program, regardless of complexity,
is composed of instructions similar to these.
WHAT IS DEBUGGING?
➢ Programming is a complex process, and because it is done by human beings, it often leads to errors.
Programming errors are called bugs and the process of tracking them down and correcting them is called
debugging.
➢ Use of the term bug to describe small engineering difficulties dates back to at least 1889, when Thomas
Edison had a bug with his phonograph.
➢ Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is
useful to distinguish between them in order to track them down more quickly.
SYNTAX ERRORS
➢ Python can only execute a program if the program is syntactically correct; otherwise, the process fails
and returns an error message.
➢ Syntax refers to the structure of a program and the rules about that structure.
➢ In English, a sentence must start with a capital letter and end with a period. This sentence contains a
syntax error. Most readers find these errors minor, allowing them to read E. E. Cummings' poetry
without issues.
➢ Python is not so forgiving because if there is a single syntax error anywhere in your program, Python
will display an error message and quit, and will not be able to run the program.
➢ Initially, in a programming career may spend a significant amount of time addressing syntax errors, but
with experience, later make fewer mistakes and find them faster.
RUNTIME ERRORS
➢ The second type of error is a runtime error, so called because the error does not appear until you run the
program.
➢ These errors are also called exceptions because they usually indicate that something exceptional (and
bad) has happened. Runtime errors are rare in the simple programs.
SEMANTIC ERRORS
➢ A semantic error is a third type of error where a program will run successfully without generating error
messages, but it will not perform the correct task, instead performing what you have instructed it to do.
➢ The program you wrote is not the desired one due to incorrect semantics. Identifying semantic errors is
challenging as it requires examining the program's output and determining its purpose, making it
difficult to work backwards.
EXPERIMENTAL DEBUGGING
➢ One of the most important skills is debugging. Although it can be frustrating, debugging is one of the
most intellectually rich, challenging, and interesting parts of programming.
➢ In some ways, debugging is like detective work. You are confronted with clues, and you have to infer
the processes and events that led to the results you see.
➢ Debugging is also like an experimental science. Once you have an idea what is going wrong, you modify
your program and try again. If your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your hypothesis was wrong, you have
to come up with a new one. As Sherlock Holmes pointed out, When you have eliminated the impossible,
whatever remains, however improbable, must be the truth. (A. Conan Doyle, The Sign of Four)
➢ For some people, programming and debugging are the same thing. That is, programming is the process
of gradually debugging a program until it does what you want. The idea is that you should start with a
program that does something and make small modifications, debugging them as you go, so that you
always have a working program.
➢ For example, Linux is an operating system kernel that contains millions of lines of code, but it started
out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry
Greenfield, one of Linus’s earlier projects was a program that would switch between displaying AAAA
and BBBB. This later evolved to Linux (The Linux Users’ Guide Beta Version 1).
World!" is a string, so-called because it contains a string of letters. Hence identifying strings is easy
because they are enclosed in quotation marks.
➢ If not sure what class a value falls into, Python has a function called type which can tell you.
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
➢ Strings belong to the class str, integers belong to the class int and numbers with a decimal point belong
to a class called float, because these numbers are represented in a format called floating-point. Here at
this stage, treat the words class and type interchangeably.
>>> type(3.2)
<class 'float'>
➢ What about values like "17" and "3.2"? They look like numbers, but they are in quotation marks like
strings. But, They’re strings!
>>> type("17")
<class 'str'>
>>> type("3.2")
<class 'str'>
➢ Strings in Python can be enclosed in either single quotes (') or double quotes ("), or three of each (' ' ' or
" " ")
>>> type('This is a string.')
<class 'str'>
>>> type("And so is this.")
<class 'str'>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str'>
➢ Double quoted strings can contain single quotes inside them, as in "Bruce's beard", and single quoted
strings can have double quotes inside them, as in 'The knights who say "Ni!"'. Strings enclosed with
three occurrences of either quote symbol are called triple quoted strings. They can contain either single
or double quotes:
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
>>>
➢ Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message)
This message will
CANARA ENGINEERING COLLEGE, MANGALORE 4
PYTHON PROGRAMMING 1BCDLC152/252
span several
lines.
>>>
➢ Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround
your strings: once it has parsed the text of your program or command, the way it stores the value is
identical in all cases, and the surrounding quotes are not part of the value. But when the interpreter
wants to display a string, it has to decide which quotes to use to make it look like a string. Hence, Python
language designers usually chose to surround their strings by single quotes.
>>> 'This is a string.'
'This is a string.'
>>> """And so is this."""
'And so is this.'
➢ When you type a large integer, you might be tempted to use commas between groups of three digits, as
in 42,000. The same goes for entering Dutch-style floating point numbers using a comma instead of a
decimal dot. This is not a legal integer in Python, but it does mean something else, which is legal:
>>> 42000
42000
>>> 42,000
(42, 0)
➢ Because of the comma, Python chose to treat this as a pair of values. But, remember not to put commas
or spaces in integers, no matter how big they are.
VARIABLES
➢ One of the most powerful features of a programming language is the ability to manipulate variables. A
variable is a name that refers to a value. The assignment statement gives a value to a variable:
>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159
➢ This example makes three assignments. The first assigns the string value "What's up, Doc?" to a variable
named message. The second gives the integer 17 to n, and the third assigns the floating-point number
3.14159 to a variable called pi.
➢ The assignment token, =, should not be confused with equals, which uses the token ==. The assignment
statement binds a name, on the left-hand side of the operator, to a value, on the right-hand side.
Basically, an assignment is an order, and the equals operator can be read as a question mark. This is
why an error if when entered:
>>> 17 = n
File "<interactive input>", line 1
SyntaxError: can't assign to literal
➢ A common way to represent variables on paper is to write the name with an arrow pointing to the
variable’s value. This kind of figure is called a state snapshot because it shows what state each of the
variables is in at a particular instant in time. (Think of it as the variable’s state of mind).
CANARA ENGINEERING COLLEGE, MANGALORE 5
PYTHON PROGRAMMING 1BCDLC152/252
➢ Some editors and programming environments do this for you, and allow you to click through the state
of the program saving you some paper. This diagram shows the result of executing the assignment
statements:
➢ If asked the interpreter to evaluate a variable, it will produce the value that is currently linked to the
variable:
>>> message
'What's up, Doc?'
>>> n
17
>>> pi
3.14159
➢ We use variables in a program to “remember” things, perhaps the current score at the football game.
But variables are variable. This means they can change over time, just like the scoreboard at a football
game. You can assign a value to a variable, and later assign a different value to the same variable. (This
is different from maths. In maths, if you give ‘x‘ the value 3, it cannot change to link to a different value
half-way through your calculations!)
>>> day = "Thursday"
>>> day
'Thursday'
>>> day = "Friday"
>>> day
'Friday'
>>> day = 21
>>> day
21
➢ Changed the value of day three times, and on the third assignment we even made it refer to a value that
was of a different type.
➢ A great deal of programming is about having the computer remember things, e.g. The number of missed
calls on your phone, and then arranging to update or change the variable when you miss another call.
➢ Programmers generally choose names for their variables that are meaningful to the human readers of
the program —they help the programmer document, or remember, what the variable is used for.
➢ Beginners sometimes confuse “meaningful to the human readers” with “meaningful to the computer”.
So they’ll wrongly think that because they’ve called some variable average or pi, it will somehow
magically calculate an average, or magically know that the variable pi should have a value like 3.14159.
No! The computer doesn’t understand what intend the variable to mean.
➢ So you’ll find some instructors who deliberately don’t choose meaningful names when they teach
beginners not because we don’t think it is a good habit, but because we’re trying to reinforce the
message that the programmer, must write the program code to calculate the average, and must write an
assignment statement to give the variable pi the value want it to have.
e = 3.1415
ray = 10
size = e * ray ** 2
pi = 3.1415
radius = 10
area = pi * radius ** 2
➢ The above two snippets do exactly the same thing, but the bottom one uses the right kind of variable
names. For the computer there is no difference at all, but for a human, using the names and letters that
are part of the conventional way of writing things make all the difference in the world. Using e instead
of pi completely confuses people, while computers will just perform the calculation!
STATEMENTS
➢ A statement is an instruction that the Python interpreter can execute. We have only seen the assignment
statement so far.
➢ Some other kinds of statements that we’ll see shortly are while statements, for statements, if statements,
and import statements. (There are other kinds too!)
➢ When typed a statement on the command line, Python executes it. Statements don’t produce any result.
EVALUATING EXPRESSIONS
➢ An expression is a combination of values, variables, operators, and calls to functions. If typed an
expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
>>> len("hello")
5
➢ In this example len is a built-in Python function that returns the number of characters in a string.
➢ The evaluation of an expression produces a value, which is why expressions can appear on the right-
hand side of assignment statements. A value all by itself is a simple expression, and so is a variable.
>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
10.75
➢ In Python 3, the division operator / always yields a floating point result. What might have wanted to
know was how many whole hours there are, and how many minutes remain. Python gives us two
different flavors of the division operator. The second, called floor division uses the token //. Its result is
always a whole number and if it has to adjust the number it always moves it to the left on the number
line. So 6 // 4 yields 1, but -6 // 4 yields -2.
>>> 7 / 4
1.75
>>> 7 // 4
1
>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10
➢ Choose the correct flavor of the division operator. If working with expressions where need floating
point values, use the division operator that does the division accurately.
➢ The type converter float can turn an integer, a float, or a syntactically legal string into a float:
>>> float(17)
17.0
>>> float("123.45")
123.45
➢ The type converter str turns its argument into a string:
>>> str(17)
'17'
>>> str(123.45)
'123.45'
ORDER OF OPERATIONS
➢ When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence. Python follows the same precedence rules for its mathematical operators that mathematics
does. The acronym PEMDAS is a useful way to remember the order of operations:
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order wanted. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2)
is 8. It can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even
though it doesn’t change the result.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not
27.
3. Multiplication and both Division operators have the same precedence, which is higher than Addition
and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 5-2*2
is 1, not 6.
4. Operators with the same precedence are evaluated from left-to-right. In algebra, they are left-
associative. So in the expression 6-3+2, the subtraction happens first, yielding 3. Then add 2 to get
the result 5. If the operations had been evaluated from right to left, the result would have been 6-
(3+2), which is 1. (The acronym PEDMAS could mislead you to thinking that division has higher
precedence than multiplication, and addition is done ahead of subtraction, don’t be misled.
Subtraction and addition are at the same precedence, and the left-to-right rule applies.)
➢ Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation
operator **, so a useful hint is to always use parentheses to force exactly the order wanted when
exponentiation is involved:
>>> 2 ** 3 ** 2 # The right-most ** operator gets done first!
512
>>> (2 ** 3) ** 2 # Use parentheses to force the order you want!
64
➢ The immediate mode command prompt of Python is great for exploring and experimenting with
expressions like this.
OPERATIONS ON STRINGS
➢ In general, it cannot perform mathematical operations on strings, even if the strings look like numbers.
The following are illegal (assuming that message has type string):
CANARA ENGINEERING COLLEGE, MANGALORE 10
PYTHON PROGRAMMING 1BCDLC152/252
INPUT
➢ There is a built-in function in Python for getting input from the user:
name = input("Please enter your name: ")
➢ The user of the program can enter the name and click OK, and when this happens the text that has been
entered is returned from the input function, and in this case assigned to the variable name.
➢ Even if asked the user to enter their age, you would get back a string like "17". It would be a job, as the
programmer, to convert that string into a int or a float, using the int or float converter functions we saw
earlier.
COMPOSITION
➢ We have looked at the elements of a program: variables, expressions, statements, and function calls, in
isolation, without talking about how to combine them.
➢ One of the most useful features of programming languages is their ability to take small building blocks
and compose them into larger chunks.
➢ For example, we know how to get the user to enter some input, we know how to convert the string we
get into a float, we know how to write a complex expression, and we know how to print values. Let’s
put these together in a small four-step program that asks the user to input a value for the radius of a
circle, and then computes the area of the circle from the formula:
Area = 𝜋𝑅2
➢ Firstly, we’ll do the four steps one at a time:
response = input("What is your radius? ")
r = float(response)
area = 3.14159 * r**2
CANARA ENGINEERING COLLEGE, MANGALORE 11
PYTHON PROGRAMMING 1BCDLC152/252
ITERATION
➢ Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without
making errors is something that computers do well and people do poorly.
CANARA ENGINEERING COLLEGE, MANGALORE 12
PYTHON PROGRAMMING 1BCDLC152/252
➢ Repeated execution of a set of statements is called iteration. Because iteration is so common, Python
provides several language features to make it easier, already seen the for statement. This is the form of
iteration likely be using most often.
➢ But here we’re going to look at the while statement — another way to have your program do iteration,
useful in slightly different circumstances.
ASSIGNMENT
➢ It is legal to make more than one assignment to the same variable. A new assignment makes an existing
variable refer to a new value (and stop referring to the old value), because the first time
airtime_remaining is printed, its value is 15, and the second time, its value is 7.
airtime_remaining = 15
print(airtime_remaining)
airtime_remaining = 7
print(airtime_remaining)
The output of this program is:
15
7
➢ It is especially important to distinguish between an assignment statement and a Boolean expression that
tests for equality. Because Python uses the equal token (=) for assignment, it is tempting to interpret a
statement like a = b as a Boolean test. Unlike mathematics, it is not! Remember that the Python token
for the equality operator is ==.
➢ Note too that an equality test is symmetric, but assignment is not. For example, if a == 7 then 7 == a.
But in Python, the statement a = 7 is legal and 7 = a is not.
➢ In Python, an assignment statement can make two variables equal, but because further assignments can
change either of them, they don’t have to stay that way:
a=5
b=a # After executing this line, a and b are now equal
a=3 # After executing this line, a and b are no longer equal
➢ The third line changes the value of a but does not change the value of b, so they are no longer equal. (In
some programming languages, a different symbol is used for assignment, such as <- or :=, to avoid
confusion.
➢ Some people also think that variable was an unfortunae word to choose, and instead we should have
called them assignables. Python chooses to follow common terminology and token usage, also found
in languages like C, C++, Java, and C#, so we use the tokens = for assignment, == for equality, and we
talk of variables.
UPDATING VARIABLES
➢ When an assignment statement is executed, the right-hand side expression (i.e. the expression that
comes after the assignment token) is evaluated first. This produces a value. Then the assignment is
made, so that the variable on the left-hand side now refers to the new value.
➢ One of the most common forms of assignment is an update, where the new value of the variable depends
on its old value. Deduct 40 cents from my airtime balance, or add one run to the scoreboard.
n=5
n=3*n+1
➢ Line 2 means get the current value of n, multiply it by three and add one, and assign the answer to n,
thus making n refer to the value. So after executing the two lines above, n will point/refer to the integer
16.
➢ If you try to get the value of a variable that has never been assigned to, you’ll get an error:
>>> w = x + 1
Traceback (most recent call last):
File "<interactive input>", line 1, in
NameError: name 'x' is not defined
➢ Before updating a variable, have to initialize it to some starting value, usually with a simple assignment:
runs_scored = 0
...
runs_scored = runs_scored + 1
➢ Line 3, updating a variable by adding 1 to it, is very common. It is called an increment of the variable;
subtracting 1 is called a decrement. Sometimes programmers also talk about bumping a variable, which
means the same as incrementing it by 1. This is commonly done with the += operator.
runs_scored = 0
...
runs_scored += 1
TABLES
➢ One of the things loops are good for is generating tables. Before computers were readily available,
people had to calculate logarithms, sines and cosines, and other mathematical functions by hand. To
make that easier, mathematics books contained long tables listing the values of these functions. Creating
the tables was slow and boring, and they tended to be full of errors.
➢ When computers appeared on the scene, one of the initial reactions was, “This is great! We can use the
computers to generate the tables, so there will be no errors.” That turned out to be true (mostly) but
shortsighted. Soon thereafter, computers and calculators were so pervasive that the tables became
obsolete.
➢ Well, almost. For some operations, computers use tables of values to get an approximate answer and
then perform computations to improve the approximation. In some cases, there have been errors in the
underlying tables, most famously in the table the Intel Pentium processor chip used to perform floating-
point division.
➢ Although a log table is not as useful as it once was, it still makes a good example of iteration. The
following program outputs a sequence of values in the left column and 2 raised to the power of that
value in the right column:
for x in range(13): # Generate numbers 0 to 12
print(x, "\t", 2**x)
➢ The string "\t" represents a tab character. The backslash character in "\t" indicates the beginning of an
escape sequence. Escape sequences are used to represent invisible characters like tabs and newlines.
The sequence \n represents a newline.
➢ An escape sequence can appear anywhere in a string; in this example, the tab escape sequence is the
only thing in the string. How do you think you represent a backslash in a string?
➢ As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track
of where the next character will go. After a print function, the cursor normally goes to the beginning of
the next line.
➢ The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for
making columns of text line up, as in the output of the previous program:
➢ Because of the tab characters between the columns, the position of the second column does not depend
on the number of digits in the first column.
TWO-DIMENSIONAL TABLES
➢ A two-dimensional table is a table where you read the value at the intersection of a row and a column.
A multiplication table is a good example. Let’s say you want to print a multiplication table for the values
from 1 to 6.
➢ A good way to start is to write a loop that prints the multiples of 2, all on one line:
for i in range(1, 7):
print(2 * i, end=" ")
print()
➢ Here we’ve used the range function, but made it start its sequence at 1. As the loop executes, the value
of i changes from 1 to 6. When all the elements of the range have been assigned to i, the loop terminates.
Each time through the loop, it displays the value of 2 * i, followed by three spaces.
➢ Again, the extra end=" " argument in the print function suppresses the newline, and uses three spaces
instead. After the loop completes, the call to print at line 3 finishes the current line, and starts a new
line.
➢ The output of the program is:
2 4 6 8 10 12
PAIRED DATA
➢ Here it shows a more advanced way of representing our data. Making a pair of things in Python is as
simple as putting them into parentheses, like this:
year_born = ("Paris Hilton", 1981)
➢ We can put many pairs into a list of pairs:
celebs = [("Brad Pitt", 1963), ("Jack Nicholson", 1937),
("Justin Bieber", 1994)]
➢ Here is a quick sample of things we can do with structured data like this. First, print all the celebs:
print(celebs)
print(len(celebs))
CANARA ENGINEERING COLLEGE, MANGALORE 19
PYTHON PROGRAMMING 1BCDLC152/252
if s == "CompSci":
counter += 1
print("The number of students taking CompSci is", counter)
The number of students taking CompSci is 3
➢ A more concise of doing this would be the following:
counter = 0
for name, subjects in students:
if "CompSci" in subjects:
counter += 1
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
➢ So an important difference between these functions and one like draw_square is that draw_square was
not executed because we wanted it to compute a value i.e, on the contrary, we wrote draw_square
because we wanted it to execute a sequence of steps that caused the turtle to draw.
➢ A function that returns a value is called a fruitful function in this book. The opposite of a fruitful
function is void function — one that is not executed for its resulting value, but is executed because it
does something useful. (Languages like Java, C#, C and C++ use the term “void function”, other
languages like Pascal call it a procedure.)
➢ Even though void functions are not executed for their resulting value, Python always wants to return
something. So, if the programmer doesn’t arrange to return a value, Python will automatically return
the value None.
➢ The standard formula for compound interest, which we’ll now write as a fruitful function:
• The return statement is followed an expression (a in this case). This expression will be evaluated
and returned to the caller as the “fruit” of calling this function.
• We prompted the user for the principal amount. The type of toInvest is a string, but we need a
number before we can work with it. Because it is money, and could have decimal places, we’ve
used the float type converter function to parse the string and return a float.
• Notice how we entered the arguments for 8% interest, compounded 12 times per year, for 5
years.
• When we run this, we get the output
At the end of the period you’ll have 14898.457083
This is a bit messy with all these decimal places, but remember that Python doesn’t understand
that we’re working with money: it just does the calculation to the best of its ability, without
rounding. Later we’ll see how to format the string that is printed in such a way that it does get
nicely rounded to two decimal places before printing.
• The line toInvest = float(input("How much do you want to invest?")) also shows yet another
example of composition — we can call a function like float, and its arguments can be the results
of other function calls (like input) that we’ve called along the way.
➢ Notice something else very important here. The name of the variable we pass as an argument — toInvest
— has nothing to do with the name of the parameter—p. It is as if p = toInvest is executed when
final_amount is called. It doesn’t matter what the value was named in the caller, in final_amount its
name is p.
➢ These short variable names are getting quite tricky, so perhaps we’d prefer one of these versions instead:
def final_amount_v2(principal_amount, nominal_percentage_rate,
num_times_per_year, years):
a = principal_amount * (1 + nominal_percentage_rate /
num_times_per_year) ** (num_times_per_year*years)
return a
def final_amount_v3(amount, rate, compounded, years):
a = amount * (1 + rate/compounded) ** (componded*years)
return a
def final_amount_v4(amount, rate, compounded, years):
"""
The a in final_amount_v3 was a useless asignment.
We might as well skip it.
"""
return amount * (1 + rate/compounded) ** (componded*years)
➢ They all do the same thing. Use your judgement to write code that can be best understood by other
humans! Short variable names should generally be avoided, unless when short variables make more
sense. This happens in particular with mathematical equations, where it’s perfectly fine to use x, y, etc.