Python Programming - GPT Koppal 137
Python Programming - GPT Koppal 137
Government of Karnataka
Department of Collegiate and Technical Education
Study Material
Prepared by
RAGHAVENDRA SETTY B
Lecturer, CSE
Government Polytechnic Koppal
WEEK-1
Fundamental Concepts:
Brief history; features; applications of python; python distributions; versions; python IDEs; Python
interpreter; Execution of python programs, debugging python code; Indentation, Comments; best
practices for python programming; Character set; tokens; keywords, variables, naming rules for
variables, Assignment.
Brief History:
Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in
Netherland.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to [Link].
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the
fundamental flaw of the language.
What is Python?
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Features of Python Programming Language:
Python provides many useful features which make it popular and valuable from the other programming
languages.
It supports object-oriented programming; procedural programming approaches and provides dynamic
memory allocation.
Few essential features of python are given below
Easy to Learn and Use
Expressive Language
Interpreted Language
Cross-platform Language
Free and Open Source
Object-Oriented Language
Extensible
Python Distributions:
Here is a brief tour of Python distributions, from the standard implementation (CPython) to versions
optimized for speed (PyPy), for special use cases (Anaconda, ActivePython), for different language runtimes
(Jython, IronPython), and even for cutting-edge experimentation (PyCopy, MesaPy).
Python Versions:
Python programming language is being updated regularly with new features and supports. There are lots of
update in Python versions, started from 1994 to current release.
A list of Python versions with its released date is given below.
Python IDEs:
An IDE (Integrated Development Environment) understand the code much better than a text editor.
It usually provides features such as build automation, code lining, testing and debugging.
This can significantly speed up the work.
There are different IDEs which are as follows.
1. PyCharm
2. Spyder
3. Eclipse PyDev
4. IDLE
5. Sublime Text 3
6. Atom
7. Thonny
8. Visual Studio Code
9. Vim
Python Interpreter:
The word "interpreter" can be used in a variety of different ways when discussing Python.
Sometimes interpreter refers to the Python REPL, the interactive prompt you get by typing python at the
command line.
Sometimes people use "the Python interpreter" more or less interchangeably with "Python" to talk about
executing Python code from start to finish.
Before the interpreter takes over, Python performs three other steps: lexing, parsing, and compiling.
Together, these steps transform the programmer's source code from lines of text into structured code
objects containing instructions that the interpreter can understand.
The interpreter's job is to take these code objects and follow the instructions.
We may be surprised to hear that compiling is a step in executing Python code at all.
Python is often called an "interpreted" language like Ruby or Perl, as opposed to a "compiled" language
like C or Rust.
However, this terminology isn't as precise as it may seem. Most interpreted languages, including Python,
do involve a compilation step.
Python Statement, Indentation and Comments:
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement. if statement, for statement, while statement, etc. are other
kinds of statements which will be discussed later.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement extend
over multiple lines with the line continuation character (\).
Ex:
This is an explicit line continuation. In Python, line continuation is implied inside parentheses (), brackets [ ],
and braces { }. For instance, we can implement the above multi-line statement as
We can also put multiple statements in a single line using semicolons, as follows:
Python Indentation:
Most of the programming languages like C, C++, and Java use braces { } to define a block of code.
Python, however, uses indentation.
Indentation refers to the spaces at the beginning of a code line.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented
line.
All the statements with the block will have the same indentation.
Generally, four whitespaces are used for indentation and are preferred over tabs.
Incorrect indentation will result in IndentationError.
Ex:
The enforcement of indentation in Python makes the code look neat and clean. This results in Python
programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes the code
more readable.
Ex:
Python Comments:
Comments are non executable statements.
Comments can be used to explain the python code.
Comments can be used to make the python code more readable.
In Python, comments start with # and Python Interpreter will ignore them.
Comments can be placed at the end of the line and python will ignore the rest of the line.
Ex:
Multiline comments:
To add a multi line comment insert # for each line.
Ex:
2) Identifiers
3) Literals
4) Operators
5) Punctuators
Keywords:
Keywords are reserved words that have special meaning in a programming language.
These are reserved for special purpose and must not be used as normal identifier names.
There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.
Some of the keywords are False, True, if, elif, else, while, for, break, continue, and, in, not, print, import,
etc.
Identifiers:
Identifiers are the names given to different program elements like variables, objects, classes, function, list,
dictionaries etc
Rules for Naming Identifier:
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or
an underscore. Names like myClass, var_1 and print_this_to_screen, all are valid example.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
Keywords cannot be used as identifiers.
Any other special character or white spaces are strictly prohibited in identifiers.
Python is a case sensitive programming language. So koppal, KOPPAL and Koppal are 3 different
identifiers.
Identifiers can be of any length.
Variables:
The quantity which changes during the execution of the program is known as variable.
In Python, there is no need to declare a variable explicitly as in C, C++, Java by using int, float, etc.
To define a variable in Python, simple assign a value to a name as given below.
Ex:
A= 20
B = “hello”
C= 35.5
Rules for Naming Variables:
Variable name consists of any number of letters, underscores and digits.
Variable name should not start with a digit.
Dept. of Computer Science and Engg. Page 8 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
WEEK-2
Basics I/O operations Input- input (), raw_input() ; output – print (), formatting output. Datatypes Scalar
type: Numeric (int, long, float, complex), Boolean, bytes, None; Type casting Operators Arithmetic,
Comparison/Relational, Logical/Boolean, Bitwise; string operators; Expressions and operator
precedence.
Input:
Python provides us with two inbuilt functions to read the input from the keyboard.
input( prompt )
raw_input( prompt )
input( ) : In python, input() function is used to read or collect data from the user.
The syntax of input() function is
variable_name = input([prompt])
The string that is written inside the parenthesis will be printed on the screen.
Ex:
name = input("what is your name?")
print(name)
age = input("what is your age?")
print(age)
print(type(age))
age = int(input("what is your age?"))
print(age)
print(type(age))
raw_ input(): This function works in older versions of python and is similar to input(). (like Python 2.x).
Ex:
name = raw_input("Enter your name : ")
print(name)
Output: print()
Ex:
print("Hello World")
print("Hello \n World")
print("")
a=10
print(a)
b=20
print(b)
print(a,b)
print("Hello",a,b)
c="koppal"
print("gpt",c)
s1="hello"
s2="koppal"
print(s1,s2)
Formatted Strings (f-strings):
F-strings were introduced in python 2.6
A f-string is a string literal prefixed with “f”
We need to specify the name of the variable or the expression inside the curly braces { } to display its
value.
Ex:
country = “India”
print(f “I Live in { country }”)
r = 3.142
print(f “Area= { 3.142*r*r }”)
Data Types:
Data types tell the type of data that the variable is holding.
Data types are the classification or categorization of input values.
Python variables can store data of different types.
Python has the following built-in data types.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric:
In Python, numeric data type represents the data which has numeric value. Numeric value can be integer,
floating number or complex numbers.
Integers: 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 integer value can be.
Ex:
x= 1
y=23534958345
z=-2356
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Float: This value is represented by float class. It is a real number with floating point representation. It is
specified by a decimal point.
Ex:
x= 1.14560
y=1.1
z=-35.689
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Complex Numbers: Complex number is represented by complex class. It is specified as (real part) +
(imaginary part) j.
x= 3+5j
y=6j
z=-7j
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Boolean:
Boolean represent one of the 2 values: True or False
When we evaluate any expression in python, we get one of 2 values: True or False
When we compare 2 values, the expression is evaluated and python returns the Boolean value.
Ex:
print(10>9)
print(10==9)
print(10<9)
When we run a condition in an if statement, python returns True or False.
Ex:
a=10
b=20
if a>b:
print("a is bigger")
else:
print("a is bigger")
None:
None keyword is used to define a null value.
It is not the same as 0, False or an empty string.
Ex:
x=None
print(x)
Type Casting:
The process of converting one data type to another is known as type casting.
1. Integer conversion function: int()
Ex:
a= int(3.5)
print(a)
print(type(a))
b= int("5")
print(b)
print(type(b))
2. String conversion function: str()
Ex:
a= str(8)
print(a)
print(type(a))
b= str(3.5)
print(b)
print(type(b))
3. Float conversion function: float()
a= float(8)
print(a)
print(type(a))
b= float("3")
print(b)
print(type(b))
c= float(35.50)
print(c)
print(type(c))
4. complex() casting function
Ex:
a= complex(8)
print(a)
print(type(a))
b= complex(3,5)
print(b)
print(type(b))
Operators:
Python language supports a wide range of operators.
They are
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
Arithmetic Operators:
Arithmetic operators are used to execute arithmetic operations such as addition, subtraction, division,
multiplication etc.
Operator Description Example
+ Addition 5+2 gives 7
print("Addition Operator")
print(10 + 35)
print("Subtraction Operator")
print(-10 + 35)
print("Multiplication Operator")
print(4*2)
print("Exponent Operator")
print(4**2)
print("Division Operator")
print(45/10)
print("Modulus Operator --> Returns a reminder")
print(2025%10)
print("Floor division Operator -> Returns the integral part of the quotient")
print(45//10.0)
print(2025//10)
Comparison Operators:
When the values of two operands are to be compared then comparison operators are used.
The output of these comparison operators is always a Boolean value, either True or False.
Operator Description Example
> Greater Than 5 > 7 gives False
print("Equal Operator")
print(10 == 12)
print("Not Equal To Operator")
print(10 != 12)
print("Less Than Operator")
print(10 < 12)
print("Greater Than Operator")
print(10 > 12)
print("Lesser than or Equal to")
print(10 <= 12)
print("Greater than or equal to")
print(10 >= 12)
print("P" < "Q")
print("Ravi" > "Ramu")
print(True == True)
Logical Operators:
The result of the logical operator is always a Boolean value, True or False.
The logical operators are and, or and not.
Operator Description Example
and Returns True if both statements are True 5 > 2 and 5 < 7 gives True
Returns True if at least one of the statement is
or 5 > 2 or 5 < 3 gives True
True
not Reverses the result. not(5 > 2 or 5 < 3) gives False
print(True and False)
print(True or False)
print(not(True) and False)
print(not(True and False))
print((10 < 0) and (10 > 2))
print((10 < 0) or (10 > 2))
print(not(10 < 0) or (10 > 2))
print(not(10 < 0 or 10 > 2))
Bitwise operators:
In Python, bitwise operators are used to performing bitwise calculations on integers.
The integers are first converted into binary and then operations are performed on bit by bit, hence the
name bitwise operators.
print(a&b)
print(a|b)
print(a^b)
print(~a)
print(a<<1)
print(a>>1)
Assignment Operators:
String Operators:
WEEK-3
Control Flow: Conditional blocks If statement: general format; Multiway branching; Sufficient
examples;
if statement:
It is a one way branching statement.
The if statement checks the condition and executes the if block of code when the condition is True, and if
the condition is False, it will not execute it.
The syntax of if statement is given below
Syntax:
if(expression):
statement(s)
If the condition is True, then statement(s) will be executed If the condition is False, statement(s) will not be
executed.
if is a keyword.
Expression: valid Boolean expression results in either True or False
Colon should be present at the end of if statement.
If block statement should have proper indentation.
Ex1:
a = 10
b = 20
if b > a:
print("b is greater than a")
Ex2:
a=int(input("enter a number"))
if a>0:
print("positive number")
if...else statement:
It is a 2 way branching statement.
The if-else statement checks the condition and executes the if block of code when the condition is True, and
executes the else block of code when the condition is False.
The syntax of if….else statement is given below
Syntax:
if(expression):
statement(s)-1
else:
statement(s)-2
If the condition is True, then statements-1 will be executed If the condition is False, statements-2 will be
executed
Nested-if Statements
In Python, the nested if-else statement is an if statement inside another if-else statement.
In Python it is allowed to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting.
The nested if-else is useful when we want to make a series of decisions.
In a nested if construct, can have an if...elif...else construct inside another if...elif...else construct.
Syntax:
if(expression1):
if(expression2):
statement(s)
else:
statements(s)
else:
statement(s)
WEEK-4
Control Flow: Loops
While loop: general format; examples For loop: general format, examples. Range();nesting loops and
conditional statements; Controlling loop execution: Break, continue, pass statements;
Ex1:
count =0
while(count <3):
print("Hello World")
count =count +1
Output
Hello World
Hello World
Hello World
In the above example, the condition for while will be True as long as the counter variable (count) is less than 3.
Ex2:
i=1
while(i <= 5):
print(i)
i=i+1
Output
1
2
3
4
5
for Loop:
A for loop is used for iterating over a sequence.
A for loop is used for sequential traversal i.e. it is used for iterating over an iterable like string, tuple, list,
dictionary etc.
The Syntax of for loop is given below
for var in sequence:
statement(s)
The first item in the sequence is assigned to the iterating variable var. Next, the statements block is
executed.
Each item in the list is assigned to var, and the statement(s) block is executed until the entire sequence is
exhausted.
Ex1:
for x in "koppal":
print(x)
output:
k
o
p
p
a
l
apple
mango
Ex3: range() function
for i in range(10):
print(i)
range() function:
The range() function is used to generate a sequence of numbers.
The range() function is a built-in function of Python.
The range() function allows the user to generate a series of numbers within a given range.
The range() works as it produces a list of numbers from zero to the value minus one.
The syntax of range() is given below
Syntax
range([start,] stop [,step])
where,
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.
step: integer value which determines the increment between each integer in the sequence.
The 3 general forms of range are given below
1. range(stop)
2. range(start, stop)
3. range(start, stop, step)
range(5) produces five values: 0, 1, 2, 3, and 4.
range(3,8) will produce the list 3, 4, 5, 6, 7
Ex1: Create a sequence of numbers from 0 to 5, and print each item in the sequence:
for n in range(6):
print(n)
Output
0
1
2
3
4
5
Ex2: Program that counts down from 5 and then prints a message.
for i in range(5,0,-1):
print(i, end=' ')
print('End!!')
Output
5 4 3 2 1 End!!
The end=' ' just keeps everything on the same line.
Ex2:
num=[11,33,55,39,55,75,37,21,23,41,13]
for n in num:
if n%2==0:
print (“the list contains an even number”)
break
else:
print (“the list does not contain even number”)
Output
the list does not contain even number
Nested loops:
Python programming language allows the use of one loop inside another loop.
Syntax for a nested for loop statement in Python programming language is as follows
for var in sequence:
for var in sequence:
statements(s)
statements(s)
Syntax for a nested while loop statement in Python programming language is as follows
while expression:
while expression:
statement(s)
statement(s)
Ex:
for i in range(1,10):
for j in range(1,10):
print (i*j)
Loop Control Statements:
The Loop control statements change the execution from its normal sequence.
Python supports the following control statements:
break statement :
Terminates the loop statement and transfers the execution to the statement immediately following the loop.
It is used in both while and for loops.
It is usually associated with if statement.
If you are using nested loops, the break statement stops the execution of the innermost loop and starts
executing the next line of the code after the block.
Syntax for a break statement in Python is as follows
break
Ex1:
for letter in 'python':
if letter == 'h':
break
print (letter)
output:
p
y
t
Ex2:
for i in range(10):
if i==5:
break
print (i)
output:
0
1
2
3
4
continue statement:
It is used to skip the current iteration and continue with the next iteration.
It is present only inside a loop.
It is usually associated with if statement.
Syntax for a continue statement in Python is as follows
continue
Ex1:
for letter in 'python':
if letter == 'h':
continue
print (letter)
output:
p
y
t
o
n
Ex2:
for i in range(5):
if i==2:
continue
print (i)
output:
0
1
3
4
pass statement:
The pass statement in Python is used when a statement is required syntactically but you do not want any
command or code to execute.
It is a null operation, nothing happens when it is executed.
It acts as a placeholder with empty body.
It is used in both loops and functions.
Syntax for a pass statement in Python is as follows
pass
Ex1:
for letter in 'python':
pass
print (letter)
output:
n
WEEK-5
Data Collections: Concept of mutability, Set – features, declaration, initialization, operations,
comprehension;
Tuple-features; declaration, initialization, basic operations; indexing; slicing; built in functions; Nested
tuples;
Set:
Set is a collection which is unordered, unchangeable and unindexed.
Sets are used to store multiple items in a single variable.
Sets are written with curly braces { }.
It is one of the 4 built-in data types in python to store collection of data. The other 3 are list, tuple and
dictionary.
Set Features:
It is represented using curly braces { } with comma separation.
Set items can be of any data type. (heterogeneous collection)
Order of elements is not preserved.
Each element must be unique. (no duplication)
We cannot change its items. But we can add new item or remove items from set.
Indexing and slicing operations are not applicable.
We can perform union, intersection and difference operations on set elements.
Declaration and Initialization:
Set can be created by enclosing the comma separated items with the curly braces.
s1={10,20,30,40}
fruits={"apple","banana","orange"}
s2={10,36.7,"banana",True}
print(s1)
print(fruits)
print(s2)
output:
{40, 10, 20, 30}
{'banana', 'apple', 'orange'}
{'banana', True, 10, 36.7}
A set () function is used to create an empty set and to convert other data collections to set.
s1=set()
print(s1)
output:
set()
String to Set:
s2=set("koppal")
print(s2)
output:
{'a', 'o', 'k', 'l', 'p'}
List to Set:
l1=[20,30,40,50]
s3=set(l1)
print(s3)
output:
{40, 50, 20, 30}
Tuple to set:
t1=(5,7,9,11)
s4=set(t1)
print(s4)
output:
{9, 11, 5, 7}
Range to Set:
s5=set(range(1,20,4))
print(s5)
output:
{1, 5, 9, 13, 17}
Basic Operations:
Adding items to the set:
add(): The add() function is used to add a single element to the list.
Ex:
s1={10,20,30,40}
print(s1)
[Link](50)
print(s1)
[Link](60)
print(s1)
output:
{40, 10, 20, 30}
{40, 10, 50, 20, 30}
{40, 10, 50, 20, 60, 30}
update(): The update() function is used to add multiple elements to the set.
Ex:
s1={10,20,30,40}
print(s1)
[Link]([5,7,9])
print(s1)
[Link]((4,8,12))
print(s1)
output:
{40, 10, 20, 30}
{5, 7, 40, 9, 10, 20, 30}
{4, 5, 7, 40, 9, 10, 8, 12, 20, 30}
Ex:
s1={10,20,30,40}
print(s1)
l1=[5,7,9]
[Link](l1)
print(s1)
t1=(4,8,12)
[Link](t1)
print(s1)
output:
{40, 10, 20, 30}
{5, 7, 40, 9, 10, 20, 30}
Dept. of Computer Science and Engg. Page 37 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
s1={10,20,30,40,50,60}
print(s1)
[Link]()
print(s1)
output:
{40, 10, 50, 20, 60, 30}
{10, 50, 20, 60, 30}
Mathematical operations such as union, intersection, difference and symmetric difference can be performed
on sets.
Union of 2 sets:
The union() method is used to join 2 or more sets.
This method returns a new set containing all the items from both sets.
It will remove the duplicates.
Ex:
s1={5,10,15,20}
s2={10,20,30,40}
s3=[Link](s2)
print(s1)
print(s2)
print(s3)
output:
{10, 20, 5, 15}
{40, 10, 20, 30}
{5, 40, 10, 15, 20, 30}
Intersection of 2 sets:
The intersection() method will return a new set that only contains the items that are present in both the sets.
Ex:
s1={5,10,15,20}
s2={10,20,30,40}
s3=[Link](s2)
print(s1)
print(s2)
print(s3)
Dept. of Computer Science and Engg. Page 39 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
output:
{10, 20, 5, 15}
{40, 10, 20, 30}
{10, 20}
Difference of 2 sets:
The difference() method will return a new set containing the difference between 2 or more sets.
It is denoted by A-B, the resulting set will contains the items that are present only in A but not in B.
Ex:
s1={5,10,15,20}
s2={10,20,30,40}
s3=[Link](s2)
print(s1)
print(s2)
print(s3)
output:
{10, 20, 5, 15}
{40, 10, 20, 30}
{5, 15}
Symmetric Difference:
The symmetric_difference() method removes the items that are present in both the sets.
Ex:
s1={5,10,15,20}
s2={10,20,30,40}
s3=s1.symmetric_difference(s2)
print(s1)
print(s2)
print(s3)
output:
{10, 20, 5, 15}
{40, 10, 20, 30}
{5, 40, 30, 15}
Tuple:
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets ( ).
Features of Tuple:
It is represented using parenthesis ( ) with comma separation.
Tuple items can be of any data type. (heterogeneous collection)
Order of elements is preserved in tuple.
We cannot change the content of tuple items.
Each element need not be unique. (allows duplication)
Indexing operation is supported.
Slicing operation is supported.
Declaration and Initialization:
Tuple can be created by enclosing the comma separated items with the parenthesis ( ).
t1 = (20,40,60,80,100)
t2 = ("apple","banana","orange")
t3 = (10,True,56.78,"apple")
print(t1)
print(t2)
print(t3)
output:
(20, 40, 60, 80, 100)
('apple', 'banana', 'orange')
(10, True, 56.78, 'apple')
It is also possible to use the tuple() constructor to create a tuple.
t1 = tuple(("apple", "banana", "cherry"))
print(t1)
output:
('apple', 'banana', 'cherry')
List to tuple:
l1=[10,20,30,40]
t1=tuple(l1)
print(t1)
output:
(10, 20, 30, 40)
Set to tuple:
s1={10,20,30,40}
t1=tuple(s1)
print(t1)
output:
(40, 10, 20, 30)
String to tuple:
t1=tuple("koppal")
print(t1)
output:
('k', 'o', 'p', 'p', 'a', 'l')
Range to tuple:
t1=tuple(range(1,20,3))
print(t1)
output:
(1, 4, 7, 10, 13, 16, 19)
Basic Operations:
Concatenation operator:
We can add the elements of 2 or more tuples using concatenation operator +.
t1 = (20,40,60)
t2 = (23,48,56)
t3 = t1 + t2
print(t3)
output:
(20, 40, 60, 23, 48, 56)
Repetition Operator:
To repeat the elements present inside the tuple for specified number of times, use the repetition operator *.
t1=(10,20,30)
print(t1*3)
output:
(10, 20, 30, 10, 20, 30, 10, 20, 30)
Membership operators (in, not):
t1=(10,20,30)
print(10 in t1)
print(50 in t1)
print(10 not in t1)
print(50 not in t1)
output:
True
False
False
True
Deleting a tuple:
The entire tuple elements can be deleted by using the del keyword.
t1=(10,20,30,40)
del(t1)
Length of a tuple:
The len is used to find the length of the tuple
t1 = (20,40,60,80,100)
t2 = ("apple","banana","orange")
print(len(t1))
print(len(t2))
output:
5
3
Indexing:
Tuple items are ordered, so they can be accessed by their index.
The items of the tuple can be accessed by using the index [ ] operator.
The first item has an index 0, the second item has an index 1, and next items have an index 2, 3, 4 and up to
length-1.
The index value must be an integer.
If the step value is positive, slicing will happen in forward direction. (left to right).
If the step value is negative, slicing will happen in backward direction. (right to left).
For forward direction:
o The default value for begin is 0.
o The default value for end is the length of the list.
o The default value for step is +1.
Ex:
t1 = (10,20,30,40,50,60,70,80)
print(t1[2:])
print(t1[:4])
print(t1[2:5])
print(t1[Link])
print(t1[::2])
print(t1[::])
print(t1[-4:-2])
print(t1[::-1])
output:
(30, 40, 50, 60, 70, 80)
(10, 20, 30, 40)
(30, 40, 50)
(10, 30, 50)
(10, 30, 50, 70)
(10, 20, 30, 40, 50, 60, 70, 80)
(50, 60)
(80, 70, 60, 50, 40, 30, 20, 10)
Ex2:
t1 = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(t1[:4])
print(t1[2:])
print(t1[-4:-1])
output:
('apple', 'banana', 'cherry', 'orange')
('cherry', 'orange', 'kiwi', 'melon', 'mango')
Dept. of Computer Science and Engg. Page 45 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
Ex:
t1=(43,26,33,41)
print(len(t1))
print(max(t1))
print(min(t1))
t2=(10,20,30,40,20,30,20)
print([Link](20))
print([Link](30))
output:
4
43
26
3
2
Nested tuple:
WEEK-6
List features; declaration, initialization, basic operations; indexing; List iterations; Slicing; built in
functions; Nested Lists; Comprehensions; Applications
List:
List is a collection which is ordered, changeable and indexed.
Lists are used to store multiple items in a single variable.
Lists are written with square brackets [ ]
List Features:
It is represented using square brackets [ ] with comma separation.
List items can be of any data type. (heterogeneous collection)
Lists are ordered i.e. order of elements is preserved.
Lists are mutable. i.e. we can modify the contents of list items.
List items are accessed by their index.
List items need not be unique. (It allows duplication)
Slicing operation is supported.
Lists can be nested.
Declaration and Initialization:
An empty list can be created by using the square brackets [ ] as follows.
l1=[]
print(l1)
output:
[]
List with items can be created by enclosing the comma separated items within the square brackets [ ].
l1=[10,20,30,40]
fruits=["apple","banana","orange"]
l2=[10,36.7,"banana",True]
print(l1)
print(fruits)
print(l2)
output:
[10, 20, 30, 40]
l2= l1*3
print(l2)
output:
[10, 20, 30, 10, 20, 30, 10, 20, 30]
6. Membership Operators (in, not)
l1=[10,20,30]
print(10 in l1)
print(50 in l1)
print(10 not in l1)
print(50 not in l1)
output:
True
False
False
True
7. Traversing List items
l1=[10,20,30,40,50]
for x in l1:
print(x)
output:
10
20
30
40
50
Indexing:
List items are ordered, so they can be accessed by their index.
The items of the list can be accessed by using the index [ ] operator.
The first item has an index 0, the second item has an index 1, and next items have an index 2, 3, 4 and up to
length-1.
The index value must be an integer.
The List supports both positive and negative Indexing.
If the step value is negative, slicing will happen in backward direction. (right to left).
For forward direction:
o The default value for begin is 0.
o The default value for end is the length of the list.
o The default value for step is +1.
Ex:
x = [1,2,3,4,5,6,7,8]
print(x[2:])
print(x[4:])
print(x[:4])
print(x[1:5])
print(x[Link])
print(x[::-1])
print(x[:-6])
print(x[-6:-1])
Output:
[3, 4, 5, 6, 7, 8]
[5, 6, 7, 8]
[1, 2, 3, 4]
[2, 3, 4, 5]
[1, 3, 5]
[8, 7, 6, 5, 4, 3, 2, 1]
[1, 2]
[3, 4, 5, 6, 7]
Ex2:
x = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(x[:4])
print(x[2:])
print(x[-4:-1])
Output:
['apple', 'banana', 'cherry', 'orange']
['cherry', 'orange', 'kiwi', 'melon', 'mango']
['orange', 'kiwi', 'melon']
Dept. of Computer Science and Engg. Page 53 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
List Iterations:
The for loop is used to iterate the contents of list items.
l1=[10,20,30,40,50]
for x in l1:
print(x)
output:
10
20
30
40
50
The while loop can also be used to iterate the list items.
l1=[10,20,30,40,50]
i=0
while i<len(l1):
print(l1[i])
i=i+1
output:
10
20
30
40
50
Using list comprehension also we can iterate the list items.
l1=[10,20,30,40,50]
[print(i) for i in l1]
output:
10
20
30
40
50
Built-in Functions:
1. append(): The append()function is used to add a item at the end of the list.
Ex:
x=[10,20,30,40]
print(x)
[Link](50)
print(x)
[Link]((5,6))
print(x)
[Link]([7,8])
print(x)
output:
[10, 20, 30, 40]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50, (5, 6)]
[10, 20, 30, 40, 50, (5, 6), [7, 8]]
2. insert()
The insert()function is used to add an item at the desired position.
This method takes 2 arguments.
The syntax of insert() function is given below
insert(position,value)
Ex:
x=[10,20,30,40]
[Link](3,25)
print(x)
[Link](2,[2,3])
print(x)
output:
[10, 20, 30, 25, 40]
[10, 20, [2, 3], 30, 25, 40]
3. extend(): The extend() function is used to add multiple elements at the same time at the end of the list.
Ex:
x=[10,20,30,40]
[Link]([3,4,5])
print(x)
[Link]((2,3,6))
print(x)
output:
[10, 20, 30, 40, 3, 4, 5]
[10, 20, 30, 40, 3, 4, 5, 2, 3, 6]
4. remove()
The remove() method is used to remove elements from the list.
It removes only one element at a time.
It removes the specified item.
It gives an error if element does not exist in list.
Ex:
x=[10,20,30,40]
print(x)
[Link](20)
print(x)
output:
[10, 20, 30, 40]
[10, 30, 40]
5. pop()
By default, the pop() method will remove the last element from the list.
The pop() with specified position will remove the specified element from the list.
Ex1:
x=[10,20,30,40]
print(x)
[Link]()
print(x)
output:
[10, 20, 30, 40]
[10, 20, 30]
Ex2:
Dept. of Computer Science and Engg. Page 56 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
x=[10,20,30,40]
print(x)
[Link](1)
print(x)
output:
[10, 20, 30, 40]
[10, 30, 40]
6. clear() : This function is used to erase all the elements from the list.
Ex:
x=[10,20,30,40]
print(x)
[Link]()
print(x)
output:
[10, 20, 30, 40]
[]
7. count(): This function returns the number of occurrences of the specified element from the list.
Ex:
x=[10,20,30,40,20,30,40,20,30]
print([Link](20))
output:
3
8. index(): This function returns the index of the first occurrence of the specified value.
x=[10,30,30,40,20,40,20]
print([Link](20))
output:
4
9. sort()
Sort means arranging items either in ascending order or in descending order.
The sort() function sorts the items in ascending order.
Ex:
x=[10,30,40,20,50]
[Link]()
Dept. of Computer Science and Engg. Page 57 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
print(x)
y=["cherri","kiwi","banana","orange"]
[Link]()
print(y)
output:
[10, 20, 30, 40, 50]
['banana', 'cherri', 'kiwi', 'orange']
10. reverse() : This function reverses the elements of the given list.
Ex:
x=[10,20,30,40,50]
print(x)
[Link]()
print(x)
output:
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
11. copy(): This function returns the copy of the list.
Ex:
x=[10,20,30,40,50]
print(x)
y=[Link]()
print(y)
output:
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
Nested List:
A List inside another list is known as nested list.
Duplicate elements are also allowed.
Nested indexing is used to access the nested elements.
Ex:
l=[4,5,6,[8,9],[10,20,30]]
print(l)
print(l[2])
print(l[3])
print(l[4])
print(l[3][1])
print(l[4][2])
output:
[4, 5, 6, [8, 9], [10, 20, 30]]
6
[8, 9]
[10, 20, 30]
9
30
List Comprehension:
List comprehension offers a shorter syntax when we want to create a new list based on the values of an existing
list.
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition: The condition is like a filter that only accepts the items that valuate to True.
Iterable: The iterable can be any iterable object, like a list, tuple, set etc.
Expression: The expression is the current item in the iteration, but it is also the outcome, which you can
manipulate before it ends up like a list item in the new list.
Ex:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
WEEK-7
Dictionary: Features, declaration, initialization, basic operations; indexing; adding and removing keys,
iterating through dictionaries; built in functions; Comprehensions; Applications.
Dictionary:
Dictionaries are used to store data values in key-value pairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Dictionaries are written with flower brackets { }.
Features:
It is an ordered collection that contains key - value pairs separated by comma inside curly braces {}.
Each key is separated from its value by a colon ( : )
Dictionaries are ordered i.e. order of elements is preserved.
Dictionaries are changeable, means we can change, add or remove items from the dictionary.
Duplicate keys are not allowed i.e. dictionaries cannot have 2 items with the same key.
Dictionary keys are case sensitive.
Keys must be single element.
Values in dictionary can be of any data type and can be duplicated. Ex: list, tuple ,string, integer, etc
Dictionaries are indexed by keys.
Slicing concept is not supported.
Declaration and Initialization:
An empty dictionary can be created by using the curly braces { } as follows.
d1={}
print(d1)
output:
{}
A dictionary is created by placing a sequence of elements within curly braces {}, separated by comma and
each key is separated from its value by the colon (:)
d1={1:'cs',2:'ec',3:'mech'}
d2={'name':'ravi','age':50,'marks':[45,56,78]}
print(d1)
print(d2)
output:
{1: 'cs', 2: 'ec', 3: 'mech'}
output:
{'brand': 'Ford', 'year': 2002}
{'brand': 'Ford', 'year': 2018}
3. Membership operators:(in, not)
d = {37:'koppal', 35:'hospet'}
print(37 in d)
print(38 in d)
print(37 not in d)
print(38 not in d)
output:
True
False
False
True
4. Concatenation Operator (+):
d1={1:'cs',2:'ec'}
d2={3:'mech',4:'civil'}
d3=d1+d2
print(d3)
5. Repetition operator(*):
d1={1:'cs',2:'ec',3:'mech'}
d2=d1*3
print(d2)
Indexing:
In dictionary, key is used to access the content of value.
car={"brand":"Ford","year":2002,"price":50000}
print(car['brand'])
print(car['year'])
print(car['price'])
d1={1:'cs','name':'ravi','age':48,'marks':[45,67,56]}
print(d1['name'])
print(d1['age'])
print(d1['marks'])
print(d1[1])
output:
Ford
2002
50000
ravi
48
[45, 67, 56]
cs
Adding and Removing Keys:
The dictionary is a mutable data type, and its value can be updated by using the specific keys.
The new key value pair can be added or removed easily from the dictionary.
Adding Keys (Elements):
A new key-value pair can be added as follows.
d={1:'cs',2:'ec'}
d[3]='mech'
d[4]='civil'
print(d)
output:
{1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
The update() method can also be used to add new key-value pairs to the dictionary.
car={"brand":"Ford","year":2002}
[Link]({'electric':False})
print(car)
output:
{'brand': 'Ford', 'year': 2002, 'electric': False}
Removing Keys:
A specific key-value pair can be removed from the dictionary using del keyword or by using pop() method.
Ex1:
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
del d[2]
print(d)
output:
{1: 'cs', 3: 'mech', 4: 'civil'}
Ex2:
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
[Link](2)
print(d)
output:
{1: 'cs', 3: 'mech', 4: 'civil'}
The popitem() method is used to remove the last item from the dictionary.
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
[Link]()
print(d)
output:
{1: 'cs', 2: 'ec', 3: 'mech'}
The clear() method is used to remove all the elements from the dictionary
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
[Link]()
print(d)
output:
{}
Iterating Through Dictionaries:
For loop is used to iterate all the key-value pairs of a dictionary.
1) To iterate keys:
emp={'name':'ravi','age':30,'salary':50000}
for x in emp:
print(x)
output:
name
age
salary
2) To iterate values:
emp={'name':'ravi','age':30,'salary':50000}
for x in emp:
print(emp[x])
output:
ravi
30
50000
3) To iterate values using values() method:
emp={'name':'ravi','age':30,'salary':50000}
for x in [Link]():
print(x)
output:
ravi
30
50000
4) To iterate keys using keys() method:
emp={'name':'ravi','age':30,'salary':50000}
for x in [Link]():
print(x)
output:
name
age
salary
5) To iterate both key-values using items() method:
emp={'name':'ravi','age':30,'salary':50000}
for x in [Link]():
print(x)
output:
('name', 'ravi')
('age', 30)
('salary', 50000)
5. get():
The get() method returns the value of the item with the specified key.
emp={'name':'ravi','age':30,'salary':50000}
x=[Link]('age')
print(x)
x=[Link]('name')
print(x)
output:
30
ravi
6. pop():
The pop() method removes and returns the specified item from the dictionary.
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
x = [Link](2)
print("The deleted item =",x)
print(d)
output:
The deleted item = ec
{1: 'cs', 3: 'mech', 4: 'civil'}
7. popitem():
The popitem() method removes the last inserted key-value pair from the dictionary.
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
x = [Link]()
print("The deleted item =",x)
print(d)
output:
The deleted item = (4, 'civil')
{1: 'cs', 2: 'ec', 3: 'mech'}
8. clear():
The clear() method removes all items from the dictionary.
d={1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
[Link]()
print(d)
output:
{}
9. update():
The update() method updates the dictionary with the elements from another dictionary or from
an iterable of key-value pairs.
d1={1: 'cs', 2: 'ec'}
d2={3: 'mech', 4: 'civil'}
[Link](d2)
print(d1)
output:
{1: 'cs', 2: 'ec', 3: 'mech', 4: 'civil'}
Dictionary comprehension:
Dictionary comprehension is an elegant and concise way to create dictionaries.
The minimal syntax for dictionary comprehension is:
dictionary = {key: value for vars in iterable}
square_dict = {}
for num in range(1, 5):
square_dict[num] = num * num
print(square_dict)
output:
{1: 1, 2: 4, 3: 9, 4: 16}
Dictionary comprehension:
square_dict = {num: num * num for num in range(1, 5)}
print(square_dict)
output:
{1: 1, 2: 4, 3: 9, 4: 16}
WEEK-8
Arrays and Strings:
Arrays: features; create, initialize, indexing, traversal, manipulation;
Strings: create, assign, indexing, built in functions;
Arrays:
Arrays are used to store multiple values in one single variable.
The main difference between arrays and lists. While python lists can contain values corresponding to
different data types, arrays in python can only contain values corresponding to same data type.
To use arrays in python language, we need to import the standard array module. This is because array is not
a fundamental data type like strings, integer etc.
Features:
Arrays are ordered collection of items.
Arrays are homogenous collection of items. i.e. All the elements of array must be same numeric type.
We can store only numeric values.
Arrays are mutable. i.e. we can modify the contents of array elements.
It supports both indexing and slicing.
Creating and initializing an array:
Array is created in Python by importing array module to the python program.
If we create arrays using the array module, elements of the array must be of the same numeric type.
The syntax for creating an array is given below
import array as arr
arrayName = [Link](typecode[,arrayitems])
OR
from array import *
arrayName = array(typecode, [arrayitems])
Ex:
import array as arr
a = [Link]('i', [10, 23, 35])
print(a)
output:
array('i', [10, 23, 35])
OR
Indexing:
We can access each element of an array using the index of the element.
An array supports both positive and negative indexing.
The syntax for indexing array elements is
arrayName[indexNum]
Ex:
import array as arr
a1 = [Link]('i', [10,20,30,40,50])
print (a1[0])
print (a1[2])
print (a1[4])
print (a1[-1])
print (a1[-2])
print (a1[-5])
output:
10
30
50
50
40
10
Slicing:
We can access a range of items in an array by using the slicing operator (:).
Ex:
import array as arr
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = [Link]('i', numbers_list)
print(numbers_array[2:5]) # 3rd to 5th
print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end
output:
array('i', [62, 5, 42])
array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
Array Traversal:
For loop is used to traverse the contents of array as shown below.
Ex:
import array as arr
a1 = [Link]('i', [10,20,30,40,50])
for x in a1:
print(x)
a2 = [Link]('d', [22.5, 36.2, 53.3])
for i in range (0, len(a2)):
print (a2[i], end =" ")
output:
10
20
30
40
50
22.5 36.2 53.3
Array manipulations:
Changing Array Elements:
Arrays are mutable; their elements can also be changed in a similar way as lists.
Ex:
import array as arr
numbers = [Link]('i', [1, 2, 3, 5, 7, 10])
numbers[0] = 50
print(numbers)
numbers[2:5] = [Link]('i', [40, 60, 80])
print(numbers)
output:
array('i', [50, 2, 3, 5, 7, 10])
array('i', [50, 2, 40, 60, 80, 10])
Adding Array Elements: insert(), append() and extend():
We can use insert() method to insert an item into an array at any given index of the array.
This method takes two arguments index and value and the syntax is given below.
[Link](index, value)
Ex:
import array as arr
numbers = [Link]('i', [300,200,100])
print(numbers)
[Link](2, 150)
print(numbers)
output:
array('i', [300, 200, 100])
array('i', [300, 200, 150, 100])
We can add one item at the end of the array using the append() method.
We can add several items at the end of the array using the extend() method.
Ex:
import array as arr
numbers = [Link]('i', [1, 2, 3])
print(numbers)
[Link](4)
print(numbers)
Dept. of Computer Science and Engg. Page 72 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
[Link]([5, 6, 7])
print(numbers)
output:
array('i', [1, 2, 3])
array('i', [1, 2, 3, 4])
array('i', [1, 2, 3, 4, 5, 6, 7])
Concatenation Operator (+):
We can also concatenate two arrays using + operator.
Ex:
import array as arr
odd = [Link]('i', [1, 3, 5])
even = [Link]('i', [2, 4, 6])
numbers = odd + even
print(odd)
print(even)
print(numbers)
output:
array('i', [1, 3, 5])
array('i', [2, 4, 6])
array('i', [1, 3, 5, 2, 4, 6])
Removing Array Elements: (del, remove(), pop())
We can delete one or more items from an array using Python's del keyword.
Ex:
import array as arr
numbers = [Link]('i', [15, 26, 37, 32, 43])
del numbers[2]
print(numbers)
del numbers
#print(numbers) # Error: array numbers is not defined
output:
array('i', [15, 26, 32, 43])
The remove() method is used to remove the given item.
The pop(i) method with index will remove an item at the given index.
count():
We can count the occurrence of elements in the array using the count() method
Ex:
import array as arr
number = [Link]('i', [22, 32, 52, 42, 32, 30, 32])
print([Link](32))
output:
3
STRINGS:
A string is a sequence of characters.
Computers do not deal with characters; they deal with numbers (binary). Even though you may see
characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s. This
conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encodings used.
In Python, a string is a sequence of Unicode characters. Python does not have a character data type,a single
character is simply a string with a length of 1.
Creating and Assigning a String:
Strings in Python can be created by enclosing characters inside a single quotes or double quotes or even
triple quotes.
Triple quotes can be used in Python but generally used to represent multiline strings.
Ex:
s1 = 'Hello'
print(s1)
s2 = "World"
print(s2)
s3 = '''"Hello World"'''
print(s3)
# triple quotes string can extend multiple lines
s4 = """Hello, welcome to
the world of Python"""
print(s4)
output:
Hello
World
"Hello World"
Hello, welcome to
the world of Python
Indexing: Accessing characters in Python:
In Python, individual characters of a String can be accessed by using the method of Indexing.
The index is used to access a specific character of a string.
Strings support both positive and negative indexing.
In positive Indexing, the index value of the first character is 0.
Negative Indexing means 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.
Ex:
str = 'program'
print(str[0])
print(str[1])
print(str[6])
print(str[-1])
print(str[-2])
print(str[-6])
output:
p
r
m
m
a
r
String Slicing:
To access a range of characters in the String, the method of slicing is used.
Slicing in a String is done by using a Slicing operator (colon)
k
o
p
p
a
l
Ex2: Count the number of l’s in the given string.
str = "hello world"
count = 0
for x in str:
if x == 'l':
count = count+1
print("The numbers of l's in sting is:",count)
output:
The numbers of l's in sting is: 3
Deleting/Updating from a String:
Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. But can simply reassign different strings to the same name.
Cannot delete or remove characters from a string. But deleting the string entirely is possible using the del
keyword.
Ex:
s1 = "Hello"
print("Initial String:")
print(s1)
s1 = "Welcome to the Python World"
print("Updated String:")
print(s1)
del s1
print("String s1 deleted")
#print(s1) #NameError: name 's1' is not defined
output:
Initial String:
Hello
Updated String:
Welcome to the Python World
String s1 deleted
String Methods / String built-in functions:
1. upper(): This method converts all the characters of a string to upper case.
Ex:
s = "koppal"
print([Link]())
output:
KOPPAL
2. lower(): This method converts all the characters of a string to lower case.
Ex:
s = "KOPPAL"
print([Link]())
output:
koppal
3. strip(): This method removes all the white spaces before and after a string.
Ex:
s=" koppal "
print(s)
print([Link]())
output:
koppal
koppal
4. replace(): This method replaces a substring with another string.
Ex:
s = "welcome to gpt koppal"
print(s)
print([Link]('gpt','wpt'))
output:
welcome to gpt koppal
Week -9
Functions:
Need of functions, Types, Define Function, Calling function, Function arguments; return and yield, None
keyword; scope of variables; Recursion; Anonymous functions; Sufficient examples.
Function:
A function is a block of code which only runs when it is called.
We can pass data known as arguments to a function.
A function can also return data as a result.
There are 2 types of functions.
1. User defined function: These functions are defined by the user to perform some task.
2. Built-in function: These functions are predefined in python.
Defining a Function:
In python, a function is defined using the def keyword.
The indented block of code will be executed when the function is called.
The syntax of defining a function is given below.
def function_name(parameters):
statement(s)
Ex:
def display():
print("hello world")
Calling a Function:
A function can be called using its name.
It can be called any number of times.
When a function is called, then only the statements associated with that function will be executed.
The syntax of calling a function is given below.
function_name()
OR
function_name(parameters)
Ex:
def display():
print("hello world")
display()
output:
Dept. of Computer Science and Engg. Page 81 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
hello world
The function can also take some arguments that can be used in the function body.
Ex:
def area(radius):
return 3.14 * radius**2
print(area(2))
output:
12.56
The function can also return result (values) to the calling function using return keyword.
The return keyword is followed by an expression.
The expression will be evaluated first and result will be returned to the function.
Ex:
def add(a,b):
return(a+b)
c=add(35,15)
print(c)
print(add(25,15))
output:
50
40
Function Arguments:
The arguments are information or data which are passed to the function.
The arguments are specified in the parenthesis.
We can pass any number of arguments, but they must be separated by a comma.
Types of Function Arguments:
1. Fixed Arguments
2. Arbitrary Arguments
3. Keyword Arguments
4. Arbitrary Keyword Arguments
5. Default argument value
6. Passing List/tuple/string as an argument
Fixed Arguments:
In this type number of arguments of the function is fixed.
Ex:
def add(a,b):
print(a+b)
add(5,10)
#add(10) => Error
#add(10,20,30) => Error
output:
15
Arbitrary Arguments:
It is possible to define a function so that any number of arguments can be passed to it.
This is done by adding * before the argument name in function definition.
The function will receive the input in the form of tuple.
Ex:
def disp(*args):
for x in args:
print(x)
disp(5,10)
disp('ravi','ramu')
output:
5
10
ravi
ramu
Keyword Arguments:
Arguments can also be sent to the function with the key=value format.
The arguments sent in this way are called keyword arguments.
Order of arguments does not matter in this type.
Ex:
def disp(a,b):
print(a)
print(b)
Dept. of Computer Science and Engg. Page 83 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
disp(a='ravi',b='ramu')
output:
ravi
ramu
Arbitrary Keyword Arguments:
It is possible to define a function so that any number of keyword arguments can be passed to it.
This is done by adding ** before the argument name in function definition.
The function will receive the input in the form of dictionary.
Ex:
def disp(**args):
print(args['brand'])
print(args['year'])
disp(brand='ford',year=2000,cost=50000)
output:
ford
2000
Default argument value:
A function with an argument can be defined so that it automatically give some default value to the argument if
none is passed to it.
Ex:
def disp(country="India"):
print(country)
disp("France")
disp("America")
disp()
disp("Japan")
disp()
output:
France
America
India
Japan
India
Dept. of Computer Science and Engg. Page 84 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
def add(a,b):
return(a+b)
print(add(25,15))
output:
40
Return with multiple values:
A function can return multiple values in the form of list or tuple or dictionary.
Ex1:
def disp():
name="ravi"
age=50
return (name,age)
t1=disp()
print(t1)
output:
('ravi', 50)
Ex2:
def disp():
name="ravi"
age=50
return [name,age]
l1=disp()
print(l1)
output:
['ravi', 50]
Yield:
Python yield returns a generator object.
The syntax is given below
def function_name(parameters):
yield (expression)
Ex:
def disp():
yield "computer science and engineering"
t=disp()
print(t)
for x in t:
print(x)
output:
<generator object disp at 0x037688F0>
Ex:
a=10
def disp():
print(a)
disp()
print(a)
output:
10
10
Local Variable:
The variable which are declared inside the function are called local variable.
The local variables can be accessed only inside the function where it is defined.
Ex:
def disp():
a=10
print(a)
disp()
#print(a) #NameError: name 'a' is not defined
output:
10
Ex2:
a=10
def disp():
a=20
print(a)
disp()
print(a)
output:
20
10
Recursion:
A function calls itself is called function recursion.
15
Ex3:
def cube(x):
return(x*x*x)
lc=lambda x:x*x*x
print(cube(3))
print(lc(4))
output:
27
64
Week -10
Modules and Packages:
Why modules? Module creation;Importing modules; Module Namespace;
Packages: basics; path setting;Package __init__.py Files;
Commonly used modules: Math, random; Emoji;
Module:
Modules in Python are reusable libraries of code having .py extension, which implements a group of
functions and statements.
Python comes with many built-in modules as part of the standard library.
A module is like a code library that can be imported and used in a program.
The module can contain functions, but also variables of all types (arrays, dictionaries, lists etc)
Why modules?
We use Modules to break down larger programs into smaller manageable programs.
Modules provide reusability of code.
Grouping related code into a module makes the code easier to understand and use.
Maintainability of the function will be increased.
Module creation:
To create a module, we just need to save the required code in a file with the file extension .py
Ex: Add the below two functions in file and save it as [Link]
def add(a,b):
print("the sum=",a+b)
def product(a,b):
print("the product=",a*b)
Ex:
Importing modules:
To use a module in your program, import the module using import statement.
All the import statements are placed at the beginning of the program.
The syntax for import statement is
import module_name
Ex:
import mymodule
[Link](5,10)
[Link](4,5)
output:
the sum= 15
the product= 20
Ex2:
[Link]
person1 = { 'name' : 'Ravi', 'age' : 25, 'state' : 'Tamil Nadu' }
person2 = { 'name' : 'Ganesh', 'age' : 29, 'state' : 'Karnataka' }
[Link]
import people
print(people.person1['name'])
print(people.person2['state'])
output:
Ravi
Karnataka
Packages:
A python package is a collection of several modules. Physically, a package is a folder containing modules and
maybe other folders that themselves may contain more folders and modules.
Conceptually, it's a namespace. This simply means that a package's modules are bound together by a package
name, by which they may be referenced. A package folder usually contains one file named __init__.py that
basically tells python that the folder is a package. The init file may be empty, or it may contain code to be
executed upon package initialization.
Random:
This module is used to generate pseudo random numbers.
Some of its methods are:
Seed(): Initialize the random number generator.
random() - Generates random number in the interval [0, 1]
randint(a, b) - Generates a random integer N such that a <= N <= b
choice(seq) - Returns a random element from a non-empty sequence
Ex:
import random
[Link](10)
print([Link]())
print("The random number between 1 and 10 is:",[Link](1, 10))
print("The random number between 5 and 25 is:",[Link](5, 25))
print("The random number between -10 and -2 is:",[Link](-10, -2))
s1="koppal"
print("The random value from string is:",[Link](s1))
t1 = (44,55,33,22,11)
print("The random value from tuple is:",[Link](t1))
l1 = ["apple", "banana", "cherry"]
print("The random value from list is:",[Link](l1))
[Link](l1)
print("The list after first shuffle:",l1)
[Link](l1)
print("The list after second shuffle:",l1)
output:
0.5714025946899135
The random number between 1 and 10 is: 7
The random number between 5 and 25 is: 20
The random number between -10 and -2 is: -10
The random value from string is: o
The random value from tuple is: 22
The random value from list is: banana
Emoji:
Emojis are very small digital images used to express an idea or emotion of the sender.
Emojis are very helpful in saving time and making the sender elaborate their mood easily.
Emojis are also very helpful for receivers as, with the help of emojis, they can easily understand with what
mood the sender has sent the message.
import emoji
print([Link](":thumbs_up:"))
print([Link](":grinning_face_with_big_eyes:"))
print([Link](":winking_face_with_tongue:"))
print([Link](":zipper-mouth_face:"))
print([Link](":grinning_face:"))
print([Link](":upside-down_face:"))
print([Link](":zany_face:"))
print([Link](":shushing_face:"))
output:
Week -11
NumPy Brief about NumPy module; NumPy arithmetic functions; NumPy array manipulation functions;
NumPy statistical functions; Pandas Introduction, series, data frame; Create dataframes; formatting
data; fundamental data frame operations;
NumPy:
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, Fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant.
It is open-source and can be used freely.
NumPy stands for Numerical Python.
Why Use NumPy:
In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray.
It provides a lot of supporting functions that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
Installing NumPy:
NumPy can be installed using the python package manger pip via command-line.
The command for installing NumPy is:
pip install numpy
Numpy Arrays:
We can create a NumPy ndarray object by using the array() function.
Ex:
import numpy as np
arr = [Link]([10, 23, 34, 46, 58])
print(arr)
print(type(arr))
output:
[10 23 34 46 58]
<class '[Link]'>
import numpy as np
a = [Link]([63, 16, 26])
b = [Link]([4, 5, 6])
c = [Link](a,b)
print(c)
print(a / b)
output:
[15.75 3.2 4.33333333]
[15.75 3.2 4.33333333]
mod() and remainder(): These functions are used to output the remainder of two arrays.
import numpy as np
a = [Link]([63, 16, 26])
b = [Link]([4, 5, 6])
c = [Link](a,b)
d = [Link](a,b)
print(c)
print(d)
output:
[3 1 2]
[3 1 2]
NumPy Statistical Functions:
The [Link]() and [Link]() functions are used to find the minimum and maximum of the array
elements along the specified axis respectively.
The function [Link]() is used to calculate the median of the multi-dimensional or one-dimensional
arrays.
The function [Link]() is used to calculate the mean of the multi-dimensional or one-dimensional
arrays.
The [Link]() function is used to find the weighted average along the axis of the multi-dimensional
arrays where their weights are given in another array.
import numpy as np
a = [Link]([[2,10,20],[80,43,31],[22,43,10]])
print("The minimum element among the array:",[Link](a))
Dept. of Computer Science and Engg. Page 100 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
Dept. of Computer Science and Engg. Page 101 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
a = [1, 7, 2]
srs = [Link](a)
print(srs)
output:
0 1
1 7
2 2
dtype: int64
DataFrames:
A Pandas DataFrame is a two-dimensional data structure, like a two-dimensional array, or a table
with rows and columns.
It can be created from a dictionary as below
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = [Link](data)
print(df)
output:
calories duration
0 420 50
1 380 40
2 390 45
DataFrames can also be created from files (and usually is) as shown below.
import pandas as pd
df = pd.read_csv('[Link]')
print(df)
The above code will load data from a Comma Separated file (CSV file) into a DataFrame and display it.
Dept. of Computer Science and Engg. Page 102 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
Week -12
Files Concept; features; file operations; Opening Files; Closing Files; Writing to Files; Reading to Files;
File methods; Working with files using data frame.
Files:
Files are named locations on disk to store related information.
These are used to permanently store data in a non-volatile memory (e.g. hard disk).
File handling in simple it means handling of files such as opening the file, reading, writing, and many other
operations.
A file operation takes place in the following order:
Open a file
Read or write
Close the file
Features of Files:
A file always has a name.
A file always takes up storage space.
A file is always saved in a certain format (.txt, .pdf, .ppt, .doc, .jpeg, etc).
A file contains information on when it was created and when it was last modified.
Files usually have access rights.
File Operations:
Opening files:
A file can be opened using the inbuilt function open() which returns a file object.
The open() function takes two parameters; filename, and mode.
The syntax is given below
fileobject = open(filename, mode)
Ex:
f = open(("[Link]", "r")
It is necessary that [Link] is in the same directory as the python program.
The mode in which the file is opened is specified as an additional argument while opening the file.
If no additional argument is present, then the file is opened in read mode.
A file can be opened in various modes:
'r' —> Read - Default value. Opens a file for reading, error if the file does not exist.
'a' —> Append - Opens a file for appending, creates the file if it does not exist.
Dept. of Computer Science and Engg. Page 103 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
'w' —> Write - Opens a file for writing, creates the file if it does not exist.
'x' —> Create - Creates the specified file, returns an error if the file exists.
We can specify if the file should be handled in text or binary mode:
't' —> Text - Default value. Text mode.
'b' —> Binary - Binary mode (e.g. for images).
In below example where a file is opened in write mode.
f = open('[Link]', 'w')
In below example where a file is opened in write mode and handled as binary:
f = open('[Link]', 'wb')
Reading Files:
The read() method is used for reading the content of the file.
Ex:
f = open("[Link]", "r")
print([Link]())
By default the read() method returns the whole text, but we can also specify how many characters we want
to read.
Ex:
f = open("[Link]", "r")
print([Link](10))
Returns the 10 first characters of the file:
readline():
We can also read files line by line by using the built in method readline().
Ex:
f = open("[Link]", "r")
print([Link]())
The above code will return the first line in [Link]
readlines():
We can also create a list of all the lines in an opened file by calling readlines().
Ex:
f = open("[Link]", "r")
l = [Link]()
print(type(l))
Dept. of Computer Science and Engg. Page 104 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
print(l[1])
Writing to Files:
Data can be written to files by using the argument 'a' or 'w' in the open() function.
'a' will append at the end of a file if it already exists.
'w' will overwrite the file if it already exists.
Both 'a' and 'w' will create a new file if it does not exist.
After a file is opened in one of the above write modes, the built-in method write() is used to write data to
the file.
Ex1:
f = open("[Link]", "a")
[Link](" Hello India")
The above code will add the text Hello India at the end of the file [Link]
Ex2:
f = open("[Link]", "w")
[Link]("Hello India")
The above code will overwrite [Link] so that the text Hello India is the only data on it.
Closing Files:
After working with a file, it is a good programming habit to close it.
In some cases, the changes made to the file may not show until the file is closed.
Files are closed using the built-in method close().
Ex:
f = open("[Link]")
print([Link]())
[Link]()
File Methods:
1. read():This method is used for reading the content of the file.
2. readline():This method reads one entire line from the file.
3. readlines(): This method reads entire file and return a list containing the lines.
4. write():This method writes a string to the file.
5. seek(): We can change our current file cursor (position) using the seek() method.
6. tell(): This method returns the current file cursor position (in number of bytes).
7. readable(): This method returns True if the file is readable otherwise it will return False.
Dept. of Computer Science and Engg. Page 105 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
8. writable(): This method returns True if the file is writable otherwise it will return False.
Dept. of Computer Science and Engg. Page 106 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
'IND_DAY': '1776-07-04'}}
columns = ('COUNTRY', 'POP', 'AREA', 'GDP', 'CONT', 'IND_DAY')
df = [Link](data=data, index=columns).T
df.to_csv('[Link]')
df = pd.read_csv('[Link]', index_col=0)
print(df)
output:
COUNTRY POP AREA GDP CONT IND_DAY
CHN China 1398.72 9596.96 12234.78 Asia NaN
IND India 1351.16 3287.26 2575.67 Asia 1947-08-15
USA US 329.74 9833.52 19485.39 [Link] 1776-07-04
Dept. of Computer Science and Engg. Page 107 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
Week-13
Error and Exception Handling: Python errors; exceptions: built in, user defined. How to catch
exceptions? Raising exceptions;
Errors:
Errors are the problems in a program due to which the program will stop the execution.
On the other hand, exceptions are raised when some internal events occur which changes the normal flow of
the program.
Two types of Error occur in python.
1. Syntax errors
2. Logical errors (Exceptions)
Syntax errors:
Syntax errors, also known as parsing errors and when the proper syntax of the language is not followed then
a syntax error will occur.
Logical errors (Exceptions):
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to
execute it.
Errors detected during execution are called exceptions.
Error Handling
Like many other programming languages, it possible to program how an error/exception that is raised during
runtime must be handled.
It is also possible to throw custom exceptions in a program.
HANDLING EXCEPTIONS
Exceptions are handled using the try, except, finally keywords.
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code regardless of the result of the try and except blocks.
During runtime, when an exception occurs, python will normally stop execution and generate an error
message. However if the line triggering the exception is in a try block, then instead of stopping and
generating an error message as usual, the code in the except block is executed.
Ex:
try:
print(x)
Dept. of Computer Science and Engg. Page 108 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
except:
print('This is a custom error message')
In the above code the variable x is not defined. Hence an exception will be triggered at runtime.
But this exception will only cause the code in except block to be executed. Hence the output of the above
code will be:
This is a custom error message
Common Exceptions
Exceptions triggered at runtime can be various types. A few common types are:
NameError: It is raised when a local or global name is not found.
Ex:
try:
a=x+20
except NameError:
print("Name Error")
TypeError: It is raised when an operation or function is applied to an object of inappropriate type.
Ex:
try:
a = "a" + 5
except TypeError:
print("Type Error")
IndexError: It is raised when a sequence subscript is out of range.
Ex:
try:
l=[10,20,30]
print(l[5])
except IndexError:
print("Index Error")
ZeroDivisionError – It is raised when the second argument of a division or modulo operation is zero.
Ex:
try:
x = 5/0
except ZeroDivisionError:
print("Zero Division Error")
Dept. of Computer Science and Engg. Page 109 Govt. Polytechnic Koppal
PYTHON PROGRAMMING 20CS31P
StopIteration – It is raised by built-in function next() to signal that there are no further items produced by
the iterator.
Ex:
try:
x = (i for i in [1, 2])
a = next(x) # a will be 1
b = next(x) # b will be 2
c = next(x)
except StopIteration:
print("Stop Iteration Error")
print('Hello')
except:
print('Something went wrong')
else:
print('Nothing went wrong')
Finally Block:
This block is executed regardless of whether or not an exception is triggered in the try block.
Ex:
try:
print(x)
except:
print('Something went wrong')
finally:
print('Finished error handling')
RAISING EXCEPTIONS:
It is possible to raise custom errors for some particular conditions in a program. The raise keyword is used
to do this.
Ex:
x = -1
if x < 0:
raise Exception('Only positive numbers are allowed')
We could also raise custom errors of a particular type.
Ex:
x = 'hello'
if type(x) != int:
raise TypeError('Only integers allowed')
Dept. of Computer Science and Engg. Page 111 Govt. Polytechnic Koppal