0% found this document useful (0 votes)
14 views80 pages

Python Notes

The document provides an introduction to Python programming, highlighting its features, uses, and advantages such as cross-platform compatibility and a large community. It covers fundamental concepts including variables, data types, operators, and basic input/output functions. Additionally, it explains Python's syntax, type conversion, and the importance of comments and identifiers in coding.
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)
14 views80 pages

Python Notes

The document provides an introduction to Python programming, highlighting its features, uses, and advantages such as cross-platform compatibility and a large community. It covers fundamental concepts including variables, data types, operators, and basic input/output functions. Additionally, it explains Python's syntax, type conversion, and the importance of comments and identifiers in coding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming 1BPLC105B

1. Introduction to Python Programming


Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. Python is dynamically-typed and garbage-
collected programming language. It was created by Guido van Rossum during
1985- 1990.

1.1 why to learn python?:


• Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.

1.2 What are the uses of Python?:


• Python can be used on a server to create web applications.
• Python can be used to connect to database systems.
• Python can be used to read and modify files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used to write machine learning programs
• Python can be used for rapid prototyping, or for production-ready
software development.

1.3 Features of Python:


Easy to Learn and Read: Python's syntax emphasizes readability, utilizing
clear, English-like keywords and indentation for code structure, making it
relatively easy to learn and understand compared to other languages.

Prepared By: Mr. Muralidhara B K 1


Python Programming 1BPLC105B

Interpreted Language: Python code is executed line by line by an


interpreter, eliminating the need for a separate compilation step. This
facilitates rapid development and debugging.

High-Level Language: Python abstracts away low-level details like memory


management and system architecture, allowing developers to focus on
problem-solving rather than intricate implementation details.

Dynamically Typed: Variable types are determined at runtime, meaning you


don't need to explicitly declare the data type of a variable before using it. This
adds flexibility and speeds up development.

Extensive Standard Library: Python comes with a vast standard library


offering modules and packages for various tasks, including web development,
data manipulation, network programming, and more, reducing the need to
write code from scratch.

Cross-Platform Compatibility: Python applications can run on various


operating systems (Windows, macOS, Linux) without significant code
modifications, thanks to its platform-independent nature.

Free and Open Source: Python is freely available for use and distribution,
and its open-source nature encourages community contributions and ongoing
development.

Extensible and Embeddable: Python can be extended with modules written


in other languages (like C/C++) for performance-critical tasks and can also be
embedded within other applications as a scripting language.

Large and Active Community Support: Python boasts a massive and active
global community, providing extensive resources, documentation, and support
for learners and developers.

Prepared By: Mr. Muralidhara B K 2


Python Programming 1BPLC105B

GUI Programming Support: Libraries like Tkinter, PyQt, and Kivy enable
the development of graphical user interfaces (GUIs) for desktop applications.

Suitable for Various Applications: Python is widely used in web


development (Django, Flask), data science and machine learning (NumPy,
Pandas, scikit-learn), automation, scripting, scientific computing, and more.

1.4 Python Comments:


