0% found this document useful (0 votes)
16 views32 pages

PY Mod 1

The document outlines the curriculum for a Python Programming course, detailing modules on Python features, functions, object-oriented programming, and database programming. It includes a laboratory component with practical experiments and references to core and additional texts. The document also provides an introduction to Python, its advantages, features, and basic syntax, including identifiers, keywords, variables, comments, and input/output methods.

Uploaded by

colade5740
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)
16 views32 pages

PY Mod 1

The document outlines the curriculum for a Python Programming course, detailing modules on Python features, functions, object-oriented programming, and database programming. It includes a laboratory component with practical experiments and references to core and additional texts. The document also provides an introduction to Python, its advantages, features, and basic syntax, including identifiers, keywords, variables, comments, and input/output methods.

Uploaded by

colade5740
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
You are on page 1/ 32

S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

CS1541: PYTHON PROGRAMMING

Module I: Introduction to Python - Features of Python, Identifiers, Reserved


Keywords, Variables, Comments in Python, Input, Output and Import Functions,
Operators; Data Types and Operations - int, float, complex, Strings, List, Tuple, Set,
Dictionary, Mutable and Immutable Objects, Data Type Conversion; Flow control -
Decision Making, Loops-for, range() while, break, continue, pass;

Module II: Functions- Definition, calling, arguments, anonymous function, recursion,


return; Modules & Packages - Built-in Modules, Creating Modules, import statement,
Locating, modules, Namespaces and Scope, dir (), reload (), Packages in Python; File
Handling- open, close, write, read, methods, rename, delete, directories;

Module III: Object oriented programming- class, object, method, attribute,


destructor, encapsulation, data hiding; Exception handling- built in exceptions,
Handling, Exception with arguments, Raising and User defined exceptions, Assertions
in Python; Regular expressions – match, search, replace, patterns.

Module IV: Database Programming- Connection, Create, insert, update, delete,


commit, rollback, disconnection, exceptions; Iterators- Data type supports iterators;
CGI Programming- HTTP Header, Env variables, Forms, Radio button, Dropdown box,
check box, text area, cookies, uploading file.

CORE TEXT

1. Jeeva Jose, “Taming PYTHON By Programming”, Khanna Publications, 2017

ADDITIONAL REFERENCES

1. Allen B. Downey,” Think Python- How to think like a computer scientist”, Second
Edition, O’Reilly, 2016.

2. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An


Introduction to Computer Science using Python 3”, Second edition, Pragmatic
Programmers, LLC,

1 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

CS1544: PYTHON PROGRAMMING LAB

The laboratory work will consist of 10‐15 Experiments

PART A

• To write, test, and debug simple Python programs.


• To implement Python programs with conditionals and loops. (square root, gcd,
exponentiation, sum of an array of numbers, linear search, binary search, bubble
sort, insertion sort, selection sort etc.)
• Use functions for structuring Python programs.
• Represent compound data using Python lists, tuples, dictionaries.

PART B

• Read and write data from/to files in Python.


• Programs to demonstrate creating and handling of modules and packages
• Programs involving a variety of Exception Handling situations
• Programs involving Database manipulation
• CGI programming

2 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Python : Introduction
Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express their
concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently. It also performs automatic memory management.

There are two major Python versions: Python 2 and Python 3. Both are quite different.
Reason for increasing popularity
1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in comparison to languages
such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented, imperative and
functional programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
Advantages :
1) Presence of third-party modules
2) Extensive support libraries (NumPy for numerical calculations, Pandas for data analytics etc)
3) Open source and community development
4) Easy to learn
5) User-friendly data structures
6) High-level language
7) Dynamically typed language (No need to mention data type, based on value assigned it takes
data type)
8) Object-oriented language
9) Portable and Interactive
10) Portable across Operating systems
Python: FEATURES
Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form called byte codes which
is then translated into native language of specific computer to run it.

3 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

• No need to worry about linking and loading with libraries, etc.


Platform Independent
• Python programs can be developed and executed on multiple operating system platforms.
• Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source: Redistributable
High-level Language
• In Python, no need to take care about low-level details such as managing the memory used by
the program.
Simple
• Closer to English language
• Easy to Learn
• More emphasis on the solution to the problem rather than the syntax
Embeddable
• Python can be used within C/C++ program to give scripting capabilities for the users.
Robust:
• Exceptional handling features
• Memory management techniques in built
Rich Library Support

