0% found this document useful (0 votes)
23 views25 pages

Python Programming Notes Module 1

The document provides an overview of Python programming, covering its classification as a high-level language, advantages, and basic concepts such as programs, debugging, variables, data types, and expressions. It explains the types of errors in programming, including syntax, runtime, and semantic errors, and introduces fundamental programming constructs like input, output, and operations on strings. Additionally, it discusses the importance of variable names, statements, and the order of operations in Python.

Uploaded by

darshanking2303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views25 pages

Python Programming Notes Module 1

The document provides an overview of Python programming, covering its classification as a high-level language, advantages, and basic concepts such as programs, debugging, variables, data types, and expressions. It explains the types of errors in programming, including syntax, runtime, and semantic errors, and introduces fundamental programming constructs like input, output, and operations on strings. Additionally, it discusses the importance of variable names, statements, and the order of operations in Python.

Uploaded by

darshanking2303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING - 1BPLC105B/205B

MODULE - 1

1 The way of the program


1.1 The Python programming language
There are several programming languages and they can be classified into high-level and
low-level languages. Python is an example of a high-level language, other high-level
languages are C + +, P HP , Pascal, C# and Java. There are low-level languages also
which are referred to as machine languages or assembly languages.

Advantages of high-level languages

1. It is easier to program.

2. The program takes less time to write.

3. They are shorter and easier to read and they are more likely to be correct.

4. They are portable which means that they can run on different kinds of computers
with few or no modifications.

The engine that translates and runs Python is called Python Interpreter. The >>> is
called the Python prompt. The interpreter uses the prompt to indicate that it is ready
for instructions. There are two ways to use it.

1. Immediate mode
In immediate mode, we type python expressions into the Python interpreter win-
dow and the interpreter immediately shows the result.

2. Script mode
We 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. Their advantage is that, they can be
saved to disk, printed and so on.

For python, there are programs that include both a text editor and a way to interact
with the interpreter. These are called development environments. Some of the devel-
opment environments are Spyder, Thonny or IDLE. The most commonly used one is
Jupyter Notebook.

1.2 What is a program


A program is a sequence of instructions that specifies how to perform a computation.
Computation can be mathematical like solving a system of equations or finding roots of
a polynomial. It just can also be compiling a program.

1
1.3 Basic building blocks of programming
1. Input
Getting data from the user or from an external source, so the program can use it.
2. Output
Displaying information back to the user or sending results to a file/screen.
3. Math
Perform basic mathematical operations like addition and multiplication.
4. Conditional execution
Check for certain conditions and execute the appropriate sequence of statements.
5. Repetition Perform some action repeatedly, usually with some variation.

1.4 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. There are three kinds of error - syntax
errors, runtime errors and semantic errors.