Comments are hints that we add to our code to make it easier to understand.
Python comments start with #. Comments are completely ignored and not
executed by code editors. The hash (#) symbol is used to write a single-line
comment. A single-line comment starts with # and extends up to the end of
the line.

1.5 Python Variables:


In programming, a variable is a container (storage area) to hold data. For
example,

Here, number is a variable storing the value 10. As we can see from the above
example, we use the assignment operator (=) to assign a value to a variable.
The value of a variable can be changed at any time. For example,

Prepared By: Mr. Muralidhara B K 3


Python Programming 1BPLC105B

multiple varibales can also beassigned values at the same time. For example,

Same value can also be assigned to multiple variables. For example,

1.6 Python Literals:


Literals are representations of fixed values in a program. They can be
numbers, characters, or strings, etc. For example, 'Hello, World!', 12, 23.0, 'C',
etc. Literals are often used to assign values to variables or constants. For
example,

1.7 Python Type Conversion:


Type conversion is the process of converting data of one type to another. For
example: converting ‘int’ data to ‘str’.
There are two types of type conversion in Python:
• Implicit Conversion - automatic type conversion
• Explicit Conversion - manual type conversion

Implicit Conversion: In certain situations, Python automatically converts one


data type to another. This is known as implicit type conversion.

Prepared By: Mr. Muralidhara B K 4


Python Programming 1BPLC105B

Explicit Conversion: In Explicit Type Conversion, users convert the data type
of an object to required data type. We use the built-in functions like int(),
float(), str(), etc to perform explicit type conversion. This type of conversion is
also called typecasting because the user casts (changes) the data type of the
objects.

1.8 Python basic output:


In Python, we can simply use the print() function to print output. Synatx of
print function is:

where
object => is the value to be printed
sep(optional) => character that separates multiple values (default: ‘ ‘)
end (optional) => character that is placed at the end of output (default: ‘\n’)
file (optional) => file where data is to be stored (default: [Link])
flush (optional) => specifies if the output is to be flushed or buffered (default:
False)
For example,

Prepared By: Mr. Muralidhara B K 5


Python Programming 1BPLC105B

Sometimes we would like to format our output to make it look attractive. This
can be done by using the [Link]() method. For example,

Here, the curly braces {} are used as placeholders. We can specify the order
in which they are printed by using numbers (tuple index). For example,

Another way to format output is through F-string. F-string allows you to


format selected parts of a string. To specify a string as an f-string, simply put
an f in front of the string literal. For example,

1.9 Python Basic Input:


In python, we can use input() function to read input from the user. Synatx of
input function is:

Prepared By: Mr. Muralidhara B K 6


Python Programming 1BPLC105B

where
prompt => string we would like to display on the screen before taking input.
Note that the input function always gives input as a string. For example,

The input given has to be converted using type converter functions like int(),
float(), etc

1.10 Keywords:
Keywords are predefined, reserved words used in Python programming that
have special meanings to the interpreter. We cannot use a keyword as a
variable name, function name, or any other identifier. They are used to define
the syntax and structure of the Python language.

All the keywords except True, False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.

1.11 Identifiers:
Identifiers are the name given to variables, classes, methods(functions), etc.
Certain rules have to be followed while creating identifiers:
1. Identifiers cannot be a keyword.
2. Identifiers are case-sensitive.

Prepared By: Mr. Muralidhara B K 7


Python Programming 1BPLC105B

3. It can have a sequence of letters and digits. However, it must begin with
a letter or _. The first letter of an identifier cannot be a digit.
4. Whitespaces are not allowed.
5. We cannot use special symbols like !, @, #, $, and so on.

Identifier Valid / Invalid Reason


marks Valid Follows all rules
marks1 Valid Follows all rules
marks_1 Valid Follows all rules
1marks Invalid Breaks rule 3
1 marks Invalid Breaks rule 4
marks#1 Invalid Breaks rule 5
return Invalid Breaks rule 1

1.12 Data Types:


Python includes several built-in data types to store and manipulate different
kinds of data. These can be broadly categorized as follows:
• Numeric Types
• Sequence Types
• Mapping Type
• Set Type
• Boolean Type
• Binary Types

Numeric Types: it represents numerical data and has 3 categories in it:


integer, floating-point and complex number.
• Integer (int): Represents whole numbers, positive or negative, without
a decimal point.
• Floating-Point (float): Represents numbers with a decimal point.
• Complex Number (complex): Represents numbers with a real and an
imaginary part.

Prepared By: Mr. Muralidhara B K 8


Python Programming 1BPLC105B

Sequence Types: it represents a sequence or collection of elements and has 4


categories in it: String, list, tuple and range.
• String (str): Represents a sequence of characters, enclosed in single or
double quotes.
• List (list): Represents an ordered, mutable collection of items. Items
can be of different data types.
• Tuple (tuple): Represents an ordered, immutable collection of items.
• Range (range): Represents an immutable sequence of numbers, often
used for looping

Mapping Type: it represents data that has 2 parts: a key and a value. This
has only one category: dictionary.
• Dictionary (dict): Represents an unordered collection of key-value
pairs. Keys must be unique and immutable.

Prepared By: Mr. Muralidhara B K 9


Python Programming 1BPLC105B

Set Types: it represents a collection of unique elements. It has 2 categories in


it: set and frozen-set.
• Set (set): Represents an unordered, mutable collection of unique items.
• Frozen-set (frozenset): it is an immutable version of a set. Like a
regular set, it is an unordered collection of unique elements. However,
once a frozenset is created, its elements cannot be added, removed, or
changed

Boolean Type: it represents truth values and has only one category: bool.
• Bool: its value can be only either True or False.

Binary Types: it represents binary data and has 3 categories: bytes,


bytearray and memoryview.
• Bytes : Represents an immutable sequence of bytes. It is created by
prefixing a string literal with ‘b’. It is Ideal for data that should not be
modified after creation
• Bytearray: A mutable sequence of bytes. It is Suitable for scenarios
where the binary data needs to be modified in place.
• Memoryview: It provides a view into the memory of another binary
object (like bytes or bytearray) without creating a copy.

Prepared By: Mr. Muralidhara B K 10


Python Programming 1BPLC105B

2. Python Operators
Operators are special symbols that perform operations on variables and
values. The different types of operators in python are:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Special Operators
2.1 Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.

Operator Operation Example


+ Addition 1+3=4
- Subtraction 3–1=2
* Multiplication 2*3=6
/ Division 7 / 2 = 3.5
// Floor Division 7/2=3
% Modulo 8%3=2
** Power 2 ** 3 = 8

2.2 Assignment Operators:


Assignment operators are used to assign values to variables. For example,

Python supports different types of assignment operators:

Operator Name Example Equivalent Code


+= Addition Assignment A += 2 A=A+2
-= Subtraction Assignment A -= 2 A=A-2
*= Multiplication Assignment A *= 2 A=A*2
/= Division Assignment A /= 2 A=A/2
%= Remainder Assignment A %= 2 A=A%2
**= Exponent Assignment A **= 2 A = A ** 2

Prepared By: Mr. Muralidhara B K 11


Python Programming 1BPLC105B

2.3 Comparision Operators:


Comparison operators compare two values / variables and return a boolean
result: True or False.

Operator Meaning Example Return Value


2 == 2 True
== Is Equal To
2 == 3 False
2 != 3 True
!= Not Equal To
2 != 2 False
2>3 False
> Greater Than
3>2 True
2 >= 3 False
>= Greater Than or Equal To 3 >= 2 True
3 >= 3 True
2<3 True
< Less Than
3<2 False
2 <= 3 True
<= Less Than or Equal To 3 <= 2 False
3 <= 3 True

2.4 Logical Operators:


Logical operators are used to check whether an expression is True or False.
They are used in decision-making. Python supports 3 logical operators: and, or
& not. The general working (Truth Table) of these operators is given in the
following table:

A B A and B A or B Not A Not B


False False False False True True
False True False True True False
True False False True False True
True True True True False False

Prepared By: Mr. Muralidhara B K 12


Python Programming 1BPLC105B

2.5 Bitwise Operators:


Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name. Python supports 6 bitwise operators: &
(bitwise AND), | (bitwise OR), ~(bitwise NOT), ^(bitwise XOR), >>(bitwise
right-shift), <<(biwise left-shift).

2.6 Special Operators:


Python language offers some special types of operators like the identity
operator and the membership operator.

Prepared By: Mr. Muralidhara B K 13


Python Programming 1BPLC105B

Identity Operators: “is” and “is not” are the two identity operators in
python. “is” and “is not” are used to check if two values are located at the
same memory location. It's important to note that having two variables with
equal values doesn't necessarily mean they are identical.

Membership operators: In Python, in and not in are the membership


operators. They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).

2.7 Operator Precedence:


The combination of values, variables, operators, and function calls is termed
as an expression. The Python interpreter can evaluate a valid expression. To
evaluate these types of expressions there is a rule of precedence in Python. It
guides the order in which these operations are carried out.
The operator precedence in Python is listed in the following table. It is in
descending order (upper group has higher precedence than the lower ones).