The Python Standard Library is very vast. It can help do various things involving regular
expressions, documentation generation, unit testing, threading, databases, web browsers, CGI,
email, XML, HTML, WAV files, cryptography, GUI and many more. Besides the standard library,
there are various other high-quality libraries such as the Python Imaging Library which is an
amazingly simple image manipulation library.

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore ( _ ) followed by zero or more
letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Man and man are two different identifiers in Python.

Here are naming conventions for Python identifiers −


• Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier is
private.
4 Naipunnya School of Management, Cherthala [Jithin Babu]
S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Starting an identifier with two leading underscores indicates a strongly private identifier.

If the identifier also ends with two trailing underscores, the identifier is a language-defined

special name.
Reserved Words

Keywords: Keywords are words which are responsible to perform some specific tasks or the
words which represent some specific functionality. The following table lists some keywords.
These are reserved words and you cannot use them as constant or variable or any other identifier
names. All the Python keywords contain lowercase letters only.
and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda yield


Python Variables
Python is not “statically typed”. We do not need to declare variables before using them, or declare
their type. A variable is created the moment we first assign a value to it.
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
Comments

Python developers often make use of the comment system as, without the use of it, things can get
real confusing, real fast. Comments are the useful information that the developers provide to make
the reader understand the source code. It explains the logic or a part of it used in the code.
Comments are usually helpful to someone maintaining or enhancing your code when you are no
longer around to answer questions about it. These are often cited as a useful programming

5 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

convention that does not take part in the output of the program but improves the readability of the
whole program. There are two types of comment in Python:
Single line comments: Python single line comment starts with hashtag symbol with no white
spaces (#) and lasts till the end of the line. If the comment exceeds one line, then put a hashtag on
the next line and continue the comment. Python’s single line comments are proved useful for
supplying short explanations for variables, function declarations, and expressions.
Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a
delimiter (""") on each end of the comment. Again, there should be no white space between
delimiter ("""). They are useful when the comment text does not fit into one line; therefore, needs
to span across lines. Multi-line comments or paragraphs serve as documentation for others reading
your code.

Taking input in Python

Python provides us with two inbuilt functions to read the input from the keyboard.
• raw_input ( prompt )
• input ( prompt ) raw_input ( ) : This function works in older version (like Python 2.x). This
function takes exactly what is typed from the keyboard, convert it to string and then return
it to the variable in which we want to store.
input ( ) : This function first takes the input from the user and then evaluates the expression, which
means Python automatically identifies whether user entered a string or a number or list. If the
input provided is not correct then either syntax error or exception is raised by python.

How the input function works in Python :


• When input() function executes program flow will be stopped until the user has given an
input.
• The text or message display on the output screen to ask a user to enter input value is optional
i.e. the prompt, will be printed on the screen is optional.
• Whatever you enter as input, input function converts it into a string. if you enter an integer
value still input() function convert it into a string. You need to explicitly convert it into an
integer in your code using typecasting.

Python Import

When our program grows bigger, it is a good idea to break it into different modules.

6 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
>>> from math import pi
>>> pi
3.141592653589793
Output using print() function
The simplest way to produce output is using the print() function where you can pass zero

or more expressions separated by commas. This function converts the expressions you pass into a

string before writing to the screen. The syntax of the print() function is print(*objects, sep=' ',

end='\n', file=sys.stdout, flush=False)

Here, objects are the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen). Here
are examples to illustrate this.

Rerurns : it returns output to the screen


print() function in Python(2.x)

# One object is passed print


"output"

# Four objects are passed


print "Output", "using", "print", "function"

l = [1, 2, 3, 4, 5] #
printing a list
print l

7 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

print() function in Python(3.x)

# One object is passed print("Python")

x=5
# Two objects are passed
print("x =", x)

# code for disabling the softspace feature


print('A', 'B', 'C', sep ='*')

# using end argument print("Python",


end = '@') print("End Argument")
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y)) The
value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in which it is printed
by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))


