CS1033 Notes a Python 2021Intake (4)
CS1033 Notes a Python 2021Intake (4)
6 - Lists........................................................................................................................................................... 43
6.1 Sequences ........................................................................................................................................43
7 - Numbers ................................................................................................................................................... 46
7.1 Introduction .....................................................................................................................................46
8 - Strings....................................................................................................................................................... 49
8.1 Introduction .....................................................................................................................................49
9 - Functions .................................................................................................................................................. 55
9.1 Defining a Function .........................................................................................................................55
10.6 File and Directory Handling with the "os" Module ...................................................................68
Symbol Description
Flow is used to connect different symbols and indicates the direction of flow
of the algorithm.
Process symbol can be used for a single step or an entire sub process.
The flowchart in Figure 1.1(a) shows the flowchart representation of the algorithm for our example above.
The flowchart in Figure 1.1(b) shows an algorithm to output the summation of the first 100 natural numbers.
Start Start
Num ← 1
Input radius r Total ← 0
a ← PI * r * r Y
Num ≤ 100? e
No
Stop Stop
(a) (b)
The algorithm to output the sum of the first 100 natural numbers in Figure 1.1(b) can be expressed in pseudo-
code format 2 as follows.
BEGIN
Num ← 1
Total ← 0
REPEAT
Total ← Total + Num
Num ← Num + 1
UNTIL Num > 100
OUTPUT Total
END
We will use flowcharts and pseudocode format 2 to express algorithms henceforth. Format 2 of pseudocode
also uses other special constructs such as IF-ELSE-ENDIF, WHILE-ENDWHILE
1
Machine language is the native language of the computer (i.e., what is understood by the CPU hardware).
int a, b, c;
0110100111000010
int main(void) { compile
0101100110100010
a = read_in();
1000100100100001
b = 2 * a /3;
1010111001011010
...
c = 4 * a + 7;
0101000101100100
....
....Figure 1.2: Compiling a high-level language program into machine-language program
Executable machine code produced by a compiler can be saved on disk as a file (referred to as the executable
file) and executed repeatedly as and when necessary (see Figure 1.3). Since the source program is already
compiled, no compilation is needed again unless the source program is modified. The saving on the translation
time is an advantage gained from compiling. Programming languages such as FORTRAN, COBOL, C, C++,
Pascal and Java have compiled implementations.
Source Executable
Compiler
Program Machine Code
Executable
Input Output
Machine Code
Source
Program Interpreter Output
Input
Figure 1.4: Interpretation of a program
Every time the program runs, the interpreter translates high-level language statements into a machine-code
format and executes them. In contrast, a compiler translates the whole program from source code just once.
Thus, the interpretation process (that requires both translating and executing a program, every time) can be
slower than directly executing a previously compiled machine code. Languages like BASIC, Perl, Smalltalk,
Lisp, Python, MATLAB, Ruby have interpreted implementations.
2
Computer architecture describes the internal organization of a computer, the instruction set, instruction format, use of
registers, memory management, communicating with I/O devices, etc.
3
Portable programs can be compiled and executed on machines with different hardware configurations.
Literals are factual data represented in a language. Numeric constants are an uninterrupted sequence of digits
(possibly containing a period). Examples: 123, 10000 and 99.99. Character constants represents a single
Other
>>>
The interactive mode makes it easy to experiment with features of the language, or to test functions during
program development. It is also a handy desk calculator. We will use the interactive mode to introduce and
demonstrate Python language features in this document, when it is more appropriate.
2.2.2 Scripting Mode
The scripting mode is also called the "normal mode" (or the "programming mode") and is non-interactive; in
this we give the Python interpreter a text file containing a Python program (also called a Python script) as
input, on the command-line, as follows:
$ python myprog.py
Here “myprog.py” is the name of the text file that contains the Python program. Python source files are
given the filename extension “.py”.
A Python program can consist of several lines of Python code. A programmer uses a text editor to create and
13 © Department of Computer Science and Engineering
modify files containing the Python source code. We will use this scripting mode more towards the later parts
of this document and use the interactive mode more in the initial sections to discuss the basics.
Here is an example.
>>> b = 57
>>> c = b
>>> c
57
>>> id(b)
1661170464
>>> id(c)
1661170464
>>> b is c
True
We cannot use arbitrary strings as object names (variables). The Python variable naming rules are:
● Must begin with a letter (a - z, A - Z) or underscore (_).
● Other characters can be letters, numbers or _ only.
● Names are case sensitive.
● Reserved words cannot be used as a variable name.
Even when a variable name is “legal” (i.e., follows the rules), it might not be a “good” name. Here are some
generally accepted conventions for designing good names:
● A name should be meaningful: “price” is better than “p”.
● For a multiple-word name, use either the underscore as the delimiter (e.g., temp_var and interest_rate)
or use camelCase capitalization (e.g., tempVar, TempVar, interestRate or InterestRate); pick one
style and use it consistently throughout your program.
● Shorter meaningful names are better than longer ones.
Here are a few examples with integer objects and string objects.
>>> b = 57 >>> p = 'abcxyz'
>>> c = b >>> q = p
>>> c >>> q
57 'abcxyz'
>>> id(b) >>> p is q
1661170464 True
>>> id(c) >>> id(p), id(q)
1661170464 (2491577354984, 2491577354984)
>>> b is c >>> q[2]
True 'c'
>>> b = 60 >>> q = '01234'
>>> b >>> id(p), id(q)
60 (2491577354984, 2491577354760)
>>> c >>> q[2] = 'W'
57 Traceback (most recent call last):
>>> id(b) File "<stdin>", line 1, in <module>
1661170560 TypeError: 'str' object does not support
>>> id(c) item assignment
1661170464
>>> b is c
False
Multiple operators are used in these expressions, which raises the question: In what order should the operations
be evaluated? The standard algebra precedence rules apply in Python: multiplication and division take
precedence over addition and subtraction and, just as in algebra, parentheses are used when we want to
explicitly specify the order in which operations should take place. If all else fails, expressions are evaluated
left- to-right.
All the expressions we have evaluated so far are plain arithmetic expressions involving number values (of
type int or type float), arithmetic operators (such as +, -, /, and *), and parentheses. When you hit the Enter
key, the Python interpreter will read the expression and evaluate it.
The two most frequently used types of number values, int and float, have different properties. For example,
when two int values are added, subtracted, or multiplied, the result is an int value. If at least one float value
appears in such an expression, however, the result is always a float value.
The exponentiation operator ** can be used to compute xy using the expression x**y:
>>> 2**3
8
>>> 2**4
16
To obtain the integer quotient and the integer remainder from an integer division operation, operators // and
%, respectively, are used. The operator // performs floor division (also called integer division), which gives
the integer quotient of the division; that is, the expression a//b returns the integer quotient of the operation
where integer a is divided by integer b. The % operator in expression a%b returns the remainder of the
operation where integer a is divided by integer b. For example:
>>> 14/3
4.666666666666667
>>> 14//3
4
>>> 14%3
2
The second (14//3) expression evaluates to 4 because 4 is the integer part (quotient) of the division. In the
third expression, 14 % 3 evaluates to 2 because 2 is the remainder when 14 is divided by 3.
The Python interpreter has several functions built into it that are always available. For example, the Python
function abs() can be used to compute the absolute value of a number.
>>> abs(-4)
4
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Boolean expressions can be combined using Boolean operators and, or, and not to form larger Boolean
expressions. The and operator applied to two Boolean expressions will evaluate to True if both expressions
evaluate to True; if either expression evaluates to False, then it will evaluate to False:
>>> 2 < 3 and 4 > 5
False
>>> 2 < 3 and True
True
Both expressions illustrate that comparison operators are evaluated before Boolean operators. This is because
comparison operators take precedence over Boolean operators, as we will see later.
The or operator applied to two Boolean expressions evaluates to False only when both expressions are false.
If either one is true or if both are true, then it evaluates to True.
>>> 3 < 4 or 4 < 3
True
>>> 3 < 2 or 2 < 1
False
The not operator is a unary Boolean operator, which means that it is applied to a single Boolean expression.
It evaluates to False if the expression is true or to True if the expression is false.
>>> not (3 < 4)
False
-------------------------------------------------------------------------------------
The above should not be used arbitrarily in programs, e.g., as names of variables. There are also several words
that have special meanings in Python, for e.g., True, False, None.
Operator Description
** Exponentiation (raise to the power)
~ , +, - Complement, unary plus and minus (method names for the last
two are +@ and -@)
*, / , %, // Multiply, divide, modulo and floor division
+,- Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^,| Bitwise exclusive `OR' and regular `OR'
<=, < , >, >= Comparison operators
=, != Equality operators
= , %=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Statement i Yes ? No
Statement i+1
Block A Block B
Statement i+2
No Loop?
Call Subprogram
Subprogram
Yes
Loop Body
We will discuss the selection control structures in Python in the rest of this Chapter and the repetition (loop)
and subprogram control structures in later Chapters.
When using the selection control structure, we specify one or more conditions to be evaluated (or tested) by
the program; this is shown by the decision element with a question mark (“?”) in Figure 4.1(b). Then we
specify one block of statements (Block A) to be selected for execution if the condition is determined to be
true, and another block of statements (Block B) to be selected for execution if the condition is determined to
be false. Note that only one of the blocks, either A or B, will get executed. Further, each of the blocks A and
It starts with the keyword if, followed by an expression that represents a condition, followed by a colon (“:”),
followed finally by a block of statements (also referred to as the if-body). With reference to Figure 4.1(b),
the if-body corresponds to block A whereas block B is empty.
The if-body is indented. Indentation is Python’s way of grouping statements. In interactive mode, you have
to type a tab or space(s) for each indented line. In a Python program, indentation can be done with a text
editor; decent text editors have an auto-indent facility. When a compound statement like an if-structure is
entered interactively, it must be followed by a blank line to indicate completion (since the Interpreter cannot
guess when you have typed the last line). Note that each line within the body must be indented by the same
amount.
The if-body is executed if the expression (also called a conditional expression) is evaluated as “true”. In
Python, like in C, any non-zero integer value is true; zero is false. The expression may also be a string or list
value, in fact any sequence; anything with a non-zero length is true, empty sequences are false.
Consider the following example:
if (marks > 50):
print("You passed the exam!")
If the value of the variable “marks” is greater than 50, the print statement is executed and the string “You
passed the exam!” is displayed on the screen; otherwise the print statement is skipped, and nothing is
displayed. Program 4.1 illustrates the use of this in a Python program.
# Program-4.1
marks = int(input('Enter your marks: '))
if (marks > 50):
print("You passed the exam")
Note that even if the expression “marks > 50” existed without the surrounding parenthesis, it still would be
valid Python syntax. We can use parenthesis for grouping of expressions and for clarity.
Executing Program-4.1 with different inputs will get the following results.
Case 1: Enter marks: 73
You passed the exam!
Let us see how to do this. First the program needs to read the input number and check whether it is greater
than or equal to 1000; if it is the case a 5% discount should be given. Then the final amount needs to be
displayed. We can compute the discount as the body of an if-structure. Program-4.2 is an attempt to implement
this.
Executing Program-4.2 with 1250.25 as the keyboard input will display the following:
Enter your amount: 1250.25
your amount is 1250.25
your final amount is 1187.74
Now test the program with a few other inputs. Detect a bug in the program and correct it.
Note that a colon (“:”) is required after the keyword else. It is followed by a block of statements referred to
as the else-body. With reference to Figure 4.1(b), the if-body corresponds to block A and the else-body
corresponds to block B (or, vice versa). Just like the if-body, the else-body is also indented in a program.
The if-body is executed if the expression is evaluated to true and the else-body is executed otherwise.
Example 4.2: Modify the program for the Example 4.1 so that it displays the message “No discount…” if the
amount is less than 1,000.
We can use an else part for the added requirement.
Let us develop an algorithm first to represent the task to be completed. It can be expressed in pseudocode as
follows,
BEGIN
INPUT amount
final_amount ← 0
IF amount >= 1000
30 © Department of Computer Science and Engineering
discount ← amount * 0.05
final_amount ← amount – discount
ELSE
OUTPUT “No discount”
final_amount ← amount
Num ← Num + 1
ENDIF
OUTPUT amount
OUTPUT final_amount
END
Example 4.3: A car increases its velocity from u ms-1 to v ms-1 within t seconds. Write a program to compute
and display the acceleration, assuming u, v and t are integers and given as input.
The relationship between a, u, v and t can be given as v = u + at . Therefore, acceleration can be found by the
v−u
a=
equation t . Note that users can input any values to the program. Therefore, to find the correct
acceleration t has to be non-zero and positive. So, our program should make sure it only accepts correct inputs.
The following Program-4.4 computes the acceleration given u, v and t. □
# Program-4.4
u = int(input("Enter u (m/s):"))
v = int(input("Enter v (m/s):"))
t = int(input("Enter t (s):"))
if t >=0:
a = float((v-u))/t
print("acceleration is: %.2f m/s^-2" % a)
else:
print("Incorrect time")
Exercise 4.1: Modify Program-4.1 to display the message “You failed!” if marks is less than or equal to 50.
Just like the if-body and the else-body, an elif-body is also indented.
If the “expression_1” is evaluated to true, the if-body is executed and rest (the corresponding elif and
else parts, if any) will be skipped. Otherwise, the “expression_2” is evaluated; if it is true, then the
corresponding elif-body is executed and rest (the remaining elif and else parts, if any) will be skipped.
Otherwise, the “expression_3” is evaluated and so on. If none of the expressions is true, the else-body is
executed.
The if...elif structure is a substitute for the “switch-case” structure in some other languages such as C.
>>> 4 + rate*3
Traceback (most recent call last):
>>> '3' + 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
The last line of the error message in each example above indicates what happened. Exceptions come in
different types, and the exception type is printed as part of the message: the types in the three examples are
ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of
the built-in exception that occurred. This is true for all built-in exceptions. Standard exception names are built-
in identifiers (not reserved keywords).
An exception is an event that disrupts the normal flow of the program execution. In general, when Python
encounters a situation that it can't cope with, it raises an exception. An exception is a Python object that
represents an error.
Python makes it possible to handle unexpected errors in our Python programs. This is important as a debugging
tool and to improve the quality of our programs.
If you have some code segment that may raise an exception, you can make your program to handle (“catch”)
it by placing the suspicious code segment in a try...except construct. This construct has a try: clause
followed by one or more except: clauses. Each except clause has a block of code which handles one
exception as elegantly as possible. The try...except construct has an optional else clause, which, when
present, must follow all except clauses. It is useful for code that must be executed if the try clause does not
raise an exception. Here is the structure of a simple try....except...else construct:
try:
Do some operation that may raise an exception;
......................
except Exception_1:
If there is Exception_1, then execute this block.
......................
except Exception_2:
If there is Exception_2, then execute this block.
......................
else:
If there is no exception then execute this block.
......................
Here is a simple example, which opens a file to write some content in it.
#!/usr/bin/python
# Program-4.5
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t open file or write data.")
else:
print("Finished writing the file successfully.")
fh.close()
In addition to using except clauses and an else clause in a try construct, you can also use the finally
clause. Note that the finally clause is optional and intended to define clean-up actions that must be executed
under all circumstances. A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not. When an exception has occurred in the try clause and has not been handled
by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally
clause has been executed. The finally clause is also executed “on the way out” when any other clause of
The block of statements executed repeatedly is called the loop body. The loop body is indented.
If the sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned
to the iterating variable iterating_var and the loop body is executed. This concludes one iteration of the
loop. Next the second iteration of the loop body is executed after the second item is assigned to the iterating
variable iterating_var. Like this, the loop body is executed repeatedly, with a unique item in the list
assigned to iterating_var in each iteration, until the entire sequence is exhausted.
Here is an example.
#!/usr/bin/python
# Program-5.1
for counter in range(1, 6):
print("This is a loop: counter = ", counter)
Execution of program-5.1 displays the following.
This is a loop: counter = 1
This is a loop: counter = 2
This is a loop: counter = 3
This is a loop: counter = 4
This is a loop: counter = 5
The range() function: If we do need to iterate over a sequence of numbers, the built-in function range()
comes in handy. It generates range objects containing arithmetic progressions. Implementation of range( ) is
as either range(stop) or range(start, stop[, step]). See how it is useful in program-5.1. Here are four interactive
examples.
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(-10, -100, -30))
[-10, -40, -70]
The given end point is never part of the generated list; range(10) generates a list of 10 values, 0,1,2,…,9 , i.e.,
the legal indices for items of a sequence of length 10 (first example). It is possible to let the range start at
another number (second example above), or to specify a different increment (even negative), which is called
the step., with a third argument for the range() function, as seen in the last two examples above.
To iterate over the indices of a list or sequence (which will be covered in the next Chapter) in a for loop, you
can combine range() and len() functions as follows:
Example 5.1: Write a program to compute the sum of all even numbers up to 100, inclusive.
For this problem, the first even number is 0 and the last even number is 100. By adding 2 to an even number
the next even number can be found. Therefore we can have a loop with a counter incremented by 2 in each
iteration. First, we can express the algorithm as shown below. Next, the Program-5.2 is an implementation of
this. □
The algorithm in pseudocode.
BEGIN
sum_total ← 0
FOR counter = 0 to 100 STEP 2
sum_total ← sum_total + counter
ENDFOR
OUTPUT sum_total
END
The Python program that implements the above algorithm is as follows.
#!/usr/bin/python
# Program-5.2
sum_total = 0
for counter in range(0,101,2):
sum_total += counter
print('total = ', sum_total)
Exercise 5.2 : Modify Program-5.2 such that it computes the sum of all the odd numbers up to 100.
Exercise 5.3 : Write a program to compute the sum of all integers form 1 to 100.
Exercise 5.4 : Write a program to compute the factorial of any given positive integer < 100.
Example 5.2 : Write a program to compute the sum of all integers between any given two numbers.
In this program both inputs should be given from the keyboard. Therefore at the time of program development
both initial value and the final value are not known. First, we develop and express the algorithm. Next, we
obtain the Python program using the algorithm as the basis. □
The algorithm in pseudocode.
BEGIN
INPUT num1, num2
sum ← 0
FOR N = num1 to num2
sum ← sum + N
ENDFOR
OUTPUT sum
END
Exercise 5.5 : Can the loop body of a for loop never get executed? Explain using program-5.3.
while expression:
statement(s)
The block of statements executed repeatedly is the loop body, which is indented, as in the for loop.
The condition to execute the loop body is considered true if the expression is true or it is any non-zero value.
The loop iterates while the condition is true. When the condition becomes false, program control passes to the
line immediately following the loop body.
Note that, in Python, all statements indented by the same number of character spaces after a programming
construct are part of a single block of code. Python uses indentation as its method of grouping statements.
Note that the while loop might not ever run. When the condition is tested and the result is false, the loop body
will be skipped and the first statement after the while loop will be executed.
Consider the following example algorithm and the subsequent Python program based on it.
BEGIN
INPUT num
WHILE num ≠ 0
OUTPUT "Hello World!"
num ← num - 1
ENDWHILE
END
The following Python program implements the above algorithm.
#!/usr/bin/python
# Program-5.4
num = int(input("Enter Number of time to repeat: "))
while (num != 0) :
print("Hello World!")
num = num - 1
Execution of Program-5.4 with 5 as the input will display the following.
Enter number of times to repeat: 5
Hello World!
38 © Department of Computer Science and Engineering
Hello World!
Hello World!
Hello World!
Hello World!
Note however that the above does not happen when the loop is terminated by a break statement (to be
discussed later). That is, a loop’s else clause is executed when no break occurs.
The following example illustrates the combination of an else clause with a while loop that prints a number
if it is less than 5. When the loop condition becomes false, the else clause gets executed.
#!/usr/bin/python
# Program-5.5
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")
When the above code is executed, it produces the following output.
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Note that you can put any type of loop inside any other type of loop. For example, a for loop can be inside a
for loop.
Example 5.2 : The following program uses a nested loop to find the prime numbers from 2 to 100.
Exercise 5.5 – Write a Python program using two loops (nested) to display the following pattern:
*
**
***
****
*****
******
In program-5.9, 5 is divided by all the integers from -5 to +5. However, we want to avoid dividing by 0. In
Program-5.9, when “i” is 0 (when the if condition is TRUE) the continue keyword is used to skip the rest
of the loop body in that iteration; this will skip the print statement which has the division by 0.
Exercise 6.1 - Write a program that can find all the even numbers in a list of numbers and then print them.
Exercise 6.2 - Write a program that will multiply two lists and generate a 3rd list. You need to also print all
three lists.
7.1 Introduction
Number data types store numeric values. They are immutable, which means once created their value never
changes. This means, changing the value of a numeric data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del
statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
Python supports three different numerical types:
● int (signed integers): often called just integers or ints, are positive or negative whole numbers with no
decimal point. There is no limit for the length of integer literals apart from what can be stored in available
memory.
● float (floating point, real values): or floats, represent real numbers and are written with a decimal point
dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating
the power of 10 (2.5e2 = 2.5 x 102 = 250).
● complex (complex numbers): are of the form a + bJ, where a and b are floats and J (or j) represents the
square root of -1 (which is an imaginary number). a is the real part of the number, and b is the imaginary
part. Complex numbers are not used much in Python programming.
7.2 Examples
Here are some examples:
10 0.0 3.14j
A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is
the real part and b is the imaginary part of the complex number.
8.1 Introduction
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in
quotes. Python treats single quotes ' ' the same as double quotes " ".
Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"
Strings can be concatenated (glued together) with the + operator and repeated with *. This is another way to
create new strings. For example:
Two string literals next to each other are automatically concatenated. The first line above could also have been
written as the word = 'Help' 'A'.
However, creating a new string with the combined content is easy and efficient, as shown below.
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
Strings are immutable does not mean we cannot assign a new (separate) string “xyz” to an existing variable
which is now assigned a string “pqr”. That means, we can "update" an existing variable, which now has a
string value, by (re)assigning it another string. The new value can be related to its previous value or to a
completely different string altogether.
The following explains this.
>>> str1 = "pqr"
>>> str2 = str1
>>> str2
'pqr'
>>> str1[0]="x"
\xnn
Hexadecimal notation, where n is in the range 0.9, a.f,
or A.F
+
a + b will give
Concatenation - Adds values on either side of the operator
HelloPython
*
Repetition - Creates new strings, concatenating multiple copies of a*2 will give -
the same string HelloHello
[ ] Slice - Gives the character from the given index a[1] will give e
[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given string H in a will give 1
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
#
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or
'0X', depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n.
m is the minimum total width and n is the number of digits to
display after the decimal point (if appl.)
Here is the same string formatted using f-strings. Notice the leading ‘f’ character in each string, which is used
to denote that this is a formatted string.
Refer the official documentation on Formatted String Literals for further details.
Function Function
call
As you already know, Python gives you many built-in functions like print( ), etc. but you can also create your
own functions which are called user-defined functions.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior; thus when invoking (calling) the function you need to list
them in the same order that they were defined.
Here is an example Python function that takes a string as input parameter and prints it on screen.
def printme( string ):
#"This prints a passed string into this function"
print(string)
return
Example 9.1 : Write a program to compute the circumference and area of a circle given its radius. Implement
computation of circumference and area as separate functions.
#!/usr/bin/python
# Program-9.2
pi = 3.141
def area(r):
return (pi*r*r)
def circumference(r):
return (2*pi*r)
radius = 0.0
radius = float(input("Enter radius: "))
print("Area : ", area(radius))
print("Circumference : ", circumference(radius))
The name inlist is a reference (is bound to) in the scope of the function changeme to the list object
referenced by name mylist in the program scope. We change the list object (lists are mutable in Python) in
the function; it will be visible outside the function. The following output will result:
The following example demonstrates another point. In the function call, the argument mylist is the name
bound to a list object; it is being passed-by-object-reference to the function (therefore the list object is bound
to the name inlist within the function scope at the time of function call).
#!/usr/bin/python
# Program-9.4
Changing inlist within the function does not affect mylist. The assignment inlist = [1,2,3,4] binds
the name inlist to a new (different) list object and that does not change the original list object bound to
mylist outside the function. The program would produce the following output.
Values before calling the function: [10, 20, 30]
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Exercise 9.1 What would be the output of the following code segment: 10 , 100 or 110 ?
def passValue( a ):
a=100
return
x=10
passValue(x)
print(x)
● Local variables
a = 5
def swap1(x,y):
z=x
x=y
y=z
return None
def swap2(x):
global a
z=x
x=a
a=z
return None
b =10
c =15
print("Value before 1st function a = ", a," b = ",b," c = ",c)
swap1(b,c)
print("Value after 1st function a = ", a," b = ",b," c = ",c)
swap2(b)
print("Value after 2nd function a = ", a," b = ",b," c = ",c)
print("Test")
Exercise 9.2 Write a function that can find and return all the even numbers in a list of numbers and return it
as a list. For example, if [2,4,6,5,3,8,1] is the input, the output will be [2,4,6,8].
#!/usr/bin/python
print("Python is really a great language,", "isn't it?");
This would produce the following result on your standard output (display screen):
Python is really a great language, isn't it?
The input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing
newline). Here is an example:
#!/usr/bin/python
string = input("Enter your input: ")
print("Received input is : ", string)
This would produce the following result against the entered input.
Enter your input: 10
Received input is : 10
The parameters (arguments) used with the open() function are as follows:
● file_name: A string value that contains the name of the file that you want to access.
● access_mode: This determines the mode in which the file has to be opened, for e.g., read, write or
append. A complete list of possible mode values are given below in a table. This is an optional parameter
and the default file access mode is read (r).
● buffering: If set to 0, no buffering will take place. If the value is 1, line buffering will be performed
while accessing a file. If the value is an integer greater than 1, then buffering action will be performed
with the indicated buffer size. If negative, the buffer size is the system default (default behavior). This is
an optional parameter.
Mode Description
r
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer will be at the beginning of
the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer will be at
the beginning of the file.
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for both writing and reading in binary format. Overwrites the existing
wb+ file if the file exists. If the file does not exist, creates a new file for reading and
writing.
Opens a file for appending. The file pointer is at the end of the file if the file exists.
a That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
Attribute Description
f.closed Returns True if the file f is closed, False otherwise.
f.mode Returns the access mode with which file f was opened.
f.name Returns the name of the file f.
Here is an example program that uses these (it requires a file named "foo.txt" to exist).
#!/usr/bin/python
# Program-10.1
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
print("File closed: ", fo.closed)
print("Opening mode : ", fo.mode)
f.close()
Here is an example.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
f.read([count])
Here, the optional argument count is the maximum number of bytes to be read. This method starts reading
from the beginning of the file and at most count bytes are read and returned. If count is omitted or
negative, the entire contents of the file will be read and returned.
The f.readline() method reads a single line from a file f; a newline character ('\n') is left at the end of
the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. If f.readline()
returns an empty string, the end of the file f has been reached, while a blank line is represented by '\n', a
string containing only a single newline. As in the f.read() method, this method too has an optional
argument count, which sets a maximum byte count (including the trailing newline) to read; as a result an
incomplete line may be returned.
For reading lines from a file, we can loop over the file object. This is memory efficient, fast, and leads to
simple code. Here is an example in which a file is read and its content output in a loop, a line in each iteration.
#!/usr/bin/python
# Program-10.2
fo = open("foo.txt", "r")
for line in fo:
print(line,end=’’)
It is a good practice to use the with keyword when dealing with file objects. This has the advantage that the
file is properly closed when the with block finishes, even if an exception is raised on the way. It is also much
shorter than writing equivalent try-finally blocks.
The following example program-10.3 shows how the previous program-10.2 can be re-written using the with
keyword.
#!/usr/bin/python
# Program-10.3
f.write(string)
Here, the argument ‘string’ is the string content to be written into the opened file f.
Here is an example.
#!/usr/bin/python
# Program-10.4
#
fo = open("foobar.txt", "w")
fo.write( "Python is a great language.\nYeah I love it!\n")
fo.close()
The above would create the foobar.txt file, write the given content in that file and finally close that file.
If you subsequently open this file, you would see the following content.
Python is a great language.
Yeah I love it!
# Open file
fo = open("foobar.txt", "r+")
string = fo.read(10)
print("Read string is : ", string)
import os
String Functions
Python includes the following built-in functions to manipulate strings:
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
The fractional and integer parts of x in a two-item tuple. Both parts have
modf(x)
the same sign as x. The integer part is returned as a float.
x rounded to n digits from the decimal point. Python rounds away from
round(x [,n])
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
Function Description
choice(seq) A random item from a list, tuple, or string.
randrange ([start,] stop [,step]) A randomly selected element from range(start, stop, step)
A random float r, such that 0 is less than or equal to r and r is
random()
less than 1
Sets the integer starting value used in generating random
seed([x]) numbers. Call this function before calling any other random
module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns None.
A random float r, such that x is less than or equal to r and r is
uniform(x, y)
less than y
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Constants Description
math.pi The mathematical constant pi=3.141592..., to available precision.
math.e The mathematical constant e= 2.718281..., to available precision.