Prepared By: Mr. Muralidhara B K 14


Python Programming 1BPLC105B

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, unary minus, bitwise not
*, /, //, % Multiplication, division, floor division,
modulus
+, - Addition, subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
is, is not, in, not in, ==, !=, >, Comparision, identity and membership
>=, <, <=, operators
not Logical NOT
and Logical AND
or Logical OR

2.8 Associativity of operators:


Associativity is the order in which an expression is evaluated that has multiple
operators of the same precedence. When two operators have the same
precedence, associativity helps to determine the order of operations. Almost
all the operators have left-to-right associativity. Exponent operator (**) has
right-to-left associativity in Python.

Prepared By: Mr. Muralidhara B K 15


Python Programming 1BPLC105B

3. Conditional Statements
Conditional statements in Python allow for the execution of specific code
blocks based on whether a given condition evaluates to True or False. These
statements are fundamental for controlling the flow of a program and enabling
decision-making. Python supports 3 types of conditional statements: if, if-else
and if-elif-else.
3.1 if statement
An if statement executes a block of code only when the specified condition is
True. It syntax is:

where the ‘condition’ is a boolean expression. If condition evaluates to True,


the body of the if statement is executed. If condition evaluates to False, the
body of the if statement will be skipped from execution.

3.2 if-else:
An if statement can have an optional else clause. The else statement executes
if the condition in the if statement evaluates to False. The syntax is:

Prepared By: Mr. Muralidhara B K 16


Python Programming 1BPLC105B

where the ‘condition’ is a boolean expression. If condition evaluates to True,


the body of the if statement is executed. If condition evaluates to False, the
body of the else statement is executed.

3.3 If-elif-else:
The if-elif-else statement allows for checking multiple conditions sequentially.
The syntax is:

Prepared By: Mr. Muralidhara B K 17


Python Programming 1BPLC105B

where ‘condition1’, ‘condition2’ are boolean expression. If ‘condition1’


evaluates to True, the ‘code block 1’ is executed. If instead ‘condition2’
evaluates to True, the ‘code block 2’ is executed. If both ‘condition1’ and
‘condition2’ are False, then ‘code block 3’ is executed. Note that only one
block of code is executed at any time.

Prepared By: Mr. Muralidhara B K 18


Python Programming 1BPLC105B

Prepared By: Mr. Muralidhara B K 19


Python Programming 1BPLC105B

4. Looping Statements
looping statements are used to repeatedly execute a block of code. Python
provides two types of looping statements: while and for.

4.1 while loop:


The while loop repeatedly executes a block of code as long as the specified
condition is true. It continues to loop until the condition becomes false. The
syntax is:

where ‘condition’ is a boolean expression. The ‘body of while loop’ executes as


long as ‘condition’ is True. When the ‘condition’ becomes False ‘body of while
loop’ will not be executed and the loop is terminated.

Care must be taken while using the ‘while’ loop as it may create an ‘infinite
loop’ which runs forever until the system crashes.

4.2 For loop:


In Python, the for loop is used for iterating over a sequence (such as a list,
tuple, dictionary, set, or string) or other iterable objects. It allows you to
execute a block of code once for each item in the sequence. The syntax is:

Prepared By: Mr. Muralidhara B K 20


Python Programming 1BPLC105B

where ‘sequence’ must be an iterable type. In each iteration, one element


from the ‘sequence’ is copied to ‘val’ and the body of the loop is executed. The
loop ends after the body of the loop is executed for the last item in the
‘sequence’.

4.3 The break statement:


The break statement in Python is used to terminate a loop prematurely. When
break is encountered within a for loop or a while loop, the loop is immediately
exited, and program execution continues with the statement following the
loop.

Prepared By: Mr. Muralidhara B K 21


Python Programming 1BPLC105B

4.4 The continue statement:


The continue statement is used to skip the current iteration of the loop and
immediately proceed to the next iteration.

4.5 Nested for loop:


A nested loop in Python refers to the placement of one or more loops inside
the body of another loop. In a nested loop, the inner loop is executed once for
each iteration of the outer loop.

4.6 The pass statement:


The pass statement in Python is a null operation; it does nothing when
executed. Its primary purpose is to act as a placeholder where Python syntax
requires a statement, but no action or code logic is intended or available at
that moment.

Prepared By: Mr. Muralidhara B K 22


Python Programming 1BPLC105B

Prepared By: Mr. Muralidhara B K 23


Python Programming 1BPLC105B

5. Functions
A function is a block of code that performs a specific task. They promote code
organization, reusability, and modularity, adhering to the "Don't Repeat
Yourself" (DRY) principle.

5.1 Types of functions:


based on the availability of functions, they are classified as: built-in functions,
module functions and user-defined functions.

• Built-in functions: these are readily available in Python without


explicit import. For example, print(), input(), len(), format(), etc
• Module functions: These reside within modules and must be imported
before use. For example, sqrt() from math module, random() from
random module, etc
• User-defined functions: These are created by the programmer to
achieve specific functionalities within their code.

5.2 Creating a user-defined function:


Functions are defined using the def keyword, followed by the function name,
parentheses (which may contain parameters), and a colon. The function body
is indented below the definition.

Where,
• function_name : an identifier for the function which follows python’s
naming convention
• parameters: Placeholders in the function definition that receive values
(arguments) when the function is called
• body: The block of code that executes when the function is called.

Prepared By: Mr. Muralidhara B K 24


Python Programming 1BPLC105B

Based on the structure of the function, a user-defined function can be


classified as: function without parameters, function with parameters, function
without a return value and function with a return value

Creating a user-defined function


Without return value With return value

Without
parameters

With
parameters

5.3 Calling a function:


A function will not execute until it is called. To execute the code within a
function, you call it by its name followed by parentheses, passing any required
arguments.

Calling a user-defined function


Without return value With return value

Without
parameters

With
parameters

Prepared By: Mr. Muralidhara B K 25