Hello John, Goodmorning
We can even format strings like the old sprintf() style used in C programming language. We use the
% operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x) The
value of x is 12.35
>>> print('The value of x is %3.4f' %x) The
value of x is 12.3457

8 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

More on using print


Say you want to print a specific string (a sequence of characters such as letters, punctuation marks,
numbers, and letters) N number of times. The (asterisk) * operator performs repetition on strings.
You can print "5" six times. Inside the print parentheses, put a€œ5a€ followed by * and the number
of times you want a€œ5a€ repeated.

>>> print("5"*6)
555555
You can separate the output using the comma delimiter. By default, this adds a space between the
output items. For example, the sequence of numbers 5,6,7 separated by comma , gets printed with
a space between one number and the next.

>>> print(5,6,7)
567
To change the output to what you want, use the keyword arguments sep and end to print ( ). When
separating the output with a comma delimiter, you can also define the separation format using the
a€œsepa€ keyword.

>>> print('LOVE', 30, 82.2)


LOVE 30 82.2
>>> print('LOVE', 30, 82.2, sep=',')
'LOVE', 30, 82.2
By default, print goes to a new line at the end. You can change this by using the keyword a€œenda€
as shown in the example below.

>>> print('LOVE', 30, 82.2, sep=',', end='!!\n') 'LOVE',


30, 82.2!!
For example, you can print the letters in the word "python" and all the letters will come in a new
line.
>>> for i in "python":
... print(i)
...
p
y
t
h
o
n

9 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

You can change this default implementation. You can have a colon : between the letters instead of
a new line.

>>> for i in "python":


... print(i, end=":")
...
p:y:t:h:o:n:

Printing the result of a calculation


Say you can assign the number 7 to a variable population and if you write the logic population * 7
inside the parentheses of print, it will just do the calculation up front and print the result.

>>> population = 7
>>> print("Population in 2050: ", population * 1.28)
# making the calculation in place
Population in 2050: 8.96
Basic Operators in Python
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.

For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.

Python divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators

10 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Arithmetic operators: Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication and division.
Operator Description Syntax
+ Addition: adds two operands x+y
- Subtraction: subtracts two operands x-y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when first operand is divided by x % y
the second

# Examples of Arithmetic Operator


a=9
b=4

# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Output:
13
5
36
2.25 2
1
Relational Operators: Relational operators compares the values. It either returns True or
False according to the condition.

11 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Operator Description Syntax


> Greater than: True if left operand is greater than the right x>y
< Less than: True if left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to: True if left operand is greater than or equal x >= y
to the right

<= Less than or equal to: True if left operand is less than or equal to the x <= y
right

# Examples of Relational Operators


a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)

Output:
False
True
False
True
False
True
Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT
operations.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x

12 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

# Examples of Logical Operator


a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
# Print not a is False
print(not a)
Output:
False
True
False
• Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

# Examples of Bitwise operators


a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Output:
0
14
-11
14
2
40

13 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

• Assignment operators: Assignment operators are used to assign values to the variables.
Operator Description Syntax

= Assign value of right side of expression to left side x = y + z


operand

+= Add AND: Add right side operand with left side operand a+=b a=a+b
and then assign to left operand

-= Subtract AND: Subtract right operand from left operand a-=b a=a-b
and then assign to left operand

*= Multiply AND: Multiply right operand with left operand a*=b a=a*b
and then assign to left operand

/= Divide AND: Divide left operand with right operand and a/=b a=a/b
then assign to left operand

%= Modulus AND: Takes modulus using left and right a%=b a=a%b
operands and assign result to left operand

//= Divide(floor) AND: Divide left operand with right operand a//=b
and then assign the value(floor) to left operand a=a//b

**= Exponent AND: Calculate exponent(raise power) value a**=b


using operands and assign value to left operand a=a**b

&= Performs Bitwise AND on operands and assign value to a&=b


left operand a=a&b

|= Performs Bitwise OR on operands and assign value to left a|=b


operand a=a|b

^= Performs Bitwise xOR on operands and assign value to left a^=b


operand a=a^b

>>= Performs Bitwise right shift on operands and assign value a>>=b
to left operand a=a>>b

<<= Performs Bitwise left shift on operands and assign value a <<= b a=
to left operand a << b

● Special operators: There are some special type of operators like-


