0% found this document useful (0 votes)
0 views57 pages

Python Unit I

The document provides an overview of Python programming, including its history, features, advantages, and applications. Python, created by Guido van Rossum in 1991, is a versatile, high-level language known for its readability and simplicity, making it suitable for various domains like web development and data science. It also discusses different types of literals in Python, including numeric, string, boolean, and collection literals.

Uploaded by

Suriya Prakash
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)
0 views57 pages

Python Unit I

The document provides an overview of Python programming, including its history, features, advantages, and applications. Python, created by Guido van Rossum in 1991, is a versatile, high-level language known for its readability and simplicity, making it suitable for various domains like web development and data science. It also discusses different types of literals in Python, including numeric, string, boolean, and collection literals.

Uploaded by

Suriya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

PYTHON PROGRAMMING

UNIT – I
1.1. BASICS OF PYTHON PROGRAMMING
Python is a popular programming language. Python is a versatile and high-level
programming language. It was created by Guido van Rossum in 1991. It’s simple to use,
packed with features and supported by a wide range of libraries and frameworks. Its clean
syntax makes it beginner-friendly.
Python offers a wide range of functionalities, easy readability and simplicity that
makes various domains such as web development, data science, artificial intelligence,
automation and more. It is used for:
 Python can be used on a server to create web applications
 Python can be used software to create workflows
 Python can connect to database systems. It can also read and modify files
 Python can be used to handle big data and perform complex mathematics
 Python can be used for rapid prototyping and system scripting