Python Programming 1BPLC105B

5.4 return statement:


In Python, the return statement serves to exit a function and send a value or
values back to the calling code.
Characteristics of return statement:
• Exits the function: When a return statement is encountered during
function execution, the function immediately terminates, and control
returns to the point where the function was called. Any code after the
return statement within that function will not be executed.
• Returns a value: The return statement can be followed by an
expression, whose evaluated value will be sent back to the caller. This
value can be of any data type, including numbers, strings, lists,
dictionaries, or even other functions.
• Multiple return statements: A function can contain multiple return
statements, often within conditional blocks (e.g., if/else). However, only
one return statement will be executed during a single function call, as
the function exits upon the first return encountered.
• Returning multiple values: Python functions can return multiple
values by listing them after the return keyword, separated by commas.
These values are then returned as a tuple.

5.5 default arguments:


In Python, default arguments allow you to assign a default value to a function
parameter. If a value for that parameter is not provided during the function
call, the default value is used. If a value is provided, it overrides the default.

Prepared By: Mr. Muralidhara B K 26


Python Programming 1BPLC105B

Default arguments are defined in the function signature by assigning a value


to the parameter using the assignment operator (=).

A function can have both non-default and default arguments in it. All
parameters with default arguments must appear after any non-default
arguments in the function definition.

5.6 Keyword arguments:


A function can be called by explicitly naming the parameters during function
call. This allows the parameters to be passed in different order than specified
in the function definition.

Prepared By: Mr. Muralidhara B K 27


Python Programming 1BPLC105B

6. Lists
A list is an ordered collection of elements. It allows us to store multiple values
in a single variable.
Characteristics of list:
• ordered: elements maintain a specific order
• mutable: list can be modified after creation. Elements can be added,
removed, or changed.
• Allows duplicate: the same value can appear multiple times within a
single list
• holds different data types: a single list can store elements of different
data types
• index-based: elements are accessed using zero-based indexing, where
first element is at index 0, second at index 1 and so on. Negative
indexing can also be used, where last element is at index -1 and so on.
6.1 creating a list:
a list can be created in multiple ways as shown in the following code:

6.2 accessing elements of a list:


As the elemets of the list are index-based, they can be accessed using those
indices.

Prepared By: Mr. Muralidhara B K 28


Python Programming 1BPLC105B

To access all the elements in a single-statement for loop can be used:

6.3 Operators on list:


The 3 operators that can be applied on a list are: + (concatenation), *
(repetition) and : (slice) operators.
The ‘+’ operator generates a new list from multiple lists:

The ‘*’ operator generates a new list by repeating elements of a list:

The ‘:’ operator is used to create a sub-list from an existing list. The syntax of
slice operator is:

Prepared By: Mr. Muralidhara B K 29


Python Programming 1BPLC105B

where
• start : index of the first element (optional), (default is 0)
• end: index where slicing ends (optional), (default is end of list)
• step: gap between elements to be selected (optional), (default is 1)

6.4 List functions:


i) len() : used to find the number of elements in a list

ii) append(): used to add an element at the end of a list

Prepared By: Mr. Muralidhara B K 30


Python Programming 1BPLC105B

iii) insert() : used to add an element at a specific position

iv) extend(): used to add multiple elements at the end of a list

v) pop(): used to remove and return the element at the given index

Prepared By: Mr. Muralidhara B K 31


Python Programming 1BPLC105B

vi) remove(): used to remove a specified value from a list

vii) clear(): used to remove all elements from a list

viii) index(): used to find the index of an element

ix) count(): used to find the number of occurence of an element

Prepared By: Mr. Muralidhara B K 32


Python Programming 1BPLC105B

x) reverse(): used to reverse the elements of a list

xi) sort(): used to arrange the elements of a list in ascending / descending


order

xii) copy(): used to make a copy of the elements of a list

Prepared By: Mr. Muralidhara B K 33


Python Programming 1BPLC105B

7. Tuples

A tuple is a collection of elements just like a list. The primary difference is that
once a tuple is created it cannot be modified. A tuple is created using ().
characteristics of a tuple:
• ordered: elements maintain a specific order
• immutable: list cannot be modified once created
• Allows duplicate: the same value can appear multiple times within a
single tuple
• holds different data types: a single tuple can store elements of
different data types
• index-based: elements are accessed using zero-based indexing, where
first element is at index 0, second at index 1 and so on. Negative
indexing can also be used, where last element is at index -1 and so on.

7.1 creating a tuple:


A tuple can be created in multiple ways as shown in the following code:

7.2 Accessing elements of a tuple:


As the elements of a tuple are index-based, they can be accessed using those
indicies.

Prepared By: Mr. Muralidhara B K 34


Python Programming 1BPLC105B

To access all the elements one at a time for loop can be used:

7.3 Operators on tuple:


The 3 operators that can be apllied on a tuple are: + (concatenation), *
(repetition), : (slice). These operators doesn’t modify the orginal tuple, instead
they create a new tuple.

7.4 Tuple functions:

Prepared By: Mr. Muralidhara B K 35


Python Programming 1BPLC105B

i) count(): used to find the number of times an element is repeated in a tuple.

ii) index(): used to find the index of an element if it is present in the tuple.

Prepared By: Mr. Muralidhara B K 36


Python Programming 1BPLC105B

8. Strings
In Python, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
8.1 Creating a string:
A string can be created in python by enclosing characters in single-quotes (‘ ’),
double-quotes(“ “) or triple-quotes (‘’’ ‘’’ or “”” “””).

Once a string is created its individual characters cannot be modified (i.e,


immutable). Any operation that appears to modify a string actually creates a
new string.
8.2 Accessing elements of a string:
Characters in a string can be accessed individually using indices. The
individual characters can be accessed using zero-based indexing:

The characters can also be accessed using negative-indexing (starts from -1):

Prepared By: Mr. Muralidhara B K 37


Python Programming 1BPLC105B

8.3 Operators on strings:


The 3 operators that can be apllied on a string are: + (concatenation), *
(repetition), : (slice). These operators doesn’t modify the orginal string,
instead they create a new string.