Identity operators : is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.

14 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

is True if the operands are identical


is not True if the operands are not identical

# Examples of Identity operators


a1 = 3
b1 = 3
a2 = 'PythonOperator'
b2 = 'PythonOperator'
a3 = [1,2,3]
b3 = [1,2,3]

print(a1 is not b1)

print(a2 is b2)
# Output is False, since lists are mutable.
print(a3 is b3)
Output: False
True
False
o Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in
a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
# Examples of Membership operator
x = 'Operators in Python'
y = {3:'a',4:'b'}

print('G' in x) print('python'
not in x) print('Python' not
in x) print(3 in y)
print('b' in y)

Output:
False
True
False
True
False

15 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Python Data Types

In Python, the data type is set when you assign a value to a variable:

Example Datatype
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these classes.

Following are the standard or built-in data type of python:

● Numeric ● Sequence Type ● Boolean ● Set ● Dictionary

Numeric

In Python, numeric data type represent the data which has numeric value. Numeric value
can be interger, floating number or even complex numbers. These values arre defined as int, float
and complex class in Python.

● Intergers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an interger
value can be.

16 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

● Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
● Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j

Note – type() function is used to determine the type of data type.

Sequence Type

In Python, sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are several sequence
types in Python –

● String

● List

● Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote or triple quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.

Creating a string
Strings in Python can be created using single quotes or double quotes or even triple quotes.

Accessing elements of string


In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back of the
String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.

While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.

Deleting/Updating from a String


In Python, Updation or deletion of characters from a String is not allowed. This will cause
an error because item assignment or item deletion from a String is not supported. This is because
Strings are immutable, hence elements of a String cannot be changed once it has been assigned.
Only new strings can be reassigned to the same name.

17 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

2) List

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it the most powerful tool in Python. A single list may contain DataTypes like
Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after
their creation. List in Python are ordered and have a definite count. The elements in a list are
indexed according to a definite sequence and the indexing of a list is done with 0 being the first
index. Each element in the list has its definite place in the list, which allows duplicating of elements
in the list, with each element having its own distinct place and credibility. It is represented by list
class.

Lists in Python can be created by just placing the sequence inside the square brackets[].
Unlike Sets, list doesn’t need a built-in function for creation of list.

Adding Elements to a List


Elements can be added to the List by using built-in append() function. Only one element at
a time can be added to the list by using append() method. For addition of element at the desired
position, insert() method is used. Other than append() and insert() methods, there’s one more
method for Addition of elements, extend(), this method is used to add multiple elements at the
same time at the end of the list.

Accessing elements from the List


In order to access the list items refer to the index number.Use the index operator [ ] to
access an item in a list. The index must be an integer. Nested list is accessed using nested indexing.
In Python, negative sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative
indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item
etc.

Removing Elements from the List


Elements can be removed from the List by using built-in remove() function but an Error
arises if element doesn’t exist in the set. Pop() function can also be used to remove and return an
element from the set, but by default it removes only the last element of the set, to remove element
from a specific position of the List, index of the element is passed as an argument to the pop()
method.

Note – Remove method in List will only remove the first occurrence of the searched element.

18 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

3) Tuple

Tuple is an ordered collection of Python objects much like a list. The sequence of values
stored in a tuple can be of any type, and they are indexed by integers. The important difference
between a list and a tuple is that tuples are immutable. Also, Tuples are hashable whereas lists are
not. It is represented by tuple class.

Creating a Tuple
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a
single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there
must be a trailing ‘comma’ to make it a tuple.

Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Accessing element of a tuple
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuple are accessed using nested
indexing.

Deleting/updating elements of tuple


In python, deletion or Updation of a tuple is not allowed. This will cause an error because
updating or deleting from a tuple is not supported. This is because tuples are immutable, hence
elements of a tuple cannot be changed once it has been assigned. Only new tuples can be
reassigned to the same name.

Boolean

Data type with one of the two built-in values, True or False. Boolean objects that are equal
to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be
evaluated in Boolean context as well and determined to be true or false. It is denoted by the class
bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.

Set

In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various

19 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.

Creating a set
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’. A set contains only unique
elements but at the time of set creation, multiple duplicate values can also be passed. The order of
elements in a set is undefined and is unchangeable. Type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.