a. Why Python?
 Python works on different platforms (Windows, Mac, Linux, 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. This means that prototyping can be very
quick
 Python can be treated in a procedural way, an object-oriented way or a functional
way
 The python interpreter’s line-editing features include interactive editing, history
substitution and code completion on systems that support the GNU Readline library
 It is possible to write Python in an Integrated Development Environment
b. Advantages
 Python is an easy to learn, powerful programming language
 It has efficient high-level data structures and a simple but effective approach to
object-oriented programming
 Python requires fewer lines of code compared to other programming languages
 Python provides many job opportunities in Software Development, Data Science
and AI/ML
 Python provides popular Web Development, Data Science and Data Analysis
Libraries like Django, Flask, Pandas, Tensorflow, Scikit-learn and many more

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 1


 Python is an object oriented programming language which encapsulates code
within object
 Python is cross-platform works on Windows, Mac and Linux
 Python is used by big companies like Google, Netflix and NASA.
 It is an ideal language for scripting and rapid application development in many areas
on most platforms
 The Python interpreter is easily extended with new functions and data types
implemented in C or C++
 Python is also suitable as an extension language for customizable applications
c. Applications of Python Programming Language
It is a high-level language and used in web development, data science, automation,
AI, etc. It is good readability which means code is easier to write, understand and
maintain. The applications of python are shown below:

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 2


Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 3
1.2. HISTORY OF PYTHON
Python is a widely used general-purpose and high-level programming language. It
was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation. It was mainly developed to emphasize code readability and allows
programmers to express concepts in fewer lines of code.
Python is a feature-rich, high-level, interpreted, interactive and object-oriented
scripting language. Python is a versatile and very popular programming language features
such as readability, simplicity, extensive libraries and many more.
 In 1980, the Python project was started
 In 1989, the application based work of Python started
 The language setup was finally released in 1991
The two of the most used versions has to Python 2.x & 3.x. Following are the
illustrations of different versions of Python along with the timeline
 In 1994, Python 1.0 version was released. It includes basic support for object-
oriented programming features
 In 1997, Python 1.5 version was released
 In 2000, Python 1.6 version was released
 In 2000, Python 2.0 significant version was released. It includes scripting and
automation, developing desktop GUI applications, scientific computing and web
development
 In 2000, Launch the Python Enhancement Proposal (PEP). It is a mechanism used by
the Python community to propose and discuss changes, improvements and new
features for the Python programming language
 In 2001, Python 2.1 and Python 2.2 versions was released
 In 2003, Python 2.3 version was released
 In 2004, Python 2.4 version was released
 In 2006, Python 2.5 version was released
 In 2007, Python 2.6 and Python 2.7 versions was released
 In 2008, Python 3.0 version was released. It is also known as “Python 3000” or
“Py3k”. It is a significant milestone in Python’s evolution. Python 3.0 introduced
several fundamental changes and improvements including cleaner syntax, improved
I/O handling, enhanced optimized uni-code support
 In 2010, Python 3.1 version was released
 In 2011, Python 3.2 version was released
 In 2012, Python 3.3 version was released
 In 2014, Python 3.4 version was released

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 4


 In 2015, Python 3.5 version was released. This year also release of TensorFlow by
Google
 In 2016, Python 3.6 version was released. This year also release PyTorch by
Facebook. It provides powerful frameworks for deep learning and neural network
development in Python
 In 2018, Python 3.7 version was released
 In 2019, Python 3.7.3 version was released
 In 2022, Pycon (Python Conference) new feature version was released by
Anaconda foundation. It is known as Pyscript (Python Script)
Python Latest Update
The latest Python version is 3.12.6 in 2024 and this version improve an efficiency,
developer experience and performance. It has the following features:
 Improved Performance – This version introduces several optimizations
techniques which provides to improve the overall performance
 Enhanced Error Messages - This version includes better to detect error messages
with more detailed suggestions for beginners
 New Debugging Features - A new debugging and profiling API was introduced
which is useful for developers in any applications
 F-String Flexibility - Python’s f-string syntax has become more flexible. This is
allowing for more powerful and readable string formatting capabilities
 Type Annotation Enhancements - This is also introduces more advanced type
annotations especially for generic classes and making code more readable and
easier to maintain
 Easy to learn and use - Python’s simple syntax for beginner and user-friendly
 Extensive libraries and frameworks – It offers rich libraries for web
development, data science, AI, etc.
 Versatile - Supports multiple programming paradigms and applications
 Cross-platform – It works across any platforms like Windows, MacOS and Linux
 Great for rapid prototyping – Quick and easy syntax allows for fast idea
implementation
1.3. FEATURES OF PYTHON
Python is a versatile and high-level programming language. It is easy readable,
dynamically typed, free open source and interpreted language. These are determined at
runtime and code is executed line by line. Python also supports object-oriented programming
(OOP) features as well as procedural-oriented programming. It is highly portable and running
on various operating systems. The significant features of python are given below:

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 5


 Free and Open Source – Python language is freely available at the official website
and we can download it. This means that source code is also available to the public
 Easy to code - Python is a high-level programming language. Python is very easy
language compared to other languages like C, C++, Javascript, Java and etc. It is also
a developer-friendly language
 Easy to Read - Python is quite simple. Python’s syntax and code block is really
straightforward
 Object-Oriented Language - One of the key features of Python is Object-oriented
programming features. Python supports object-oriented language and concepts of
classes, object, encapsulation and etc.
 GUI Programming Support - Graphical User interfaces can be made using
different modules of Python. PyQt5 is the most popular option for creating
graphical apps with Python
 High-Level Language - Python is a high-level programming language. The Python
codes are written in English statements
 Memory Utilization – Python also need to manage the good memory architecture
 Large Community Support - Python has gained popularity over the years. We can
use constantly in large students, masters and developers
 Easy to Debug – Python is excellent information for mistake tracing. This
interpreter is able to quickly identify and correct the majority of error traces
 Python is a Portable language - Python language is also a portable language. It
can be run any platforms
 Python is an Integrated language - Python is also an integrated language
because we can easily integrate with other languages like C, C++ and etc
 Interpreted Language - Python is an Interpreted Language because Python code
is executed line by line at a time. There is no need to compile the program. Python
code is much easier to debug the code. The source code of Python is converted into
an immediate form called byte code
 Large Standard Library - Python has a large standard library that provides a rich
set of modules and functions
 Dynamically Typed Language - Python is a dynamically-typed language. That
means the type for a variable is decided at run time not in advance to declared
 Frontend and backend development – The Python Pyscript is used to develop
frontend applications. The Backend is the strong and extensively used frameworks
of storing data like Django and Flask

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 6


 Allocating Memory Dynamically - In Python, the variable data type does not
need to be specified. The memory is automatically allocated to a variable at
runtime
 Versatile Applications - Python is used in various fields including web
development, data analysis, machine learning, automation and scientific computing
1.4. LITERALS
Literals in Python are fixed values or raw data that are used directly in the
code. Literals are fixed values written directly in the code that represent constant data. They
provide a way to store numbers, text or other essential information that does not change
during program execution. Python supports different types of literals such as numeric
literals, string literals, Boolean literals, and special values like none.
General Example

a. Types of Literals
 Numeric Literals
 String Literals
 Boolean Literals
 Collection Literals
 Special Literals
1. Numeric Literals
Numeric literals represent numbers and are classified into three types:
Integer Literals – This represents the whole numbers (positive, negative or zero) without a
decimal point. Example: 10, -25 and 0
Integer literals consists of three different types of literal values decimal, octal and
hexadecimal literals.
 Decimal Literal - Decimal literals represent the signed or unsigned numbers.
Digitals from 0 to 9 are used to create a decimal literal value. The following
statement assigning decimal literal to the variable:
x = 10, y = -25 and z = 0
 Octal Literal - Python allows an integer to be represented as an octal number. A
numeric representation with only eight digit symbols (0 to 7) but prefixed by 0o or
0O is an octal number in Python. The following statement assigning octal literal to
the variable: x = 0O34

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 7


 Hexadecimal Literal – Python allows an integer values 0 to 9 and symbol a to f but
prefixed by 0x or 0X is a Hexadecimal number in Python. The following statement
assigning hexadecimal literal to the variable: x = 0X1C
Floating-point (Decimal) Literals – This represents the numbers with a decimal point. It is
also called real numbers. Example: 3.14, -0.01 and 2.0
Complex Number Literals – This represents the numbers in the form of a + bj, where a is the
real part and b is the imaginary part. Example: 5 + 2j and 7 – 3j
Example
# Integer literals
a = 100
b = -50
# Floating-point literals
c = 3.14
d = -0.005
# Complex number literals
e = 4 + 7j
f = -3j
print(a, b, c, d, e, f)
Output
100 -50 3.14 -0.005 (4+7j) (-0-3j)
2. String Literals
String literals are sequences of characters enclosed in quotes. String literals are
classified into three types:
Single-quoted strings – Enclosed in single quotes (‘ ‘). Example: ‘Hello World!’
Double-quoted strings – Enclosed in double quotes (” “). Example: “Python is fun!”
Triple-quoted strings – Enclosed in triple single (”’ ”’) or triple double (“”” “””) quotes,
generally used for multi-line strings or docstrings. Example: ‘’’ Welcome ‘’’
Raw strings – Prefix with r to ignore escape sequences (\n, \t, etc.). Example:
r”C:\Users\Python” (backslashes are treated as normal characters)
Example
# Different string literals
a = 'Hello' # Single-quoted
b = "Python" # Double-quoted
c = '''This is
a multi-line string''' # Triple-quoted
d = r"C:\Users\Python" # Raw string

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 8


print(a)
print(b)
print(c)
print(d)
Output
Hello
Python
This is
a multi-line string
C:\Users\Python
3. Boolean Literals
Boolean literals represent truth values in Python. This literals helps in decision-
making and logical operations. Boolean literals are useful for controlling program flow in
conditional statements like if, while and for loops. Boolean literals are classified into two
types.
True – Represents a positive condition (equivalent to 1).
False – Represents a negative condition (equivalent to 0).
Example
# Boolean literals
a = True
b = False
print(a, b) # Output: True False
print(1 == True) # Output: True
print(0 == False) # Output: True
print(True + 5) # Output: 6 (1 + 5)
print(False + 7) # Output: 7 (0 + 7)
4. Collection Literals
Python provides four different types of collection literals:
Lists - Ordered, mutable sequences of items enclosed in square
brackets []. Example: [1, 2, 3]
Tuples - Ordered, immutable sequences of items enclosed in parentheses (). Example: (1, 2, 3)
Dictionaries - Unordered collections of key-value enclosed in pair of curly
braces {}. Example: {'a': 1, 'b': 2}
Sets - Unordered collections of unique items enclosed in curly braces {}. Example: {1, 2, 3}.

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 9


Example
Rank = ["First", "Second", "Third"] # List
colors = ("Red", "Blue", "Green") # Tuple
Class = { "Jai": 10, "Anaya": 12 } # Dictionary
unique_num = {1, 2, 3} # Set
print(Rank, colors, Class, unique_num)
Output
['First', 'Second', 'Third'] ('Red', 'Blue', 'Green') {'Jai': 10, 'Anaya': 12} {1, 2, 3}
Explanation
 [“First”, “Second”, “Third”] is a list (rank of students)
 (“Red”, “Blue”, “Green”) is a tuple (like a set of crayons you can’t change)
 {“Jai”: 10, “Anaya”: 12} is a dictionary (storing names and ages)
 {1, 2, 3} is a set (a bag where every item is unique)
5. Special Literal
Python contains only one special literal (None). ‘None’ is used to define a null variable.
Example
res = None
print(res)
Output
None
Advantages of Literals
 Readability - Literals represent values directly in the code and making it easier to
understand the intended data
 Simplicity - Literals provide a concise way to define constant values without the
need for computation or function calls
 Efficiency - The literals are fixed values and don't require any processing or
evaluation during program execution. It can improve performance
 Versatility - Literals can be used in various contexts such as assigning values to
variables, passing arguments to functions and initializing data structures
 Clarity - Literals clearly indicate the data type and value. It is reducing ambiguity
and potential errors
 Testability - Literals are useful for testing code and easily define specific input
values and verify the expected output
 Immutability - Literals are immutable that means values cannot be changed after
they are defined and ensuring data integrity

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 10


1.5. CONSTANTS
In Python programming, constants are a fundamental concept referring to values that
don’t change throughout a program's execution. Developers use constants often in various
projects and special cases. The constants are variables treated as a symbolic constant. They
are typically defined using uppercase letters to signify their fixed value. The uppercase
variables are separated by underscores (e.g., MAX_LIMIT).
Example
# Mathematical constant
PI = 3.14159
# Acceleration due to gravity
GRAVITY = 9.8
print(PI)
print(GRAVITY)
Output
3.14159
9.8
Rules while declaring a Constant
 Python constant names can include
 Uppercase letters (A-Z)
 Digits (0-9)
 Underscores (_)
 Naming rules for constants
 Use UPPERCASE letters for constant names (e.g., CONSTANT = 65).
 Do not start a constant name with a digit
 Only the underscore (_) is allowed as a special character; other characters (e.g.,
!, #, ^, @, $) are not permitted
 Can be of any length
 Best practices for naming constants
 Use meaningful and descriptive names (e.g., VALUE instead of V) to clearer and
easier to understand
Advantages of Constants
 Improved Code Maintainability - We can use one name to identify one value
throughout the program. Hence, this makes the code more maintainable
 Enhanced Code Readability - A single descriptive name to represent a value
throughout the code and makes it is more readable and understand

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 11


 Reduced Bugs - The constant’s value is the same throughout the program, so there
are fewer errors and bugs. This is quite useful feature for large projects.
 Clear Intent Communication - The constant naming PI is conveys the clearly and
allow developers to understand the program accurately
 Thread-safe Data Storage - We can only access constants and thread-safe objects
for storage. So, multiple threads can simultaneously use a single constant
 Reduced Risks - There are fewer risks of errors because we use different values and
need to change for a particular set of calculations. Constants are values used to
represent magnitude, quantity, parameter or object that remain unchanged
throughout the program.
1.6. VARIABLES
Variables are containers for storing data values. The variables are used to store data
that can be referenced and manipulated during program execution. A variable is essentially
a name that is assigned to a value. In Python, variables do not require explicit declaration. The
type of the variable is inferred based on the value assigned in the program. Creating the
variable has the following aspects:
 Variables act as placeholders for data
 This allows us to store and reuse values in a program
 Python has no command for declaring a variable
 A variable is created to assign a value
Example
# Variable 'x' stores the integer value 10
x=5
# Variable 'name' stores the string "Samantha"
name = "Samantha"
print(x)
print(name)
Output
5
Samantha
a. Rules for Naming Variables
 Variable names can only contain letters, digits and underscores (_) sign
 A variable name cannot start with a digit
 Variable names are case-sensitive (myVar and myvar are different)
 Variable names are not use keywords
 Variables can be of any length

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 12


Valid Example
age = 21
_colour = "lilac"
total_score = 90
Invalid Example
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
b. Assigning Values to Variables
In Python, assigning values to the variables has the following categories:
1. Basic Assignment
Variables in Python are assigned values using the = operator
x=5
y = 3.14
z = "Hi"
2. Dynamic Typing
Python variables are stored dynamically that means the same variable can hold different
types of values during execution.
x = 10
x = "Now a string"
3. Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single line. It can be
useful for initializing variables with the same value.
Example
a = b = c = 100
print(a, b, c)
Output
100 100 100
Assigning Different Values
We can assign different values to multiple variables simultaneously. It can be useful
for initializing variables with the different value
Example
x, y, z = 1, 2.5, "Python"
print(x, y, z)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 13


Output
1 2.5 Python
c. Type Casting a Variable
Type casting refers to the process of converting the value of one data type into
another. Python provides several built-in functions to facilitate casting including int(), float()
and str() among others.
Basic Casting Functions
Int() – Converts compatible values to an integer
Float() – Transforms values into floating-point numbers
Str()– Converts any data type into a string
Examples
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output
10
5.0
25
d. Getting the Type of Variable
In Python, we can determine the type of a variable using the type() function. This
built-in function returns the type of the object passed to it.
Example Usage of type()
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 14


bool = True
# Get and print the type of each variable
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
e. Scope of a Variable
There are two methods to define scope of a variable in python
Local Variables
The variables defined inside a function are local variables
def f():
a = "I am local"
print(a)
f()
# print(a) # This would raise an error since 'local_var' is not accessible outside the
function
Output
I am local
Global Variables
The variables defined outside any function are called global variables and can be
accessed inside functions using the global keyword
a = "I am global"
def f():
global a
a = "Modified globally"
print(a)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 15


f()
print(a)
Output
Modified globally
Modified globally
Example Program - Swapping Two Variables
a, b = 5, 10
a, b = b, a
print(a, b)
Output
10 5
Advantages
 Data Storage and Reusability - Variables act as containers for storing data values,
which can be referenced and manipulated throughout a program. This is promoting
code reusability and efficiency
 Dynamic Typing - Python is dynamically typed that means the data type of a
variable is automatically inferred at runtime. This flexibility allows a single variable
to hold different types of values during the program's execution
 Descriptive Naming - Variables allow assigning descriptive names to data and
making code more readable, meaningful and understandable
 Memory Management - Variables facilitate efficient memory management by
allocating and deallocating memory as needed
 Modularity and Encapsulation - Local variables are defined within specific
functions or blocks of code. This is promote modularity and encapsulation
 Flexibility and Adaptability - Variables enable programs to adapt to different
inputs and conditions. It is more flexible and responsive
 Debugging and Error Handling - Variables aid in debugging by providing a way to
inspect the values of data at different points in the program. This helps identify and
resolve errors more easily and improving code quality and reliability.
 Multiple Assignment - Python allows assigning the same value to multiple
variables simultaneously which can be useful for initializing variables or setting
default values concisely
 Data Sharing - Global variables can be accessed from anywhere in the code and
facilitating data sharing between multiple functions or modules. This can be useful
for managing data that needs to be consistent across different parts of the program

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 16


 Integration with other languages - Python can be integrated with other
programming languages such as C, C++ and Java. These are allowing variables to be
shared and manipulated across different language environments
1.7. GLOBAL AND LOCAL VARIABLES
In Python programming, variables are essential tools that store information to be used
and manipulated within a program. The variables are declared two types of scopes:
 Global Variables
 Local Variables
Global Variables - Global variables are declared outside of any function in a Python program.
They can be accessed and modified from any part of the code. This is useful for values that need
to be consistent and accessible throughout the entire program.
Example
x = 10 # This is a global variable
def print_global():
print(x)
print_global()
Output: 10
In the above example, the variable x is a global variable because it is defined outside of
any function. The function print_global() can access x and print its value without any issues.
Advantages of Using Global Variables
 Accessibility - Global variables can be accessed from any function which is needs to
be used by multiple parts of a program
 Consistency – This is maintain a single source of truth for values that are used across
various functions and reducing redundancy
 Simplicity – The global variables can simplify the understanding between different
parts of a program
Disadvantages of Using Global Variables
 Unintended Modifications - The global variables can be accessed and modified by
any part of the code. It increases the risk of accidental changes and leading to bugs or
error
 Namespace Pollution - Global variables can lead to a cluttered namespace and
making it difficult to track
 Reduced Modularity – The global variables can make the code less modular become
dependent on external variables

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 17


Local Variables - Local variables are declared within a function and can only be accessed and
used within that function. They are created, executing and destroyed when the function ends
Example
def my_function():
y = 5 # This is a local variable
print(y)
my_function()
Output
5
print(y) # This will raise an error because y is not accessible outside the function
In the above example, y is a local variable within my_function(). It cannot be accessed
outside of this function and ensuring that its scope is limited
Advantages of Using Local Variables
 Encapsulation - Local variables help encapsulate the data within a function
 Modularity - Functions using local variables are more modular and easier to
understand
 Memory Management - Local variables are destroyed once the function execution is
complete which can help in efficient memory management
Disadvantages of Using Local Variables
 Limited Scope - Local variables cannot be accessed outside their function which can
be restrictive in nature
 Redundancy - If the same value is needed across different functions then it may need
to be passed repeatedly and leading to redundancy
Combining Global and Local Variables
Python programming often involves a combination of both global and local variables.
Example
counter = 0 # Global variable
def increment():
global counter
counter += 1 # Modify the global variable
def print_counter():
print(counter)
increment()
print_counter()
Output
1

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 18


In the above example, counter is a global variable that is modified within
the increment function using the global keyword, which allows the function to modify the global
variable rather than creating a new local variable.
Best Practices of Variables
 Minimize Global Variables – In the Python Programming, minimize the global
variables maintain clarity and reduce the risk of bugs
 Use Local Variables for Function-Specific Tasks - Encapsulate data within
functions using local variables to enhance modularity and readability
 Consistent Naming Conventions - Adopt consistent naming conventions to
differentiate between global and local variables easily
1.8. IDENTIFIERS
In Python, an identifier is a name given to a variable, function, class, module or other
object. It serves as uniquely identify and refer to object within the code. An identifier can only
contain letters, digits, and underscores and cannot start with a digit. Identifiers are case-
sensitive.
Valid Identifiers
 Yourname - It contains only lowercase alphabets
 Name_school - It contains only ‘_’ as a special character
 Id1 - the numeric digit comes at the end
 roll_2 - It starts with lowercase and ends with a digit
 _classname - Contains lowercase alphabets and an underscore starts with first
Invalid Identifiers
 (for, while, in) - These are the keywords in python that cannot use as identifiers
 1myname - Invalid identifier because It begins with a digit
 $myname - Invalid identifier because It starts with a special character
 a b - Invalid identifier because it contains a blank space
 (a/b and a+b) - are Invalid identifiers because contain special character
Rules for Naming Identifiers
 An identifier can contain letters (both uppercase and lowercase), digits and
underscores
 It must begin with a letter or an underscore
 First letter should not give a digit
 Python is case-sensitive
 All the identifiers in python should have a unique name in the same scope
 Special characters like @, $ and % are not allowed within identifiers
 Identifiers can be of any length

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 19


Naming Conventions
 Use lowercase letters for variables and functions (e.g. counter, calculate_average)
 Use capitalized words for classes (e.g., MyClass, DataProcessor)
 Separate words in identifiers with underscores to improve readability
(e.g. total_amount, user_name)
 Avoid using single-character identifiers
 Choose descriptive and meaningful names that clearly indicate the purpose of the
identifier
 Keywords cannot be used as names for identifiers
 Avoid using abbreviations because abbreviations can make the code harder to read
and understand
 Limit the length of names identifiers
 Use consistent naming conventions to improve readability and maintainability of the
code base
 Identifiers in python should be lowercase and use underscores to separate words
 It’s a good practice to avoid using single-letter variable names
1.9. KEYWORDS
Every language contains words and a set of rules that would make a sentence
meaningful. In Python programming language, there are a set of predefined words called
Keywords. The keywords are also called reserved words. User cannot change their meaning.
Keywords are used to define the syntax of the coding. Python keywords cannot be used as
the names of variables, functions and classes. All the keywords in Python are written in
lowercase letters except True and False. There are 35 keywords in Python 3.11.
Rules for Keywords in Python
 Python keywords cannot be used as identifiers
 All the keywords in Python should be in lowercase except True and False
List of Python Keywords
Keywords Description
and This is a logical operator which returns true if both the operands are
true else returns false
or This is also a logical operator which returns true if anyone operand is
true else returns false
not This is again a logical operator it returns True if the operand is false else
returns false
if This is used to make a conditional statement
elif Elif is a condition statement used with if statement. The elif statement is
executed if the previous conditions were not true
else The else block is executed if the given condition is not true

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 20


for This is used to create a loop
while This keyword is used to create a while loop
break This is used to terminate the loop
as This is used to create an alternative
def It helps us to define functions
lambda It is used to define the anonymous function
pass This is a null statement which means do nothing
return It will return a value and exit the function
True This is a boolean value
False This is also a boolean value
try It makes a try-except statement
with The with keyword is used to simplify exception handling
assert This function is used for debugging purposes
class It helps us to define a class
continue It continues to the next iteration of a loop
del It deletes a reference to an object
except Used with exceptions
finally Finally is used with exceptions, a block of code that will be executed no
matter if there is an exception or not
from It is used to import specific parts of any module
global This declares a global variable
import This is used to import a module
in It’s used to check whether a value is present in a list, range, tuple, etc.
is This is used to check if the two variables are equal or not
none This is a special constant used to denote a null value or avoid
nonlocal It’s declared a non-local variable
raise This raises an exception
yield It ends a function and returns a generator
async It is used to create asynchronous routine
await It releases the flow of control back to the event loop
Example
The following code allows viewing the complete list of Python’s keywords. This code
imports the “keyword” module in Python and then prints a list of all the keywords in Python
using the “kwlist” attribute of the “keyword” module.
# code
import keyword
print(keyword.kwlist)
Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',...]

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 21


1.10. BUILT-IN DATA TYPES
In Python programming, a data type is a classification or categorization that dictates a
computer interprets and manipulates a piece of data. It specifies the kind of value a variable can
hold and some operations can be performed. It is a way to categorize data based on types.
a. Key Aspects of Data Types
 Classification - Data types categorize data into different groups like integers,
floating-point numbers, strings, Boolean values (true/false) and others
 Interpretation - Tell the computer to clearly interpret the data
 Operations - Data types also determine which operations are valid on that data
Memory Allocation - Data types needs to store its data. Different data types
require different memory allocations
b. Types of Data Types
Python has several built-in data types used to store different kinds of values. It
represents the kind of value that tells what operations can be performed on a particular data.
The following are the standard or built-in data types in Python:

 Numeric – int, float, complex


 Sequence Type – string, list, tuple
 Mapping Type – dict
 Boolean – bool
 Set Type – set, frozenset
 Binary Types – bytes, bytearray, memoryview
1. Numeric Types
 int - Represents integers (whole numbers), e.g., 10, -5 and 0
 float - Represents floating-point numbers (numbers with decimal points), e.g., 3.14,
-0.5 and 2.0
 complex - Represents complex numbers in the form of a + bj, where a and b are
reals and j is the imaginary unit, e.g., 2 + 3j and -1j
2. Sequence Types
 str - Represents strings (sequences of characters), e.g., "hello", 'world' and "123"

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 22


 list - Represents ordered, mutable (changeable) sequences of items, e.g., [1, 2, 3]
and ['a', 'b', 'c']
 tuple - Represents ordered, immutable (unchangeable) sequences of items, e.g., (1,
2, 3) and ('a', 'b', 'c')
 range - Represents a sequence of numbers and often used in loops, e.g., range(5) (0,
1, 2, 3, 4).
3. Mapping Type
 dict - Represents key-value pairs, where keys are unique and immutable and values
can be of any type, e.g., {'name': 'Alice', 'age': 30}
4. Set Types
 set - Represents an unordered collection of unique items, e.g., {1, 2, 3} and {'a', 'b',
'c'}
 frozenset - Represents an immutable version of set
5. Boolean Type
 bool - Represents truth values either True or False
6. Binary Types
 bytes - Represents immutable sequences of bytes
 bytearray - Represents mutable sequences of bytes
 memoryview - Provides a memory view of other binary objects
7. None Type
 none - Represents the absence of a value with only one possible value is None
1.11. INPUT STATEMENTS
An input statement in programming allows the user to provide data to a program
during its execution. This is enabling interactive behavior and data processing based on
user input. It essentially acts as a bridge between the user and the program and
allowing the user to influence the program's actions.
Input() function
Python provides a built-in function called input which takes the input from the
user. The input() function in Python allows a program to receive data from the user
during runtime. It passes the program's execution, displays an optional prompt to the
user and waits for the user to enter text followed by the Enter key. If no prompt is given
then the function proceeds without displaying any message.
Syntax
input(prompt)
Here, prompt is a String and representing a default message before the input

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 23


Need the input() Function
 It allows programmers to interact with users
 It is a method to read different inputs
 Many programs use a dialog box to collect inputs from users
How the input function works in Python
 The input() function executes program flow will be stopped until the user
has given the input
 The text or message displayed on the output screen to ask a user to enter an
input value
 The input() function is used to get the string only
 The input() function converts integer and float value by using int(0 and
float() function
Example #1
name = input("Please enter your name: ")
print("Hello, " + name + "!")
In the above example, the input() function displays the prompt "Please enter
your name: " and waits for the user to type their name and press Enter. The entered
name is then stored in the variable name and the program prints a greeting message
using the stored name.
It's important to note that the input() function always returns a string. If we need
to enter numerical data to convert the input string to the appropriate data type using
functions like int() or float().
Example #2
age = input("Please enter your age: ")
age = int(age)
print("You are", age, "years old.")
In this case, the input string is converted to an integer using int() before being
used in the print statement.
Example #3
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 24


# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
Output
Enter number : 123
123
Enter name : Welcome to Python
Welcome to Python
Type of number <class ‘str’>
Type of name <class ‘str’>
In this case, the input() function is used to get string only. The type() function is
used to give the class ‘str’.
Example #4
num = int(input("Enter a number: "))
print(num, " ", type(num))
floatNum = float(input("Enter a decimal number: "))
print(floatNum, " ", type(floatNum))
Output
Enter a number:
29 <class ‘int’>
Enter a decimal number:
100.4 <class ‘float’>
In this case the input() function takes all the input as a string only. There are
various function that are used to take as desired like int(input()) and float(input())
split() function
Taking multiple inputs from user in Python
a. split()
It divides the string into separate components based on whitespace by default.
Example #1
# taking two inputs at a time
x, y, z = input("Values: ").split()
print(x)
print(y)
print(z)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 25


Output
values: 5 6 7
5
6
7
Example #2
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
b. List Comprehension
List comprehension is a way to create lists using a concise syntax
Example
a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res)
Output
[4, 9, 16, 25]
c. Take Conditional Input from user in Python
The following example program prompts the user to enter their age. The input is
converted to an integer using the int() function. Then, the program uses conditional
statements to check the age range and prints a message based on condition by using if…..elif
statement

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 26


Example
# Prompting the user for input
age_input = input("Enter your age: ")
# Converting the input to an integer
age = int(age_input)
# Checking conditions based on user input
if age < 0:
print("Please enter a valid age.")
elif age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output
Enter your age: 22
You are an adult
d. map() function
The map() function is useful for applying the same operation to all elements in an
iteration, resulting in cleaner and more readable code compared to traditional loops
Example #1 – Normal map() function
def square(n):
return n * n
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
Output
[1, 4, 9, 16, 25]
Example #2 - A lambda function can be used for a more concise approach
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
Output
[1, 4, 9, 16, 25]
Example #3: Multiple iteration can be passed to map()and the function takes multiple
arguments

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 27


def add(a, b):
return a + b
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = map(add, list1, list2)
print(list(result))
Output
[5, 7, 9]
1.12. OUTPUT STATEMENTS
An output statement in programming is a command that instructs a computer to display
or transmit information. It's the mechanism by which a program communicates results to the
outside screen. Python print() function prints the message to the screen or any other standard
output device.
It sends data to the standard output which is typically the console. The print() function
can accept multiple arguments including strings, numbers and other Python objects
Syntax
print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Here:
value(s) - Any value be converted to a string before printed
sep=’separator’ - (Optional) Specify to separate the objects
end=’end’ - (Optional) Specify what to print at the end. The default is ‘\n’
file - (Optional) An object with a write method. The default is sys.stdout
flush - (Optional) A Boolean to specifying the output is flushed (True) or buffered
(False). The default is False
Example #1: The simplest way to use print() is to pass it a string
print("Hello, world!")
Output
Hello, world!
Example #2: Print multiple items by separating them with commas
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output
Name: Alice Age: 30
Example #3: The print() separates arguments with a space. This can be changed using
the sep parameter

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 28


print("apple", "banana", "cherry", sep=", ")
Output
apple, banana, cherry
Example #4: we use sep argument for multiple variables
a = 12
b = 12
c = 2022
print(a, b, c, sep="-")
Output
12-12-2022
Example #5: End Parameter – The print() adds a newline character (\n) at the end of the
output. This can be modified using the end parameter
print("Hello", end=" ")
print("world!")
Output
Hello world!
Example #6: Formatting Output including f-strings (formatted string literals)
name = "Bob"
score = 95
print(f"Name: {name}, Score: {score}")
Output
Name: Bob, Score: 95
F-strings allow embedding expressions inside string literals and making it easier to
create formatted output.
Examples #7: The output of a mathematical computation can be printed
print(5 + 80 + 23)
Output
108
Example #8: The prompt message and the math result is computed and displayed on the
screen
print("What is 5 + 80 + 23?", 5 + 80 + 23)
Output
What is 5 + 80 + 23? 108
Example #9: String literals using the character “/n” is used to add a new blank line
print("Welcome \n to All")
Output

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 29


Welcome
To All
Example #10: Printing strings on the screen using the concatenation (Join)
coding="Welcome"
a="to"
b="All"
print(coding+a+b)
Output
WelcometoAll
Example #11: The space between the values of the variables
coding="Welcome"
a="to"
b="All"
print(coding+" "+a+" "+b)
Output
Welcome to All
Example #12: Format the strings using format() method. The curved bracing {} serves as
a hold
coding="Welcome to {}"
b="All"
print(coding.format(b))
Output
Welcome to All
Example #13: Special Case Example in format() method
# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
print('The value of a is {} and b is {}'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
Output
The value of a is 20 and b is 10
30 is the sum of 20 and 10

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 30


1.13. COMMENTS IN PYTHON
A comment line in programming is a line of code that the compiler or interpreter ignores
message. It is intended for human readability and document the code for future reference.
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. It has the following features:
 Comments are primarily for humans, not the computer
 Comments enhance the readability of the code
 Comment can be used to identify functionality or structure the code-base
 Comment can help understanding unusual or to prevent accidental removal or
changes
 Comments can be used to prevent executing any specific part of your code
 Comments can help programmers understand the logic and purpose of the code
Syntax
Most of the programming languages have specific syntax for including comments. Python
has the following syntax of comments:
# for single-line comments in Python
How it works
When a program is compiled or interpreted, the compiler or interpreter simply ignores
the comment lines and doesn't include in the executable code. Comments in Python are
explanatory notes added to the code to make it more readable and understandable.
Types
There are three main types of comments in Python:
a. Single-line comments - These start with a hash symbol (#) and continue until the end of the
line
Example
# This is a single-line comment
x = 5 # Assign the value 5 to the variable x
b. Multi-line comments - Python doesn't have a specific syntax for multi-line comments, they
can be created using triple single quotes or triple double quotes (""" or ‘’’) or by using # at the
beginning of each line.
Example #1
"""
This is a multi-line comment
using triple quotes

“””

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 31


Example #2
'''
This is also a
multi-line comment
using triple single quotes
'''
Example #3
# The following code is temporarily commented out
# print("This line will not be executed")
Docstrings - These are string literals that appear as the first statement in a module, function,
class or method definition. Docstrings are accessed using the ___doc__.
Example
def add(a, b):
"""
This function adds two numbers and returns the result.
"""
return a + b
print(add.__doc__)
Output
This function adds two numbers and returns the result.
Uses of Comments
Comments in Python are identified with a hash symbol (#) and extend to the end of the
line. There are multiple uses of writing comments in Python. Some significant uses include:
 Increasing readability
 Explaining the code to others
 Understanding the code easily after a long-term
 Including resources
 Re-using the existing code
 Explaining the logic and purpose of code sections
 Making code easier to understand for other developers or for future reference
 Disabling code temporarily for testing or debugging purposes
Best Practice to Write Comments
These are some of the tips we want to make the comments in effective manner:
 Comments should be short and precise
 Use comments only to understand the code
 Avoid writing generic or basic comments

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 32


 Write comments that are self explanatory
Advantages of Comments in Python
 Enhanced Readability - Comments are easily understand the other users and
functionality of code clearly stating the program
 Code That Documents Itself - Comments are almost self-documenting. Comments
that provide the logic become important resources for future reference
 Improved Cooperation – Comments are effective communication for efficient
teamwork and rapidly understand the operation of the code
 Improved troubleshooting - Comments can serve as useful cues for
troubleshooting. This can help to speed up the process of identifying and resolving
program faults
 Logic Explanation - If there are complex algorithms or logic in the code then the
comments can easily explain computations or decision-making processes
 Code Maintainability - Comments facilitate code maintenance and modification can
more confidently in the program
 Code Reuse – The comments are Reusable in other program sections is encouraged
 Knowledge Sharing – Comments are shared understanding of the code base in the
developers
1.14. INDENTATION
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements with the
same level of indentation are considered part of the same block. Indentation is achieved using
whitespace (spaces or tabs) at the beginning of each line.
In other words, indentation signifies that every statement with the same space to the
right is a part of the same code block. Indentation is significant feature in Python as it ensures
code readability. Wondering what is the role of indentation in Python? It determines the flow of
code and also serves the following purposes: Consistent indentation keeps the code organized,
clean and understandable. Several programming languages like C, C++, and Java use curly braces
{} to define a block of code. However, Python uses indentation which is clearly to define the
code structure.
Example
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 33


Output
This is true!
I am tab indentation
I have no indentation
Explanation
The first two print statements are indented by 4 spaces, so they belong to the if block
The third print statement is not indented, so it is outside the if block
Types of Indentation
There are two types of indentation:
 Space- The most preferred indentation method in Python is space which is a
standard convention in Python Style We can use 4 spaces for every indentation level
 Tab- We can use tabs for indentation but they are not universally accepted. This is
can raise issues and errors in Python. Most of the case tabs cannot use the code
structure level.
Indentation Rules for Python
 In Python, the first line of code can’t have indentation
 Python uses four spaces by default for each indentation level
 Programmers always better to use spaces for consistency
 Proper spaces to form the better working in a collaborative environment
 Never mix tabs and whitespaces for indentation
 Use a colon (:) to show the beginning of an indentation block such as for, if, while
and function definitions
 We use indentation to define code blocks including conditional loops and function
bodies
 Maintain the uniform number of spaces in a block of code
Example #1
name = 'Rahul'
if name == 'Rahul':
print('Welcome Rahul')
print('How are you?')
else:
print('Dude! whoever you are ')
print('Why you here?')
print('Have a great day!')
Output
Welcome Rahul

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 34


How are you?
Have a great day!
Example #2
i=1
while(i <= 6):
print("Value is " + str(i))
i=i+1
Output
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is 6
Benefits of Indentation in Python
 The proper use of indentation in a program provides many benefits some of them
are:
 Indentation is important to increase the readability of the code by clearly indicating
the hierarchy
 This avoids the need to use delimiters such as braces or brackets
 Python indentation is consistent throughout the program and making it easier to
debug
 In most programming languages, indentation makes the structure of the code
 Python uses for grouping and making the code automatically beautiful
 Python indentation rules are very simple. Most of the Python IDEs automatically
indent the code
1.15. OPERATORS
An operator is a symbol that instructs the computer to perform a specific mathematical
or logical operation on data. Operators are used to manipulate data and variables. Operators
operate on constants of variables, which are called operands. Python supports various types of
operators categorized as follows:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 35


 Membership operators
 Bitwise operators
a. Arithmetic Operators
Arithmetic operators are used to perform numeric operation. The different types of
arithmetic operators are given below:
Operator Name Example
+ Addition 5+2=7
- Subtraction 5-2=3
* Multiplication 5 * 2 = 10
/ Division 5 / 2 = 2.5
% Modulus 5%2=1
** Exponentiation 5 ** 2 = 25
// Floor Division 5 // 2 = 2
Example
a=5
b=2
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)
print(a // b)
b. Assignment Operators
Assignment operators are used to simplify the coding of a certain type of assignment
statement. The general form of this statement is:
Operand1 Operator = Operand 2
Here, operator can be either +, -, *, /, %. The short hands of all binary operators in
Python are:
Operator Example Equivalent
= a=5 a=5
+= a += 5 a=a+5
-= a -= 5 a=a-5
*= a *= 5 a=a*5
/= a /= 5 a=a/5
%= a %= 5 a=a%5
//= a //= 5 a = a // 5
**= a **= 5 a = a ** 5
Example

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 36


a=5
a += 2
print(a)
a **= 2
print(a)
c. Comparison Operators
Comparison operators are also called relational operators. Relational operators are used
to test the relationship between two operands.
Operator Name Example
== Equal to 5 == 2 is False
!= Not equal to 5 != 2 is True
> Greater than 5 > 2 is True
< Less than 5 < 2 is False
>= Greater than or equal to 5 >= 2 is True
<= Less than or equal to 5 <= 2 is False
Example
a=5
b=2
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
d. Logical Operators
Logical expression is the combination of relational expression. Logical operators are
used to combine the result the evaluation of relational expression. Python provides three logical
operators.
Operator Description Example
and Returns True if both operands (5 > 2) and (5 < 10) is True
are True
or Returns True if at least one (5 > 2) or (5 > 10) is True
operand is True
not Reverses the boolean value not(5 > 2) is False
Example
a=5
b=2
print((a > b) and (a < 10))
print((a > b) or (a > 10))

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 37


print(not(a > b))
e. Identity Operators
In Python, identity operators are used to determine whether two variables refer to the
same object in memory, rather than just having the same value. They compare the memory
addresses of the objects. Python provides two identity operators:
1. is operator - This operator returns True if both operands refer to the same object in
memory. Otherwise, it returns False
Example
x = [1, 2, 3]
y=x
z = [1, 2, 3]
print(x is y)
print(x is z)
Output: True (x and y refer to the same list object)
Output: False (x and z are different list objects)
2. is not operator - This operator returns True if both operands do not refer to the same object
in memory. Otherwise, it returns False. It is the inverse of the is operator
Example
a = 10
b = 20
c = 10
print(a is not b)
print(a is not c)
Output: True (a and b are different integer objects)
Output: False (so a and c might be the same object)
f. Membership Operators
These operators test if a value is present in a sequence or not. The membership
operators are listed below:
Operator Description Example
in Returns True if the value is found in 'a' in 'apple' is True
the sequence
not in Returns True if the value is not 'a' not in 'apple' is False
found
Example
a = 'apple'
print('a' in a)
print('b' not in a)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 38


g. Bitwise Operators
Bit wise operation refers to testing setting or shifting the actual bits in a byte or word. If
supports standard char and int data types and variants.
We cannot use bitwise operator on float, double, long double, void or other more
complex types.
Operator Action
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive – OR (XOR)
~ One’s complement (NOT)
>> Shift right
<< Shift left
Example
AND operator ( & )
9 – 00001001
7 – 00000111 (&)
00000001
OR operator ( | )
18 – 00010010
03 – 00000011 (|)
00010011
Exclusive OR operator ( ^ )
09 – 00001001
07 – 00000111 ( ^ )
00001110
One’s complement (NOT) (~)
9 – 00001001 (~)
11110110
Unsigned char X Binary value of X Value of X
X=7 00000111 7
Shift left operators (<< )
X=X<<1; 00001110 14
Unsigned char X Binary value of X Value of X
X = 192 11000000 192
Shift right operator (>>)
X = X >> 1; 01100000 96

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 39


Example 1- Code to implement basic arithmetic operations on integers
num1 = 5
num2 = 2
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)
Output
Sum: 7
Difference: 3
Product: 10
Quotient: 2.5
Remainder: 1
Example 2 - Code to implement Comparison operations on integers
num1 = 30
num2 = 35
if num1 > num2:
print("The first number is greater.")
elif num1 < num2:
print("The second number is greater.")
else:
print("The numbers are equal.")
Output
The second number is greater.
Operator Precedence
Operator precedence describes the order in which operations are performed. The
precedence order is starting with the highest precedence at the top. The range of operator
precedence is listed below:

Operator Description
() Parentheses

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 40


** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise NOT
* / // % Multiplication, division, floor division, and
modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not Comparisons, identity, and membership
in operators
not Logical NOT
and AND
or OR
If two operators have the same precedence then the expression is evaluated from left to right.
Example - Operator Precedence
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
Output
610
Hello! Welcome.
Operator Associativity in Python
If an expression contains two or more operators with the same precedence then
Operator Associativity is used. It can either be Left to Right or from Right to Left.
Example – Operator Associativity
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)
Output
100.0
6
0
512

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 41


1.21. EXPRESSIONS
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array
element or a constant. An expression is a combination of operators, constants and variables.
An expression may consist of one or more operands and zero or more operators to produce a
value.

Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value. Python supports
various types of expressions including:
 Constant Expressions
 Arithmetic Expressions
 Integral Expressions
 Floating Expressions
 Comparison expressions
 Logical Expressions
 Bitwise Expressions
 Combinational Expressions
 String Expressions
 Assignment Expressions
 Conditional Expressions
 Lambda Expressions
 Generator Expressions
 Regular Expressions
a. Constant Expressions - These are the expressions that have constant values only
Example
x = 15 + 1.3
print(x)
Output
16.3

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 42


b. Arithmetic expressions – It perform mathematical calculations using operators like +, -
, *, /, // (floor division), % (modulus) and ** (exponentiation)
Example
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
c. Integral Expressions - These are the kind of expressions that produce only integer results
after all computations and type conversions
Example
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
d. Floating Expressions - These are the kind of expressions that produce only floating point
numbers after all computations and type conversions
Example
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 43


2.6
e. Comparison expressions - Compare two values using operators like == (equal to), != (not
equal to), >, <, >=, and <=, returning a Boolean value (True or False). These expressions are also
called Boolean expressions or relational expressions
Example
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
f. Logical expressions - Combine Boolean values using operators like and, or and not. These are
kinds of expressions that result in either True or False. It basically specifies one or more
conditions
Example
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
g. Bitwise Expressions - These are the kind of expressions in which computations are
performed at bit level
Example
# Bitwise Expressions
a = 12

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 44


x = a >> 2
y = a << 1
print(x, y)
Output
3 24
h. Combinational Expressions - We can also use different types of expressions in a single
expression is called combinational expressions
Example
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
i. String expressions - Manipulate strings using operators like + (concatenation)
and * (repetition
Example
#String Expressions
string1 = 'My favorite number'
num = 14
string2='is the best number'
print(string1+': '+str(num)+' '+string2)
Output
My favorite number: 14 is the best number
j. Assignment expressions - Assign a value to a variable using the = operator and
operator := allows assignment within an expression
Example
student = 'Priya'
print(student)
x, y = 50, 100
print('Value of x: ',x)
print('Value of y: ',y)
Output
Priya
Value of x: 50
Value of y: 100

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 45


k. Conditional expressions - Choose between two expressions based on a condition using if---
else statement
Example
age=27
if age>18:
print('You can drive')
else:
print('you can not drive)
Output
You can drive
l. Lambda expressions - Create anonymous functions using the lambda keyword. A lambda
function is a single-line function declared with no name which can have any number of
arguments but it can only have one expression.
Example
print((lambda x: x*2)(5))
Output
10
m. Generator expressions - Create number of iterations in a concise way and similar to list
comprehensions but without storing all elements in memory
Example
def generate (str):
for s in str:
yield s
for ch in generate("Hello"):
print(ch)
Output
H
E
l
l
o
n. Regular expressions - A Regular Expression or RegEx is a special sequence of characters
that uses a search pattern to find a string or set of strings
Example
import re
pattern = '^a...s$'

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 46


test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Note: ^a...s$ - The above code defines a RegEx pattern. The pattern is: any five letter string
starting with a and ending with s
o. Multiple operators expression - It’s a quite simple process to get the result of an
expression. Multiple operators, values and operands are used these expressions. The operator
precedence rules are followed by these expressions
Example
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
1.22. TYPE CONVERSIONS
Type conversion is also known as type casting. It involves changing a variable's data
type to one another. Python supports two main types of type conversions:
 Implicit Type Conversion
 Explicit Type Conversion
Implicit Type Conversion - Python automatically converts one data type to another without
the programmer's intervention. It perform operations involving mixed data types
Example
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 47


print("z is of type:",type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
Explicit Type Conversion - Programmers use built-in functions to manually convert data types.
Commonly used functions for explicit type conversion include:
 int() - Converts a value to an integer
 float()- Converts a value to a floating-point number
 str()- Converts a value to a string
 bool() - Converts a value to a boolean
 list(), tuple(), set(), dict()- Convert to their respective data structures
Example
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output
After converting to integer base 2 : 18
After converting to float : 10010.0
PYTHON ARRAYS
1.23. DEFINING ARRAYS
A Python array is a data structure containing multiple items of the same data type at
contiguous memory locations. It is an important part of most programming languages. It is
easier to calculate the position of each item. An array holds multiple values in a single variable.
It contains an element and an index. All elements have their respective index helps to find the
location of an element. Array index starts with 0.
In Python, array is a collection of homogeneous elements makes it memory efficient.
Python arrays are not popular. However, we use them in certain situations. Arrays are mutable.

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 48


So we can add elements to an array, update, delete items and perform other operations. We can
also use various methods on arrays such as slicing, searching, reversing, etc. The general syntax
for creating an array looks like this:
Syntax
variable_name = array(typecode,[elements])
Here, variable_name is any valid name of the array, array is a keyword to define the
array, typecode specifies what kind of elements would be stored in the array and
elements that would be stored in the array with each element being separated by a comma The
different type codes that can be used with the different data types are listed below:
Typecode C type Python Type Size
'b' signed char int 1
'B' unsigned char int 1
'u' wchar_t Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8

Key Features
 Multi-dimensional support - NumPy arrays can handle more than one dimension
and making suitable for matrix operations and more complex mathematical
constructs
 Broad broadcasting capabilities - They can perform operations between arrays
of different sizes and shapes. So this feature is known as broadcasting
 Efficient storage and processing - NumPy arrays are stored more efficiently than
Python lists and provide optimized performance for numerical operations
Example #1
import array as arr
# creating array of integers
a = arr.array('i', [1, 2, 3])
# accessing First Araay
print(a[0])

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 49


# Adding element to array
a.append(5)
print(a)
Output
1
array('i', [1, 2, 3, 5])
Example #2
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
Output
array('i', [10, 20, 30])
Example #3
import array as arr
numbers = arr.array('i',[10,20,30])
print(len(numbers))
Output
3
Example #4
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element
Output
10
20
30
Example #5
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
Output
30

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 50


20
10
Example #6
import array as arr
numbers = arr.array('i',[10,20,30])
#search for the index of the value 10
print(numbers.index(10))
Output
0
1.24. PROCESSING ARRAYS
An array is a collection of similar quantities. An array contains a collection of data
elements of the same type. An array referenced by a common name. Each elements of an array
is stored in successive locations of the memory. The element of the array is known as
member of the array. Each array element is identifies by assigning a unique index stating
from o. Some of the most commonly used methods which are used for performing operations on
arrays.
a. Create an Array in Python
Array in Python can be created by importing an array module The syntax
array( data_type , value_list ) is used to create array in Python with data type and value list
specified in its arguments.
Example
import array as arr
# creating array
a = arr.array('i', [1, 2, 3])
# iterating and printing each item
for i in range(0, 3):
print(a[i], end=" ")
Output
123
b. Adding Elements to an Array
Elements can be added to the Python array by using built-in insert() function. Insert is
used to insert one or more data elements into an array. A new element can be added at the
beginning, end or any given index of array.
Example
import array as arr
# Integer array example

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 51


a = arr.array('i', [1, 2, 3])
print("Integer Array before insertion:", *a)
a.insert(1, 4) # Insert 4 at index 1
print("Integer Array after insertion:", *a)
Output
Integer Array before insertion: 1 2 3
Integer Array after insertion: 1 4 2 3
c. Append Elements in Array
The append() is also used to add the value mentioned in its arguments at the end of the
Python array.
Example
a = [1, "Hello", [3.14, "world"]]
a.append(2) # Add an integer to the end
print(a)
Output
[1, 'Hello', [3.14, 'world'], 2]
d. Accessing Array Items
In order to access the array items refer to the index number. We can use the index
operator [ ] to access an item in Python array . The index must be an integer.
Example
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print(a[0])
print(a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print(b[1])
print(b[2])
Output
1
4
3.2
3.3
e. Updating Elements in an Array
In order to update an element in the array we simply reassign a new value to the
desired index.
Example

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 52


import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
# update item at index 2
arr[2] = 6
print(arr)
# update item at index 4
arr[4] = 8
print(arr)
Output
array('i', [1, 2, 6, 1, 2, 5])
array('i', [1, 2, 6, 1, 8, 5])
f. Removing Elements from the Array
Elements can be removed from the Python array by using built-in remove() function.
Remove() method only removes the first occurrence of the searched element. The pop()
function can also be used to remove and return an element from the array. The
remove()function removes only the last element of the array but pop() function remove
element from a specific position.
Example
import array
arr = array.array('i', [1, 2, 3, 1, 5])
# using remove() method to remove first occurance of 1
arr.remove(1)
print(arr)
# pop() method - remove item at index 2
arr.pop(2)
print(arr)
Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])
1.25. METHODS OF ARRAYS
In Python, array is a collection of items stored at contiguous memory locations. Arrays
are mutable which means they are changeable. We can change the value of the different array
items. Lists in Python are the most flexible and commonly used data structure for sequential
storage. They are similar to arrays in other languages but with several key differences:
 Dynamic Typing - Python lists can hold elements of different types in the same
list. We can have an integer, string and even other lists stored within a single list

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 53


 Dynamic Resizing - Lists are dynamically resized that means add or remove
elements without declaring the size of the list
 Built-in Methods - Python lists come with numerous built-in methods that allow
for easy manipulation of the array elements including methods for appending,
removing, sorting and reversing elements.
Example
import array as arr
# creating array of integers
a = arr.array('i', [1, 2, 3])
# accessing First Araay
print(a[0])
# Adding element to array
a.append(5)
print(a)
Output
1
array('i', [1, 2, 3, 5])
a. NumPy Arrays
NumPy arrays are a part of the NumPy library which is a powerful tool for numerical
computing in Python. These arrays are designed for high-performance operations on large
volumes of data and support multi-dimensional arrays and matrices. This is ideal for complex
mathematical computations and large-scale data processing.
Example
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4])
# Element-wise operations
print(arr * 2)
# Multi-dimensional array
arr2d = np.array([[1, 2], [3, 4]])
print(arr2d * 2)
Output
[2 4 6 8]
[[2 4]
[6 8]]
b. Slice of an Array

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 54


We can access a specific range of values inside the array by using the slicing operator
(colon :). The slicing operator includes the value of index starts from 0 by default. We use slice
operation in the following:
 Elements from beginning to a range use [:Index]
 Elements from end use [:-Index]
 Elements from specific Index till the end use [Index:]
 Elements within a range, use [Start Index:End Index]
 Print complete List, use [:]
 For Reverse list, use [::-1]
Example
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
Sliced_array = a[3:8]
print(Sliced_array)
Sliced_array = a[5:]
print(Sliced_array)
Sliced_array = a[:]
print(Sliced_array)
Output
array('i', [4, 5, 6, 7, 8])
array('i', [6, 7, 8, 9, 10])
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
c. Searching Element in an Array
In order to search an element in the array we use a python in-built index() method.
This function returns the index of the first occurrence of value mentioned in arguments.
Example
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
# index of 1st occurrence of 2
print(arr.index(2))
# index of 1st occurrence of 1
print(arr.index(1))
Output
1
0

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 55


d. Counting Elements in an Array
We can use count() method to count given item in array.
Example
import array
arr = array.array('i', [1, 2, 3, 4, 2, 5, 2])
count = arr.count(2)
print("Number of occurrences of 2:", count)
Output
Number of occurrences of 2: 3
e. Reversing Elements in an Array
In order to reverse elements of an array we need to simply use reverse method.
Example
import array
arr = array.array('i', [1, 2, 3, 4, 5])
arr.reverse()
print("Reversed array:", *arr)
Output
Reversed array: 5 4 3 2 1
f. Extend Element from Array
In Python, an array is used to store multiple values or elements of the same data type
in a single variable. The extend() function is simply used to attach an item to the end of the
array.
Example
import array as arr
a = arr.array('i', [1, 2, 3,4,5])
# using extend() method
a.extend([6,7,8,9,10])
print(a)
Output
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
g. Change the Value of an Item in an Array
We can change the value of a specific element by specifying its position and assigning it
a new value.
Example
import array as arr
#original array

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 56


numbers = arr.array('i',[10,20,30])
#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40
print(numbers)
Output
array('i', [40, 20, 30])

Developed By Dr. T. BALAJI/AP/CSC/GAC/MELUR 57

You might also like