The == (equality) operator can be used to check if 2 strings are same or not.

8.4 String functions:


The string functions can be categorized as: case conversion functions,
searching & finding functions, manipulation functions and validation
functions.

Prepared By: Mr. Muralidhara B K 38


Python Programming 1BPLC105B

i) case conversion functions


upper(): converts all lowercase alphabets to uppercase.

lower(): converts all uppercase alphabets to lowercase.

capitalize(): converts only the first letter to uppercase while keeping other
letters to lowercase.

title(): converts first letter of every word to uppercase while keeping other
letters to lowercase.

swapcase(): converts all uppercase alphabets to lowercase and vice versa.

ii) searching & finding functions:


find(): used to find the location of a string in another string. If the search is
successful, it returns the index where the string was found. If the search is
unsuccessful, it returns -1. The syntax is:

Prepared By: Mr. Muralidhara B K 39


Python Programming 1BPLC105B

index(): used to find the location of a string in another string. If the search is
successful, it returns the index where the string was found. If the search is
unsuccessful, it gives an error. The syntax is similar to find() function.

Count(): used to find the number of occurence of a substring in another


string. If the substring is found, it returns the number of times it occurs in the
string. If the substring is not found, it returns 0. The syntax is similar to find()
function.

Startswith(): used to check if a string begins with a specific substring or not.


If the string begins with a specified substring, it returns True, else returns
False. The syntax is similar to find() function.

Prepared By: Mr. Muralidhara B K 40


Python Programming 1BPLC105B

Endswith(): used to check if a string ends with a specific substring or not. If


the string ends with a specified substring, it returns True, else returns False.
The syntax is similar to startswith() function.

iii) manipulation functions:


The string manipulation functions doesn’t modify the original string instead
they create a new string.
Replace(): used to replace one or more occurences of a substring with
another substring. The syntax is:

Prepared By: Mr. Muralidhara B K 41


Python Programming 1BPLC105B

lstrip(): used to remove leading (starting) whitespaces or a specified char


from a string. The syntax is:

rstrip(): used to remove trailing (ending) whitespaces or a specified char


from a string. The syntax is similar to lstrip() function.

Strip(): used to remove both leading (starting) as well as trailing (ending)


whitespaces or a specified char from a string. The syntax is similar to lstrip() /
rstrip() function.

Prepared By: Mr. Muralidhara B K 42


Python Programming 1BPLC105B

Split(): returns a list of substrings by dividing(splitting) the string at a


specified character. The syntax is:

join(): used to join (concatenate) any number of strings with a specified


character. The syntax is:

Prepared By: Mr. Muralidhara B K 43


Python Programming 1BPLC105B

partition(): partitions (divides) a string into 3 parts using the given seperator
and returns as a 3-tuple. The 3 parts are: part before the seperator, seperator
and part after the seperator. If the seperator is not found, it returns 3-tuple
containing original string and 2 empty strings. The syntax is:

iv) validation functions:


isalpha(): checks if the string contains only alphabets. If the string contain
only alphabets then it returns True else returns False.

isdigit(): checks if the string contains only digits. If the string contain only
digits then it returns True else returns False.

islower(): checks if the alphabets in the string are in lowercase or not. If all
the alphabets are in lowercase then it returns True else returns False.

Prepared By: Mr. Muralidhara B K 44


Python Programming 1BPLC105B

isupper(): checks if the alphabets in the string are in uppercase or not. If all
the alphabets are in uppercase then it returns True else returns False

isalnum(): checks if the string is made up of only alphabets and/or digits. If


the string is made up of only alphabets and/or digits then it returns True else
returns False.

Prepared By: Mr. Muralidhara B K 45


Python Programming 1BPLC105B

9. Dictionary
A Python dictionary is a collection of items, similar to lists and tuples.
However, unlike lists and tuples, each item in a dictionary is a key-value pair
(consisting of a key and a value).

Characteristics of a Dictionary:
• Key-Value Pairs: Each item in a dictionary consists of a key and its
corresponding value, separated by a colon (:).
• Curly Braces: Dictionaries are defined by enclosing key-value pairs
within curly braces {}.
• Unique Keys: Dictionary keys must be unique and immutable (e.g.,
strings, numbers, tuples). If duplicate keys are provided, the last
assigned value for that key will overwrite previous ones.
• Mutable Values: Dictionary values can be of any data type and can be
duplicated.
• Ordered: From Python 3.7 onwards, dictionaries maintain insertion
order, meaning the order in which items are added is preserved.
• Efficient Operations: Dictionaries are implemented using hash tables,
allowing for efficient (average constant time) operations like searching,
inserting, and deleting items.

9.1 Creating a Dictionary:


A dictionary is created by specifying its element within curly braces ({}). Each
element will have 2 parts: a key and a value. The key and value are seperated
by a colon(:). Keys must be unique, i.e., duplicates not allowed. Values can be
duplicated. Keys must be of immutable type whereas values can be of any
type.

Prepared By: Mr. Muralidhara B K 46


Python Programming 1BPLC105B

9.2 Accessing elements of a dictionary:


We can access the value of a dictionary item by placing the key inside square
brackets.

To access each element of a dictionary one at a time, we can use for loop as
follows:

9.3 Dictionary methods:


i) update() : The update() method updates the dictionary with the elements
from another dictionary object or from an iterable of key/value pairs. It can

Prepared By: Mr. Muralidhara B K 47


Python Programming 1BPLC105B

also be used to update/change the value of an existing key. The syntax of


update method is:

ii) setdefault() : adds a key-value pair only if the key is not found. If the key
already exists, it will not add the key-value pair. The syntax is:

iii) pop() : It is used to remove and return an element (key-value pair) if the
key is found. If the key is not found then the default-value is returned. The
syntax is :

Prepared By: Mr. Muralidhara B K 48


Python Programming 1BPLC105B

iv) popitem(): It removes the last / latest element from the dictionary. The
syntax is:

v) clear() : Removes all elements from the dictionary.

Prepared By: Mr. Muralidhara B K 49


Python Programming 1BPLC105B

vi) get(): it returns a value associated with a key, if the key is found. If the key
is not found it retuns the default-value. Its syntax is:

vii) keys(): returns a list of all the keys present in the dictionary.

viii) values(): returns a list of all the values present in a dictionary.

Prepared By: Mr. Muralidhara B K 50


Python Programming 1BPLC105B

ix) items(): returns a list of tuples containing all the key-value pairs as (key,
value).

x) copy(): returns a shallow copy of the dictionary.

Prepared By: Mr. Muralidhara B K 51


Python Programming 1BPLC105B

10. Files
A file is a named location used for storing data. For example, [Link] is a file
that is always used to store Python code. Python provides various functions to
perform different file operations, a process known as File Handling.

10.1 Opening a file:


In Python, we need to open a file first to perform any operations on it. To open
a file we use the open() method. Python allows us to open files in different
modes (read, write, append, etc.), based on which we can perform different
file operations. The different modes are:

Mode Description
r Open a file in reading mode
w Open a file in writing mode
x Open a file in exclusive creation
a Open a file in appending mode (adds content at the end of file)
t Open a file in text mode
b Open a file in binary mode
+ Open a file in both read and write mode

10.2 Closing a file:


When we are done performing operations on the file, we need to close the file
properly. We use the close() function to close a file in Python. Closing a file will
free up the resources that are tied to the file. Hence, it is a good programming
practice to always close the file.

In Python, there is a better way to open a file using with...open. The


with...open automatically closes the file, so we don't have to use the close()
function.

10.3 Reading a file:


The content of a file can be read using read(), readline() or readlines()
methods.
The read() method read the complete contents of the file into a string.
The readline() method reads one line at a time.

Prepared By: Mr. Muralidhara B K 52


Python Programming 1BPLC105B

The readlines() method reads all the lines of a file as a list of lines.

To open a file located at some other location, we have to give the complete
path of the file to the open() method.

To give a file’s complete path which is independent of operating system, we


can make use of the “os” module available in python. The ‘join’ method of the
‘os’ module formats the location of the file according to operating system
being used.

Prepared By: Mr. Muralidhara B K 53


Python Programming 1BPLC105B

10.4 writing to a file:


Data can be stored in a file using either write() or writeline() method. When a
file is opened in write mode, the old content of the file is deleted.
The write() method writes a string into a file.
The writelines() method writes a list of lines to a file.

10.5 adding content to a file:


content can be added to a file without destroying the old content by opening a
file in ‘append’ mode.

10.6 reading content from the web:


A file that exist on the web can be read and stored on a local file using either
‘urllib’ or ‘requests’ module.

Prepared By: Mr. Muralidhara B K 54


Python Programming 1BPLC105B

Prepared By: Mr. Muralidhara B K 55


Python Programming 1BPLC105B

11. Numpy

NumPy (Numerical Python) is a fundamental, open-source Python library for


efficient numerical computing. It provides a powerful multidimensional array
object called “ndarray”, which is essential for data science, machine learning,
and scientific computing in Python.
The following table shows the difference between a pyhton list and numpy
array:

Feature Numpy Array Python List


Data Type Homogeneous (all elements Heterogeneous (can
must be of same type) contain mixed data types)
Performance Faster for numerical and Slower for large numeric
vectorized operations workloads due to overhead
Memory More efficient, data stored Less efficient, stores
contiguously in memory pointers to objects
scattered in memory
Size Fixed size upon creation Dynamic, can grow or
shrink easily
Functionality Optimized for advanced General-purpose, with built-
math, linear algebra, and in methods for
statistics insertion/deletion/sorting
Availability Requires importing the Built-in to core Python
numpy library

To use the Numpy library, it needs to be imported into the file as:
import numpy as np

11.1 Numpy Datatypes:


A data type is a way to specify the type of data that will be stored in an array.
NumPy provides us with several built-in data types to efficiently represent
numerical data.

Category Numpy Data Type


Signed integer int8, int16, int32, int64
Unsigned integer uint8, uint16, uint32, uint64
Floating-point float32, float64
Complex number complex32, complex64

Prepared By: Mr. Muralidhara B K 56


Python Programming 1BPLC105B

11.2 creating 1-D array in numpy:


A 1-D array can be created in multiple ways in numpy as follows:

11.3 creating 2-D arrays in numpy:


A 2-D array can be created in multiple ways numpy as follows:

11.4 converting arrays using reshape():


A 1-D array can be converted into 2-D array and vice-versa using the reshape()
method as follows:

Prepared By: Mr. Muralidhara B K 57


Python Programming 1BPLC105B

11.5 Numpy array attributes (properties):


NumPy arrays possess several key properties (attributes) that provide
information about their structure, size, and data. These attributes are
essential for understanding and manipulating arrays efficiently in numerical
computing.

Attribute Description
ndim Gives the number of dimensions in the array, also
known as its rank
shape Gives the size of array in each dimension
size Gives the total number of elements in the array
dtype Gives the data type of each element of the array
itemsize Gives the size of each element in bytes
nbytes Gives the total number of bytes consumed by all
elements in the array
T Transpose of a 2-D array

Prepared By: Mr. Muralidhara B K 58


Python Programming 1BPLC105B

11.6 Slicing an array:


Slicing in NumPy is used to extract a subset of elements from an array based
on a specified range of indices. It uses the same syntax as Python lists, but
extends it to N dimensions to select portions of multi-dimensional arrays
efficiently. The basic syntax for slicing is array[start : stop : step].

Prepared By: Mr. Muralidhara B K 59


Python Programming 1BPLC105B

11.7 Masking:
Masking is a powerful technique in numpy which is used to select, filter, or
modify elements in an array based on a condition.

Prepared By: Mr. Muralidhara B K 60


Python Programming 1BPLC105B