Adding Elements to a Set

Elements can be added to the Set by using built-in add() function. Only one element at a
time can be added to the set by using add() method. For addition of two or more elements Update()
method is used.
Accessing a Set

Set items cannot be accessed by referring to an index, since sets are unordered the items has no
index. But you can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.

Removing elements from a set

Elements can be removed from the Set by using built-in remove() function but a KeyError arises
if element doesn’t exist in the set. To remove elements from a set without KeyError, use discard().
Pop() function can also be used to remove and return an element from the set, but it removes only
the last element of the set. To remove all the elements from the set, clear() function is used.

Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like
a map, which unlike other Data Types that hold only single value as an element, Dictionary holds
key:value pair. Key-value is provided in the dictionary to make it more optimized. Each keyvalue
pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

Creating a dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and
can be duplicated, whereas keys can’t be repeated and must be immutable.

20 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.

Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.

Adding elements to a Dictionary


In Python Dictionary, Addition of elements can be done in multiple ways. One value at a
time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.

Note – While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.

Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. There is also a method called get() that will also help in accessing the element
from a dictionary.

Removing Elements from Dictionary


In Python Dictionary, deletion of keys can be done by using the del keyword. Using del
keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other
functions like pop() and popitem() can also be used for deleting specific values and arbitrary
values from a Dictionary. All the items from a dictionary can be deleted at once by using clear()
method.

Mutable vs Immutable Objects in Python

Every variable in python holds an instance of an object. There are two types of objects in
python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a
unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards.
However, it’s state can be changed if it is a mutable object.

To summarise the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.

Immutable Objects : These are of in-built types like int, float, bool, string, unicode,
tuple. In simple words, an immutable object can’t be changed after it is created.

21 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.

1. Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
2. Use of mutable objects is recommended when there is a need to change the size or content of
the object.
3. Exception : However, there is an exception in immutability as well. We know that tuple in
python is immutable. But the tuple consists of a sequence of names with unchangeable
bindings to objects.

Consider a tuple, the tuple consists of a string and a list. Strings are immutable so we can’t change
its value. But the contents of the list can change. The tuple itself isn’t mutable but contain items
that are mutable.
Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming. This article is aimed at providing the
information about certain conversion functions.

1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
s = "10010"
# printing string converting to int base 2
c = int(s,2)
2. float() : This function is used to convert any data type to a floating point number
e =float(s)

3. ord() : This function is used to convert a character to integer.


c =ord(s)
4. hex() : This function is to convert integer to hexadecimal string.
c =hex(56)
5. oct() : This function is to convert integer to octal string.
c =oct(56)
6. tuple() : This function is used to convert to a tuple.
s = 'python'
c = tuple(s)
7. set() : This function returns the type after converting to set.

22 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

c =set(s)
8. list() : This function is used to convert any data type to a list type.
c =list(s)
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
tup = (('a', 1) ,('f', 2), ('g', 3))
c =dict(tup)

10. str() : Used to convert integer into a string.


a=1
c =str(a)

11. complex(real,imag) : : This function converts real numbers to complex(real,imag)


number.
c =complex(1,2)

Decision Making in Python (if , if..else, Nested if, if-elif)


Decision making statements in programming languages decides the direction of flow of program execution.
Decision making statements available in python are:
· if statement
· if..else statements
· nested if statements
· if-elif ladder
if statement
if statement is the most simple decision making statement. It is used to
decide whether a certain statement or block of statements will be
executed or not
i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:
if condition:
# Statements to execute if condition is true
Here, condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block
of statements below it otherwise not. We can use condition with bracket
‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block
under an if statement will be identified as shown in the below example:

23 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

# python program to illustrate If statement


i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not executed.
if- else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the
else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:
if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false
# python program to illustrate If else statement
i = 20
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is
false after call the statement which is not in block(without spaces).
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.

24 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement Will only be executed if statement above it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top down. As soon
as one of the conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example:-
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):

25 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

print ("i is 15")


elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20