1.5 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 pro-
gram and the rules about that structure.
If there is a single syntax error anywhere in the program, Python will display an error
message and quit.
Example:
print ( " Hello World

Output:
SyntaxError : unterminated string literal ( detected at line 1 )

If there is a single syntax error anywhere in the program, Python will display an error
message and quit, and we will not be able to run the program.

1.6 Runtime errors


The second type of error is a runtime error because the error does not appear until we
run the program. These errors are also called exceptions because they usually indicate
something bad has happened.
Example: Divide 10 by 0
10 / 0

Output:
ZeroD ivisionE rror : division by zero

The sentence is gramatically correct but dividing by 0 is not possible. So it gives run-
time error.

2
1.7 Semantic errors
The third type of error is the semantic error. Even though there is a semantic error in
the program, it will run successfully, in the sense that the computer will not generate
any error messages, but it will not do the right thing. It will do something else.
Example:
a = 10
b = 20
average = a + b / 2
print ( " Average : " , average )

Output:
Average : 20 . 0

1.8 Experimental debugging


Debugging is one of the most intellectually rich, challenging and interesting parts of
programming. Debugging is like an experimental science. Once we have an idea of
what is going wrong, we can modify the program and try again. If the hypothesis is
correct, then we can predict the results and we can take a step closer to a working pro-
gram. If the hypothesis is wrong, we have to come up with a new one.
For some people, programming and debugging are the same thing. That is, program-
ming 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 mod-
ifications, debugging them as you go, so that you always have a working program.

2 Variables, expressions and statements


2.1 Values and data types
Values represent a letter or a number.
Example: 4, "Hello, World!"
These values are seggregated into different classes or data types.
Example: 4 is an integer.
"Hello, World!" is a string.

Strings are easier to identify because it will always be enclosed in quotation marks.
If we are not sure in which class or data type, a value falls into, Python has a function
called ‘type’ which gives the class or data type. Example:
type ( " Hello World ! " )
type ( 17 )

Output:
str
int

3
Strings belong to the class str.
Integers belong to the class int.
Decimal numbers belong to the class float.
type ( 3 . 2 )

Output:
float

Anything that is written within the parenthesis are strings. They are always enclosed
in either single quotes or double quotes or triple quotes.
Example:
type ( " 17 " )
type ( " 3 . 2 " )
type ( ' This is a string ')
type ( " This is also a string " )
type ( ' ' ' This is also a string ' ' ')

Output:
str
str
str
str
str

Double quoted string can contain single quotes and vice versa. Triple quoted strings
can span multiple lines.
Example:
print ( ' ' '" Today is a an auspicious day to celebrate , " Ganesh Chathurthi
" throughout India ." ' ' ')

Output:
" Today is a an auspicious day to celebrate , " Ganesh Chathurthi "
throughout India . "

Example:
message = """ This message will
... span several
... lines . """
print ( message )

Output:
This message will
span several
lines .

Python does not care if we use a single or double or triple quotes to display the string.
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.
Example:
' This is a string . '

4
Output:
' This is a string . '

Example:
""" And so is this . """

Output:
' And so is this . '

So, the Python language designers usually chose to surround their strings by single
quotes.

Now, when we write numbers/integers we write it as, say for eg, 42,000 i.e., we put
comma in certain places. But when we implement this in python, we get the following
42 , 000

Output:
( 42 , 0 )

Python treats this as a pair of values. So do not put commas or spaces in the integers.
Example:
42000

Output:
42000

2.2 Variables
One of the most powerful features of a programming language is the ability to manipu-
late variables. A variable is a name that refers to a value.
message = " What 's up , Doc ? "
n = 17
pi = 3 . 14159
print ( message )
print ( n )
print ( pi )

Output:
What 's up , Doc ?
17
3 . 14159

This example makes 3 assignments. The first assigns the string value "Good morn-
ing" to a variable named message. The second gives the integer 17 to a variable n. The
third assigns the floating-point number 3.14159 to a variable called pi.

The assignment token, =, should not be confused with equals. In python, equal is rep-
resented as "==". All the above examples just assigns the variable. If we write in a
paper, we can write it as

5
We say message is assigned to Good morning.
n is assigned to 17.
pi is assigned to 3.14159.

If we ask the interpreter to evaluate a variable, it will produce the value that is cur-
rently linked to the variable.
Example:
message

pi

Output:
' What 's up , Doc ? '

17

3 . 14159

We can assign a value to a variable and later assign a different value to the same vari-
able.
Example:
Input:
day = " Thursday "
day

Output:
' Thursday '

Input:
day = " Friday "
day

' Friday '

Input:
day = 21
day

Output:
21

It is noticed that the value of day is changed three times, and on the third assignment
we even made it refer to a value that was of a different type.

6
2.3 Variable names and keywords
Variable names can be arbitrarily long. They can contain both letters and digits, but
they have to begin with a letter or an underscore. Although, we can use uppercase let-
ters, by convention we don’t. If at all we use upper case letters, we have to remember
that python is case sensitive. Bruce and bruce are different variables.
The underscore character (_) can appear in a name. It is often used in names with
multiple words, such as my_name.
my_name = " SHRUTHY "
print ( my_name )

Output:
SHRUTHY

Input:
76trombones = " big parade "
print ( 76trombones )

Output:
SyntaxError : invalid decimal literal

76trombones is illegal because it does not begin with a letter.


more \ $ = 1000000
print ( more \ $ )

Output:
SyntaxError : invalid syntax

more$ is illegal because it contains an illegal character, the dollar sign.


class = " Computer Science 101 "
print ( class )

Output:
SyntaxError : invalid syntax

We cannot use class as a variable name. Because it is already used by Python as a key-
word. It is built-in and defines the language’s syntax rule and structure. They cannot
be used as variable names. Python has more than 30 keywords and they are given in
the table below

7
2.4 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 are while state-
ments, f or statements, if statements, and import statements. When we type a state-
ment on the command line, Python executes it. Statements donâĂŹt produce any re-
sult.

2.5 Evaluating expressions


An expression is a combination of values, variables, operators, and calls to functions. If
we type an expression at the Python prompt, the interpreter evaluates it and displays
the result:
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 ex-
pression, and so is a variable.
Example:

2.6 Operators and Operands


Operators are special tokens that represent computations like addition, multiplication
and division. The values the operator uses are called operands. The legal Python ex-
pressions are as follows:

8
The tokens are +, - and *. The use of parenthesis in Python is the same as what they
mean in mathematics. The symbol for multiplication is *. The symbol for exponentia-
tion is **.
Example:

When a variable name appears in the place of an operand, it is replaced with its value
before the operation is performed.
Example: Let us convert 645 minutes into hours.

The division operator / always gives a floating point result. Floor division uses // sym-
bol. Its result is always a whole number.

2.7 Type converter functions


Three more Python functions, int, f loat and str, which will (attempt to) convert their
arguments into types int, f loat and str respectively. We call these type converter func-
tions.
The int function can take a floating point number or a string, and turn it into an int.
For floating point numbers, it discards the decimal portion of the number - a process
we call truncation towards zero on the number line.

9
The last example gives an error because we are trying to find the integer form of a
string, which is not possible. Nevertheless, if there was only a string in the form of a
number, then we could have parsed a string to produce an output. The same way it
was done in the previous example of int(“2345”).

The type converter f loat can turn an integer, a float, or a syntactically legal string into
a float:

The type converter str turns its argument into a string:

10
2.8 Order of operations
When more than one operator appears in an expression, the order of evaluation de-
pends 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 you want. Since expressions in parentheses are evaluated
first, we have the following. Also, we can use parentheses to make an expression
easier to read. You can also use parentheses to make an expression easier to read.

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.

2.9 Operations on strings


In general, we cannot perform mathematical operations on strings, even if the string
look like numbers. But, the + operator does work with strings. For strings, the + op-
erator represents concatenation, not addition. Concatenation means joining the two
operands by linking them end-to-end.
Example:

The space before the word nut is part of the string, and is necessary to produce the
space between the concatenated strings. The * operator also works on strings; it per-
forms repetition.
Example:

11
One of the operands has to be a string; the other has to be an integer.
The interpretation of + and * has analogy with addition and multiplication. Eg: 4*3 is
equivalent to 4+4+4. Similarly "Fun"*3 = "Fun" + "Fun" + "Fun".
Commutative property is a property that addition and multiplication have that string
concatenation and repetition do not.

2.10 Input
There is a built-in function in Python for getting input from the user:
name = input ( " Please enter your name : " )

Output:
Please enter your name : Shruthy

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 as-
signed to the variable "name".
age = int ( input ( " Please enter your age : " ) )

. Output:
Please enter your age : 25

2.11 Composition
One of the most useful features of programming languages is their ability to take small
building blocks and compose them into larger chunks.
Example: 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 = πR2

Now let’s compose the first two lines into a single line of code, and compose the second
two lines into another line of code.
r = float ( input ( " What is your radius ? " ) )
print ( " The area is " , 3 . 14159 * r ** 2 )

We can also write the entire code in one statement.


print ( " The area is " , 3 . 14159 * float ( input ( " What is your radius ? " ) ) ** 2 )

12
2.12 The modulus operator
The modulus operator works on integers (and integer expressions) and gives the re-
mainder when the first number is divided by the second. In Python, the modulus oper-
ator is a percent sign (%).

3 Iteration
Iteration in mathematics refers to the process of repeatedly applying a function or a
mathematical procedure, where the output of each step is used as the input. Comput-
ers are often used to automate repetitive tasks. Repeated execution of a set of state-
ments is called iteration. Because iteration is so common, Python provides several lan-
guage features to make it easier to understand f or statement, while statement, and so
on.

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

Difference between an assignment statement and a Boolean expression that


tests for equality
Python uses equal (=) token for assignment and the Python token for equality operator
is ==.

13
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:
Example:
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 language, a different symbol is used for assignment,
such as < − or :=. But Python chooses to follow common terminology like C, C++,
Java and C#. So we use = for assignment and == for equality.

3.2 Updating variables


When an assignment statement is executed, the right-hand side expression 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 assign-
ment is an update, where the new value of the variable depends on its old value.
Example:

Line 2 gives the current value of n. So after executing the two lines above, the updated
value of n will be 16.
If we try to get the value of a variable that has never been assigned to, we will get an
error:

Before you can update a variable, we have to initialize it to some starting value, usually
with a simple assignment:
runs_scored = 0
...
runs_scored = runs_scored + 1

14
Line 2 is updating a variable by adding 1 to it. It is called increment of the variable.
Another term used for an increment is bumping a variable. This is commonly done
with += operator. So, the previous syntax can also be written as
runs_scored = 0
...
runs_scored + = 1

3.3 The for loop revisited


A for loop in Python is a way to repeat a block of code for each item in a collection,
like a list, string or range of numbers. It automatically goes through each item one by
one and runs the code inside the loop for each item. This helps to do repetitive tasks
easily without writing the same code multiple times.
Example 1: If we have a list of fruits and want to print each one, a ‘for’ loop can go
through the list and print each fruit automatically.

This code prints every fruit in the list, one at a time.


Example 2: Looping through a string to print each character.

Example 3: Looping through a range of numbers from 0 to 4.

Example 4:

15
Running through all the items in a list is called traversing a list or traversal.
Example 5:

3.4 The while statement


A while statement in Python creates a loop that repeatedly executes a block of code
as long as a specified condition remains true. The condition is evaluated before every
iteration and the loop stops, when the condition becomes false. Generally the syntax is
given as
while < CONDITION > :
< STATEMENT >

Example 1: Counting loop

The loop prints numbers 1 through 5. The loop runs as long as i < 6. After each it-
eration, i increases by 1 and eventually the condition becomes false, halting the loop.
Example 2:

16
The following is the precise flow of execution for a while statement:

• Evaluate the condition at line 4, yielding a value which is either F alse or T rue.

• If the value is F alse, exit the while statement and continue execution at the next
statement (line 7 in this case).

• If the value is T rue, execute each of the statements in the body (lines 5 and 6)
and then go back to the while statement at line 4.

The body consists of all of the statements indented below the while keyword. If the
loop condition is false, the first time we get loop, the statements in the body of the
loop are never executed. The body of the loop should change the value of one or more
variables so that eventually the condition becomes false and the loop terminates. Oth-
erwise the loop will repeat forever, which is called an infinite loop.

This is the same example as Example 2. Here, we use for loop instead of while loop.

Feature While loop For loop


Initialization The loop variable (i) must be The loop variable (i) is automati-
initialized before the loop cally initialized by range.
Condition Explicit condition i<=n is re- The loop automatically repeats for
quired in the loop each value in range (n+1).
Increment The variable i must be manually The loop variable (i) is incremented
incremented (i+=1) automatically by range.
Ease of use More error, manual management Simple, less error.
of variables and condition

17
3.5 The Collatz 3n+1 sequence
It was coined by German mathematician called Lothar Collatz. The Collatz conjecture
is also known as 3n+1 conjecture. The Collatz 3n+1 sequence is the famous unsolved
problem in mathematics that involves a simple rule applied repeatedly to positive inte-
gers. So far no one has been able to prove it.
The Rule
Start with any positive integer n. Then apply the following steps repeatedly.
n
1. If n is even. Divide the number by 2. i.e., n = .
2
2. if n is odd. Multiply by 3 and add 1. i.e., n = 3n + 1.

Repeat this process again and again for each new value of n. No matter which num-
ber you start with, the sequence always reaches 1 i.e., the sequence terminates when n
reaches 1.

The print function on line 4 has an extra argument end=", ". This tells the print func-
tion to follow the printed string with whatever the programmer chooses (in this case,
a comma followed by a space), instead of ending the line. So each time something is
printed in the loop, it is printed on the same output line, with the numbers separated
by commas. The call to print (n, end=".\n") at line 9 after the loop terminates will
then print the final value of n followed by a period and a newline character.
The condition for continuing with this loop is n! = 1, so the loop will continue running
until it reaches its termination condition, (i.e. n == 1).
Each time through the loop, the program outputs the value of n and then checks whether
it is even or odd. If it is even, the value of n is divided by 2 using integer division. If it
is odd, the value is replaced by n * 3 + 1.

3.6 Tables
One of the things loops are good for is generating tables. Table is a way to organize
data into rows and columns, similar to spreadsheets or database tables. Tables are use-
ful for storing, manipulating and analyzing structured data.

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:

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

3.7 Two-dimensional tables


A two-dimensional table is a table where you read the value at the intersection of a
row and a column. Each element in the table can be accessed using row and column
indices. A multiplication table is a good example.
Example 1: Multiplication table

Here we have 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 com-
pletes, the call to print at line 3 finishes the current line, and starts a new line.

3.8 The break statement


The break statement is used inside loops (for or while) to stop the loop immediately,
even if the loop condition is still true.
Once break condition is executed:

19
• The program exits the loop at once.

• Execution continues with the next statement after the loop.

Example 1:

The loop breaks at i=6. So because of the break statement, the loop stops immedi-
ately and executes only till 5. The numbers 6 to 10 are not printed, because the loop
stopped at i=6.
Example 2:

So if i is odd, the condition i%2=1 is True, and since break statement is given, it will
stop the loop.

3.9 The continue statement


The continue statement is used inside loops (for or while) to skip the rest of the code in
the current iteration and move directly to the next iteration of the loop.
Example 1:

20
Since we have used continue statement, at i=6, we will not get a value. But the rest of
the code will be printed.
Example 2:

So, for the condition i%2=1, python will skip the value. The rest will be printed.

len
It gives the number of elements.
Example:

3.10 Paired data


Paired data refers to a set of data where each element in one collection corresponds di-
rectly to an element in another collection. Each pair is treated as a tuple (x,y) or as
two aligned lists where the ith element of one list corresponds to the ith element of the
other list. Making a pair of things in Python is as simple as putting them into paren-
theses, like this:
year_born = ( " Paris Hilton " , 1981 )

21
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:

The celebs list has just 3 elements, each of them pairs.


Now we print the names of those celebrities born before 1980:

Here, we have used a pair of variable names, (name, year). The loop is executed three
times-once for each pair in the list, and on each iteration both the variables are as-
signed values from the pair of data that is being handled.

3.11 Nested Loops for Nested Data


A nested loop is a loop inside another loop. In Python, nested loops are often used to
process nested data structures such as lists of lists, tuples of tuples and so on. Nested
loops allow you to access each element at multiple levels making it possible to work
with rows, columns or multi-level structures. In this case, we have a list of students.
Each student has a name which is paired up with another list of subjects that they are
enrolled for:
students = [ ( " John " ,[ " Comp " ," Phy " ] ) ,
( " Rahul " ,[ " Maths " ," Comp " ," Stats " ] ) ,
( " Jess " ,[ " Comp " , " Accounts " , " Eco " , " MBA " ] ) ,
( " sarah " ,[ " Sci " , " Accounts " , " Eco " , " Law " ] ) ,
( " Rohit " ,[ " Soc " , " Eco " , " Law " , " Stats " , " Music " ] )
]

Here we’ve assigned a list of five elements to the variable students. LetâĂŹs print out
each student name, and the number of subjects they are enrolled for:

22
Now we would like to see how many students are taking Comp. This needs a counter,
and for each student we need a second loop that tests each of the subjects in turn:

The first loop prints how many courses each student is taking. The second nested loop
counts how many students are taking a specific course.

A shorter concise way to write the code is as follows:

4 Functions
In Python, a function is a named sequence of statements that belong together. Their
primary purpose is to help us organize programs into chunks that match how we think
about the problem. The syntax for a function definition is:
def < NAME > ( < PARAMETERS > ) :
< STATEMENTS >

We can make up any names we want for the functions we create, except that we canâĂŹt
use a name that is a Python keyword, and the names must follow the rules for legal
identifiers. There can be any number of statements inside the function, but they have
to be indented from the def . Function definitions are the second of several compound
statements we will see, all of which have the same pattern:
1. A header line which begins with a keyword and ends with a colon.

23
2. A body consisting of one or more Python statements, each indented the same
amount-the Python style guide recommends 4 spaces-from the header line.

4.1 Functions that require arguments


In Python, an argument is the actual value or data we provide to a function when we
call it. Most function require arguments: the arguments provide for generalization. For
example, if we want to find the absolute value of a number, we have to indicate what
the number is. Python has a built-in function for computing the absolute value:

Some functions take more than one argument. For example, the built-in function pow
takes two arguments, the base and the exponent. Inside the function, the values that
are passed get assigned to variables called parameters.

Another built-in function that takes more than one argument is max.

max can be passed any number of arguments, separated by commas, and will return
the largest value passed. The arguments can be either simple values or expressions. In
the last example, 503 is returned, since it is larger than 33, 125, and 1.

24
4.2 Functions that return values
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.
Below is the standard formula for compound interest, which we will now write as a
fruitful function:

• The return statement is followed by an expression (a in this case). This expres-


sion will be evaluated and returned to the caller as the "fruit" of calling this func-
tion.

• 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 have used the float type converter function to parse the
string and return a float.

• Then enter the arguments for 8% interest, compounded 12 times per year, for 5
years.

• When we run this, we get the output.

25

You might also like