11.8 Broadcasting:
Broadcasting is a mechanism in NumPy that allows you to perform arithmetic
operations on arrays of different shapes and sizes without explicitly reshaping
or creating unnecessary copies of the data. Instead, NumPy implicitly expands
the smaller array to match the shape of the larger array for the duration of the
operation, leading to efficient, vectorized code.

2 rules of broadcasting:
• only dimensions of size 1 can be stretched (expanded)
• dimensions are compared from the last to the first before doing any
operation

11.9 Changing data type of an array:


The data type of an array can be changed while creating the array, as well as
after creating the array as follows:

Prepared By: Mr. Muralidhara B K 61


Python Programming 1BPLC105B

Prepared By: Mr. Muralidhara B K 62


Python Programming 1BPLC105B

12. Modules
A module is a file containing Python definitions and statements intended for
use in other Python programs. At its simplest, any file saved with a .py
extension is a module. It can define functions, classes, and variables.

12.1 Types of Modules:


Python features several types of modules:
• Built-in Modules: These are pre-installed and come bundled with the
Python interpreter, such as math, os, and random.
• User-Defined Modules: These are modules you create yourself to
organize your project's code.
• External (Third-Party) Modules: These are modules and packages
created by other developers that you install using a package manager
like pip (e.g., NumPy, Pandas, Requests).

Python's standard library is extensive. Some frequently used built-in modules


include:
• os: Provides a way to interact with the operating system, useful for file
and directory operations.
• sys: Provides access to system-specific parameters and functions related
to the Python interpreter.
• math: Implements various mathematical functions and constants (e.g.,
[Link](), [Link]).
• random: Used to generate pseudo-random numbers and shuffle
sequences.
• datetime: Supplies classes for manipulating dates and times.
• json: Provides functionality to work with JSON (JavaScript Object
Notation) data.
• re: Offers powerful regular expression facilities for pattern matching in
strings.

To use any module, you need to import it using the import statement. For eg.,
math module can be imported as: import math

Prepared By: Mr. Muralidhara B K 63


Python Programming 1BPLC105B

12.2 random module:


The Python random module is a built-in library used for generating pseudo-
random numbers and performing random operations like selecting items from
sequences or shuffling lists.
To use any of its functions, you must first import the module: import random

12.3 time module:


The Python time module provides a set of functions for working with time-
related tasks, such as getting the current time, measuring elapsed time,
formatting time strings, and pausing program execution.
The module handles time in three main ways: as a floating-point number
(seconds since the epoch), as a struct_time object (a named tuple with time
components), or as a formatted string.
To use any of its functions, you must first import the module: import time

Prepared By: Mr. Muralidhara B K 64


Python Programming 1BPLC105B

12.4 math module:


The math module in Python is a built-in standard library module that provides
access to common mathematical functions and constants. It is used for
operations with real floating-point numbers and does not support complex
numbers. To use any function or constant from the module, you must first
import it in your Python script: import math

Prepared By: Mr. Muralidhara B K 65


Python Programming 1BPLC105B

12.5 Creating user-defined modules:


All we need to do to create our own modules is to save our script as a file with
a .py extension. For example to create a module called ‘utilities’, we create a
file called ‘[Link]’ as follows:

Prepared By: Mr. Muralidhara B K 66


Python Programming 1BPLC105B

We can use the ‘utilities’ module as follows:

12.6 Namespaces:
A namespace is a collection of identifiers that belong to a module, or to a
function. Each module has its own namespace, so we can use the same
identifier name in multiple modules without causing an identification problem.
Namespaces permit several programmers to work on the same project without
having naming collisions.

Prepared By: Mr. Muralidhara B K 67


Python Programming 1BPLC105B

12.7 Scope and Lookup rules:


The scope of an identifier is the region of program code in which the identifier
can be accessed, or used.
There are three important scopes in Python:
• Local scope: refers to identifiers declared within a function. These
identifiers are kept in the namespace that
belongs to the function, and each function has its own namespace.
• Global scope: refers to all the identifiers declared within the current
module, or file.
• Built-in scope: refers to all the identifiers built into Python — those
like range and min that can be used without having to import anything, and
are (almost) always available.

To list the identifiers declared in a specific module, in the current module and
in the function, we can use the functions dir(), globals() and locals()
respectively.

12.8 Three import statement variants:


import statement can be used in 3 ways as follows:
i) import math: Here just the single identifier math is added to the current
namespace. If you want to access one of the functions in the module, you need
to use the dot notation to get to it

Prepared By: Mr. Muralidhara B K 68


Python Programming 1BPLC105B

ii) from math import radians, sin, cos: here only the identifiers radians, sin
and cos are added to the current namespace. Hence if you want to access
them you can do it directly without the need of dot(.) operator. Also note that
you cannot access any other identifiers of math module.

iii) from math import * : here all the identifiers declared in math module
are added to the current namespace. Hence you can them without dot(.)
operator.

Prepared By: Mr. Muralidhara B K 69


Python Programming 1BPLC105B

13. Classes and Objects


Object_Oriented Programming (OOP) is a programming paradigm that uses
classes and objects to structure code, bundling related data (attributes) and
behaviors (methods) into single, reusable units. This approach helps in
managing complexity and promoting code reuse in large applications.

13.1 Principles of OOP:


The 4 principles of any OOP are:
• Abstraction: Hiding the complex implementation details and showing
only the essential features of an object.
• Encapsulation: The practice of bundling data and methods within a
class and controlling access to them.
• Polymorphism: The ability for objects of different classes to respond to
the same method name in different ways
• Inheritance: mechanism where a new class (child/derived) inherits
attributes and methods from an existing class (parent/base), promoting
code reuse and establishing a hierarchy.

13.2 Classes:
In Python, a class is a blueprint or template for creating objects that bundle
data (attributes) and behavior (methods) into a single, structured unit.
A class in python is created by using the ‘class’ keyword, followed by the name
of the class and ending with a colon(:).

The __init__ method: Every class should have a method with the special
name “__init__”. This initializer (constructor) method is automatically called
whenever a new instance of object is created. It gives the programmer the
opportunity to set up the attributes required within the new instance by giving
them their initial state/values.