Loops in python
Python programming language provides following types of loops to handle looping requirements. Python
provides three ways for executing the loops. While all the ways provide similar basic functionality, they
differ in their syntax and condition checking time.
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a condition is
satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax :
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello World")
Output:
Hello World
Hello World
Hello World
Using else statement with while loops: As discussed above, while loop executes the block until a condition
is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The
else clause is only executed when your while condition becomes false. If you break out of the loop, or if an
exception is raised, it won’t be executed.
If else like this:
if condition:
# execute these statements
else:
# execute these statements

26 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

and while loop like this are similar


while condition:
# execute these statements
else:
# execute these statements
#Python program to illustrate combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello World")
else:
print("In Else Block")
Output:
Hello World
Hello World
Hello World
In Else Block
Single statement while block: Just like the if block, if the while block consists of a single statement the we
can declare the entire loop in a single line as shown below:
For in Loop
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python,
there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to ‘for each’ loop in
other languages. Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
# Python program to illustrate Iterating over a list
print("List Iteration")
l = ["aaa", "bbb", "ccc"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("xxx", "yyy", "zzz")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "abcd"
for i in s :

27 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Output:
List Iteration
aaa
bbb
ccc
Tuple Iteration
xxx
yyy
zzz
String Iteration
a
b
c
d
Dictionary Iteration
xyz 123
abc 345
Iterating by index of sequences: We can also use the index of elements in the sequence to iterate. The key
idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.
See the below example:
# Python program to illustrate Iterating by index
list = ["aaa", "bbb", "ccc"]
for index in range(len(list)):
print list[index]
Output:
aaa
bbb
ccc
Using else statement with for loops: We can also combine else statement with for loop like in while loop.
But as there is no condition in for loop based on which the execution will terminate so the else block will
be executed immediately after for block finishes execution.
Below example explains how to do this:
# Python program to illustrate combining else with for
list = ["xxx", "yyy", "zzz"]

28 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

for index in range(len(list)):


print list[index]
else:
print "Inside Else Block"
Output:
aaa
bbb
ccc
Inside Else Block
Python range() function
range() is a built-in function of Python. It is used when a user needs to perform an action for a specific
number of times. The range() function is used to generate a sequence of numbers. range() is commonly
used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code.
Most common use of range() function in Python is to iterate sequence type (List, string etc.. ) with for and
while loop. In simple terms, range() allows user to generate a series of numbers within a given range.
Depending on how many arguments user is passing to the function, user can decide where that series of
numbers will begin and end as well as how big the difference will be between one number and the
next.range() takes mainly three arguments.
start: integer starting from which the sequence of integers is to be returned
stop: integer before which the sequence of integers is to be returned. The range of integers end at stop – 1.
step: integer value which determines the increment between each integer in the sequence
for i in range(10):
print(i, end =" ")
for i in range(1, 20):
print(i, end =" ")
for i in range(0, 30, 3):
print(i, end = " ")
Output:
0123456789
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 3 6 9 12 15 18 21 24 27
Python range() function doesn’t support the float numbers. i.e. user cannot use floating-point or noninteger
number in any of its argument. User can use only integer numbers
Nested Loops: Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:

29 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example
a for loop can be inside a while loop or vice versa.
# Python program to illustrate nested for loops in Python
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output:
1
22
333
4444
Loop Control Statements: Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.
Continue Statement: It returns the control to the beginning of the loop.
Prints all letters except 'h'
for letter in 'Python':
if letter == 'h':
continue
print( 'Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

30 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

Break Statement: It brings control out of the loop


for letter in 'Python':
if letter == 'h':
break
print( 'Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statement, function and classes.
# An empty loop
for letter in 'Python':
pass
print( 'Last Letter :', letter)
Output:
Last Letter : n
.

Python program for implementation of Selection Sort


import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining unsorted array


min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with the first element


A[i],A[min_idx]=A[min_idx],A[i]

# Driver code to test above function


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i])

31 Naipunnya School of Management, Cherthala [Jithin Babu]


S5 BSc Computer Science CS1541: PYTHON PROGRAMMING [Module 1]

#Python program for implementation of Insertion Sort

def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greater than key,
#to one position ahead of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above function


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

# Python program for implementation of Bubble Sort


def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1] :
arr[j],arr[j+1]=arr[j+1],arr[j]

# Driver code to test above function


arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

32 Naipunnya School of Management, Cherthala [Jithin Babu]

You might also like