The Self Parameter: It is the first parameter in any instance method. The
‘self’ parameter is automatically set to reference the newly created object that
needs to be initialized.

Prepared By: Mr. Muralidhara B K 70


Python Programming 1BPLC105B

Attributes: Variables associated with a class or an instance. There are 2 types


of attributes:
• class attributes: These are shared by all instances
• instance attributes: These are unique to each instances

Methods: Functions defined within a class that describe the object's


behaviors.
The __str__ method: The __str__ method is automatically called whenever an
object needs to be converted into a string.
The __eq__ method: The __eq__ is called whenever an object is compared
using “==” operator.

13.3 objects:
Objects are instances of a class. An object is the fundamental abstraction for
data: everything in a Python program, including numbers, strings, lists,
functions, and even classes themselves, is an object.
Objects are created by "instantiating" a class using function notation. The
special __init__ method, often called the constructor, runs automatically when
an object is created to set its initial state.

Prepared By: Mr. Muralidhara B K 71


Python Programming 1BPLC105B

13.4 Object composition:


creating an object by embedding other objects in it is called ‘object
composition’.

13.5 Sameness (equality):


objects can be compared to check if they are same or not. The sameness or
equality has 2 variants.
Shallow Equality: When only references are compared and not the contents
of 2 objects, it is called “shallow equality”. Shallow equality can be checked
using the ‘is’ operator.
Deep Equality: When the contents of the 2 objects are compared instead of
their references, it is called “deep equality”. The deep equality can be checked
by using the ‘==’ operator, provided the “__eq__” method is implemented in
the class.

Prepared By: Mr. Muralidhara B K 72


Python Programming 1BPLC105B

13.6 Copying:
when a reference variable is assigned to another using assignment (=)
operator, it doesn’t creates another object, but instead creates a ‘alias’ for the
same object. Since both references are referring to same object, you can use
any reference to modify the values(state) of the object.

Prepared By: Mr. Muralidhara B K 73


Python Programming 1BPLC105B

To make another copy (duplicate) of an object you need to use the ‘copy’
module. The ‘copy’ module allows you to do both shallow copy and deep copy.
Shallow copy: makes a copy of the object, without making copy of any of the
embedded objects. It is done through the copy() method of ‘copy’ module.
Deep copy: makes copy of both the object and also any embedded objects
inside it. It is done through the deepcopy() method of ‘copy’ module.

Prepared By: Mr. Muralidhara B K 74


Python Programming 1BPLC105B

13.7 operator overloading:


An operator can be made to behave differently when it is applied to different
types. This process is called operator overloading.
To overload ‘+’ operator you need to provide a method named ‘__add__’ in
your class.
To overload ‘*’ operator you need to provide either ‘__mul__’ or ‘__rmul__’ or
both methods in your class.
The ‘__mul__’ method is called when both LHS and RHS of ‘*’ operator are
objects of same type.
The ‘__rmul__’ method is called when only RHS of ‘*’ operator is an object and
LHS is a number.

Prepared By: Mr. Muralidhara B K 75


Python Programming 1BPLC105B

13.8 Polymorphic functions:


If a function can be successfully applied to different data types, then it is
called a polymorphic function. A polymorphic function can take arguments
with different types.

In the above example, add function is polymorphic as it can be applied to


integer, float and strings.

Prepared By: Mr. Muralidhara B K 76


Python Programming 1BPLC105B

The len() function in python is polymorphic as it can be used to find the


number of elements in lists, tuple and strings.

13.9 Inheritance:
Inheritance is the ability to define a new class that is a modified version of an
existing class. The primary advantage of this feature is that you can add new
methods to a class without modifying the existing class.

Parent class: The existing class is called the “parent” class. Sometimes this
class is also called “superclass”.

Child class: The new class created from an existing class (parent class) is
called “child” class or “subclass”. A child class is created by specifying the
parent class in the parantheses while defining the child class.

Super() function: The super() function is used to access methods and


properties of a parent class (superclass) from within a child class (subclass).

Prepared By: Mr. Muralidhara B K 77


Python Programming 1BPLC105B

14. Exceptions
Exceptions in Python are events that occur during the execution of a program
and disrupt its normal flow. They are runtime errors that can be caught and
handled to prevent the program from crashing abruptly, making the code
more robust and reliable.

All exceptions are classes that inherit from the base class BaseException,
and most common exceptions inherit from the Exception class.

14.1 Exception Handling Keywords:


Python uses four main keywords for exception handling:
• try: This block contains the code that might raise an exception.
• except: This block catches and handles the exception if one occurs
within the try block. You can specify the type of exception to catch for
specific handling.
• else: This block executes only if no exception was raised in the try
block. It's useful for code that should only run upon success.
• finally: This block always executes, regardless of whether an exception
occurred or was handled. It is typically used for cleanup actions, such as
closing files or releasing resources.

14.2 Common Built-in Exceptions:


Python has an extensive hierarchy of built-in exceptions. Some of the most
common include:
• ZeroDivisionError: Raised when the second argument of a division or
modulo operation is zero.
• TypeError: Raised when an operation or function is applied to an object
of an inappropriate type.
• NameError: Raised when a local or global name is not found.
• ValueError: Raised when a function receives an argument of the
correct type but an inappropriate value.
• IndexError: Raised when a sequence subscript (index) is out of range.
• KeyError: Raised when a dictionary key is not found.

Prepared By: Mr. Muralidhara B K 78


Python Programming 1BPLC105B

• FileNotFoundError: Raised when a file or directory is requested but


does not exist.
• ImportError: Raised when an import statement fails to find or load a
module.

You can write multiple exception clause to handle multiple exception types:

Prepared By: Mr. Muralidhara B K 79


Python Programming 1BPLC105B

14.3 User-Defined Exceptions:


Developers can also create custom exceptions by defining a new class that
inherits from the base Exception class or one of its existing subclasses. This
helps in organizing and categorizing application-specific errors, making code
more maintainable.

Prepared By: Mr. Muralidhara B K 80

You might also like