0% found this document useful (0 votes)
1 views112 pages

Python_Programming NOTES _I_CS_FINAL AUTONOMOUS

The document provides an overview of Python programming, detailing its history, features, and types of literals including numeric, boolean, string, and Unicode literals. It highlights Python's design philosophy of readability and simplicity, making it accessible for both beginners and experienced programmers. Additionally, it discusses the importance of Python's extensive libraries and community support in its widespread adoption across various domains.

Uploaded by

Mano Ranjani
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)
1 views112 pages

Python_Programming NOTES _I_CS_FINAL AUTONOMOUS

The document provides an overview of Python programming, detailing its history, features, and types of literals including numeric, boolean, string, and Unicode literals. It highlights Python's design philosophy of readability and simplicity, making it accessible for both beginners and experienced programmers. Additionally, it discusses the importance of Python's extensive libraries and community support in its widespread adoption across various domains.

Uploaded by

Mano Ranjani
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/ 112

SENGUNTHAR ARTS AND SCIENCE COLLEGE

(Autonomous)
(Affiliated to Periyar University, Salem and Approved by AICTE, NewDelhi)
An ISO 9001:2015 Certified Institution Recognised under section 2(f)
and 12(B) of the UGC Act 1956 and Accredited by NAAC with A+

TIRUCHENGODE–637205, NAMAKKAL DT., TAMIL NADU


website: www.senguarts.co.in Emailid: [email protected]

24S1UCS01
Python Programming

Academic Year -2024-25

1
SENGUNTHAR ARTS AND SCIENCE COLLEGE, TIRUCHENGODE
AUTONOMOUS
(Affiliated to Periyar University, Salem)
DEPARTMENT OF COMPUTER SCIENCE

Subject Name: Python Programming Subject Code: 23UCS01

UNIT - I

Basics of Python Programming


History of Python

 Python is a high-level, general-purpose programming language that was created by Guido Van Rossum
and first released in 1991. Its design philosophy emphasizes code readability and simplicity, making it an
ideal language for beginners and experienced programmers alike. Python's versatility and extensive
libraries have contributed to its popularity, making it one of the most widely used programming languages
in the world.

Here is a detailed overview of the history of Python:

1. Origins: In the late 1980s, Guido Van Rossum, a Dutch programmer, began working on Python as
a successor to the ABC programming language. He aimed to develop a language with a clean and
readable syntax that would enhance programmer productivity. Guido named the language "Python"
after the British comedy series "Monty Python's Flying Circus," as he wanted a fun and memorable
name.

2. Early Development: Guido released the first version of Python, version 0.9.0, in February 1991. It
was implemented in the C programming language and ran on the Amoeba operating system. Python

1.0 was released in January 1994, featuring numerous improvements, such as functional
programming tools and an extensive standard library.

3. Python 2: Python 2.0 was released in October 2000, introducing several significant enhancements.
It added support for Unicode, list comprehensions, and a garbage collector. Python 2.2, released in
December 2001, included a new cycle-detecting garbage collector and introduced the 'iterators'
concept. Python 2.3, released in July 2003, introduced generators, support for the 'with' statement,
and enhancements to the standard library.

4. Python 3: Python 3.0, also known as Python 3000 or Py3K, was released in December 2008. This
release introduced several backward-incompatible changes to improve the language's design and

2
eliminate redundancy and inconsistency. Python 3 focused on Unicode support, simplified syntax,
and enhanced library modules. However, due to the significant changes, it was not fully backward
compatible with Python 2, leading to a period of coexistence of both versions.

5. Transition from Python 2 to Python 3: The transition from Python 2 to Python 3 took several years
due to the incompatibilities between the two versions. The Python community encouraged
developers to migrate their code to Python 3, but many projects still relied on Python 2. To bridge the gap, a
series of Python 2.6 and 2.7 releases were made, which included some features back ported from Python 3.
This allowed developers to write code compatible with both versions. However, in 2020, Python 2 officially
reached its end-of-life and is no longer maintained.

6. Python's Popularity and Ecosystem: Python's simplicity, readability, and versatility have
contributed to its widespread adoption. Its ease of use, extensive standard library, and third-party
packages have made it popular across various domains, including web development, data analysis,
scientific computing, artificial intelligence, machine learning, and automation. Python's package
management system, pip, and its package repository, PyPI, have played a crucial role in the growth
of its ecosystem.

7. Recent Developments: Python continues to evolve with regular releases. Major versions, such as
Python 3.4, 3.5, 3.6, 3.7, 3.8, and 3.9, have introduced new features, performance improvements,
and optimizations. Python 3.10, the latest major release at the time of writing, was released in
October 2021, bringing additional language enhancements and improved developer productivity.

Throughout its history, Python has gained a large and active community of developers, contributing to
its growth and fostering the development of countless libraries, frameworks, and tools. Its simplicity,
versatility, and readability make it a powerful language for solving a wide range of programming tasks.

Features of Python

 Python is a versatile and powerful programming language known for its simplicity and readability. It
offers a wide range of features that contribute to its popularity among developers. Here are some key
features of Python:

1. Easy to Read and Write: Python's syntax emphasizes code readability, using indentation and a clean
structure. It avoids the use of complex symbols and braces, making it easier for beginners to
understand and write code.

2. Expressive Language: Python allows developers to express concepts in fewer lines of code compared
to other programming languages. It emphasizes code readability and simplicity, promoting a more
productive and efficient development process.
3
3. Interpreted and Interactive: Python is an interpreted language, which means that there is no need
for explicit compilation. Developers can execute Python code directly without the need for a separate
compilation step. Additionally, Python provides interactive mode, allowing users to experiment with
code snippets and get immediate feedback.

4. Cross-platform Compatibility: Python is a cross-platform language, meaning that Python programs


can run on various operating systems such as Windows, macOS, Linux, and more. This feature makes
it highly portable and versatile.

5. Large Standard Library: Python comes with an extensive standard library that provides a rich set
of modules and functions for a wide range of tasks. This library eliminates the need to build certain
functionalities from scratch, saving development time and effort.

6. Third-party Libraries and Packages: Python has a vast ecosystem of third-party libraries and
packages. These libraries cover diverse domains such as web development, data analysis, scientific
computing, machine learning, artificial intelligence, and more. Some popular libraries include NumPy,
Pandas, TensorFlow, Django, Flask, and Matplotlib.

7. Object-Oriented Programming (OOP): Python supports object-oriented programming principles,


allowing developers to create and use classes and objects. It provides inheritance, encapsulation, and
polymorphism, enabling developers to write modular and reusable code.

8. Dynamic Typing: Python is dynamically typed, meaning that variable types are determined at
runtime. Developers do not need to explicitly declare variable types, making Python more flexible and
reducing the complexity of type-related errors.

9. Memory Management: Python handles memory management automatically through a garbage


collector. Developers do not need to allocate or deallocate memory explicitly, reducing the risk of
memory leaks and simplifying memory management.

10. Integration and Extensibility: Python can be easily integrated with other programming languages
like C, C++, and Java. This feature allows developers to leverage existing code and libraries from
different languages and extend the functionality of Python.

11. Community and Support: Python has a large and active community of developers who contribute to
its growth and provide support through online forums, mailing lists, and conferences. The community-
driven nature of Python ensures continuous improvement, bug fixes, and the availability of resources
for learning and development.

4
These features make Python a powerful and flexible programming language suitable for a wide range of
applications, from small scripts to large-scale enterprise applications.

Literal-Constants

 In programming constants are referred to variables that cannot be changed.

Literal Constants

Numeric Literals Boolean Literals String Literals

 Generally Literal constants are classified in to three types.

Numeric Literals

Numeric literals in Python represent numerical values and can be classified into integers, floating-point numbers,
and complex numbers. Let's delve into each type with examples:

1. Integer Literals: Integer literals are whole numbers without decimal points. They can be positive or
negative.

Examples:

x = 42
y = -10
z=0
In the code above, x is assigned the integer literal 42, y is assigned -10, and z is assigned 0.
2. Floating-Point Literals: Floating-point literals are numbers with decimal points or written in scientific
notation.

Examples:

A=10.23
a=20.12
b=34.00
m=20.0e+12
pi = 3.14
temperature = -0.5
5
scientific_notation = 1.0e-3

Here, pi is assigned the floating-point literal 3.14, temperature is assigned -0.5, and scientific_notation

is assigned the value 0.001 written in scientific notation.

3. Complex Number Literals: Complex number literals consist of a real part and an imaginary part,
represented by "j" or "J".

Examples:

a = 2 + 3j

b = -1.5 - 2j

In the code snippet, a is assigned the complex number literal 2 + 3j, representing 2 as the real part and 3
as the imaginary part. b is assigned -1.5 - 2j, where -1.5 is the real part and -2 is the imaginary part.
Numeric literals are used for various purposes in Python, such as mathematical calculations,
comparisons, and storing numeric values. By utilizing integer literals, floating-point literals, and
complex number literals, you can work with different types of numerical data efficiently and accurately
within your programs.

Boolean Literals

 Boolean literals in Python represent the truth values of logical expressions and can only have two possible
values: True or False. These literals are often used in conditional statements and control flow constructs.
Here's an explanation of boolean literals with examples:

1. True Literal: The True literal represents the boolean value of true.
Example:

is_true = True

 In the code snippet, the variable is_true is assigned the boolean literal True.

2. False Literal: The False literal represents the boolean value of false.
Example:

is_false = False

 Here, the variable is_false is assigned the boolean literal False.

 Boolean literals are fundamental in controlling the flow of a program. They are commonly used
in conditional statements, such as if-else statements and while loops, to determine the execution
6
path based on the truth or falsehood of a condition.

 For example:

x=5

y = 10

is_greater = x > y # Assigns False since x is not greater than y

 In this case, the boolean literal False is assigned to the variable is_greater since the condition x

> y evaluates to False.

 Boolean literals can also be the result of logical operations and comparisons, such as and, or,
not, and relational operators (<, >, ==, etc.), which return boolean values based on the truth or
falsehood of the expressions.

 Understanding boolean literals is essential for writing conditional logic and decision-making in
Python programs.

String Literals

 String literals in Python represent sequences of characters enclosed in quotation marks, either single quotes
('') or double quotes (""). They allow you to work with textual data and manipulate strings in your code.
Here's an explanation of string literals with examples:

1. Single-Quoted String Literal: A single-quoted string literal is enclosed within single quotes ('').
Example:

single_quoted_string = 'Hello, World!'

In the code snippet, the variable single_quoted_string is assigned the string literal 'Hello, World!'.

2. Double-Quoted String Literal: A double-quoted string literal is enclosed within double quotes ("").
Example:

double_quoted_string = "Python is awesome"

Here, the variable double_quoted_string is assigned the string literal "Python is awesome".

String literals can contain any combination of characters, including letters, digits, symbols, and
whitespace. They can also span across multiple lines using triple quotes (''' ''') or triple double quotes ("""
""").

7
3. Multi-Line String Literal: A multi-line string literal spans across multiple lines and can be enclosed
within triple quotes (''' ''') or triple double quotes (""" """).

Example:

multi_line_string = '''This is a multi-line string.'''

In this example, the variable multi_line_string is assigned a multi-line string literal that spans across
three lines.

4. Special Characters and Escape Sequences: String literals can include special characters and escape
sequences to represent specific characters or control characters. Some commonly used escape sequences
include:

 \n - New line

 \t - Tab

 \" - Double quote

 \' - Single quote

 \\ - Backslash

Example 1 :

special_characters = "This is a quote: \"Hello, World!\""


new_line = "This is a string\nwith a new line."
print(special_characters)

print(new_line)
Output 1:

This is a quote: "Hello, World!"

This is a string
with a new line.

8
Example 2:

# String Literal Example


message = "Hello, World!"
print(message)

name = 'kumar'

print("My name is", name)

quote = """Python is a versatile programming language.

It is widely used for web development, data analysis, and more."""


print(quote)

Output 2:

Hello, World!

My name is kumar

Python is a versatile programming language.

It is widely used for web development, data analysis, and more.

 The special_characters variable is assigned a string literal that includes a double quote using the
escape sequence \". The new_line variable is assigned a string literal with a new line character
(\n).String literals are versatile and can be manipulated using various string methods and operators to
perform operations such as concatenation, slicing, formatting, and more. They are widely used for
representing textual data, handling user input, and working with strings in Python programs.

Unicode Strings

 Unicode strings in Python support a wide range of characters from different languages. They are
represented using the u prefix before the quotation marks.

Example:

unicode_string = u"こんにちは"

 Here, the variable unicode_string contains a Unicode string literal that represents the Japanese greeting

"こんにちは" ("Konnichiwa" or "Hello" in English). Unicode strings allow handling of non-ASCII

9
characters and are essential for multilingual applications.

Using Unicode strings in Python:


Example:

# Unicode String Example


greeting = u"こんにちは"

print(greeting)

 In this program, we define a variable greeting and assign it a Unicode string literal u"こんにちは".

The u prefix before the quotation marks indicates that the string is a Unicode string.

 The Unicode string "こんにちは" is written in Japanese and translates to "Konnichiwa" or "Hello" in
English. By using Unicode strings, we can handle and display non-ASCII characters and support
different languages and writing systems.

 The print() statement is used to display the Unicode string greeting. When the program is executed, it
will output the string “こんにちは” on the console, representing the Japanese greeting.

Output:

こんにちは

 Using Unicode strings enables us to work with diverse textual data and support multilingual applications

where different languages and characters are involved.

Raw Strings

 Raw strings in Python are string literals that treat backslashes () as literal characters, rather
than interpreting them as escape sequences. They are represented using the r prefix before
the quotation marks. Here's a short explaination of raw strings with an example:

Example: path = r'C:\Users\username'

 In the code snippet, the variable path is assigned a raw string literal r'C:\Users\username'.
The prefix r indicates that the string is a raw string.Raw strings are often used when dealing
with file paths, regular expressions, or any situation where backslashes are common and
should be treated as literal characters. They eliminate the need for double backslashes or
10
using escape sequences, making the code more readable and less error-prone.

 For instance, in the example above, the backslashes in the file path C:\Users\username are
treated as literal backslashes and not as escape characters. Using raw strings can be
particularly helpful when working with Windows file paths, regular expressions, or any
scenario where backslashes are prevalent.

 Here's a sample program that demonstrates the use of raw strings in Python:

# Raw String Example

path = r'C:\Users\username\Documents\file.txt'

# Printing the raw string


print(path)

 In this program, we define a variable path and assign it a raw string literal
r'C:\Users\username\Documents\file.txt'. The raw string represents a file path in a Windows operating
system.

 By using the r prefix before the quotation marks, we ensure that the backslashes \ in the path are treated
as literal characters, without being interpreted as escape sequences.

 The print() statement is then used to display the raw string path. When executed, the program will output
the file path as it is, preserving the backslashes without any interpretation.

Output:

C:\Users\username\Documents\file.txt

 By utilizing raw strings, we eliminate the need for double backslashes or additional escape characters,
simplifying the representation of file paths or other scenarios where backslashes are commonly used.

Variables and Identifiers

Variables:

 Variables and identifiers are fundamental concepts in programming, including Python. Let's explore them
individually:

1. Variables: In Python, a variable is a named storage location that holds a value. It serves as a reference to
a memory address where data is stored. Variables allow us to store and manipulate data during program
execution. They are created by assigning a value to a name.

11
Example:

x = 42 name = "Alice"

 In this code snippet, x and name are variables. x holds the value 42, and name holds the string "Alice". The
values can be changed or updated during the program execution.

 Variables in Python have the following characteristics:

 They must be assigned a value before they can be used.

 They can be reassigned to a different value.

 They can hold different types of data (e.g., integers, strings, lists, etc.).

 They have a scope (local or global) that determines their visibility and accessibility within
different parts of the program.

Identifiers:

 Identifiers: An identifier is a name used to identify a variable, function, class, module, or other entities in
python. It is used to provide a unique name to these entities so that they can be referred to and used in the

code.

 Rules for naming identifiers in Python:

 They can consist of letters (a-z, A-Z), digits (0-9), and underscores (_).

 They cannot start with a digit.

 They are case-sensitive (e.g., count and Count are different identifiers).

 They cannot be a reserved keyword (e.g., if, while, for).


Example:

score = 100 my_function = lambda x: x ** 2

 In this example, score and my_function are identifiers. score is an identifier for a variable holding the value
100, while my_function is an identifier for an anonymous lambda function.

 Identifiers play a crucial role in naming and referencing various entities in Python code. Choosing meaningful
and descriptive names for identifiers helps improve code readability and maintainability.

 Understanding variables and identifiers is essential for working with data and manipulating values in Python
programs.

Example:
12
# Variable and Identifier Example
name = "Alice"

age = 25
is_student = True

print("Name:", name)

print("Age:", age)

print("Is Student?", is_student)

Output:

Name: Alice
Age: 25

Is Student? True

Keywords

 Keywords in Python are reserved words that have predefined meanings and are used to represent specific
functionalities or actions within the programming language.

 These keywords cannot be used as identifiers (variable names, function names, etc.) because they are already
assigned a specific purpose in the language. Here is a list of keywords in Python:

 These keywords have special significance and are part of Python's syntax. They define control structures,
define functions and classes, handle exceptions, and more.

 It's important to avoid using keywords as identifiers to prevent conflicts and errors in your code. Identifiers
should be chosen wisely, using meaningful and descriptive names that are not already reserved by the
13
language.

Built-in Data Types

 Python provides several built-in data types that are used to represent different kinds of values. Here are some
of the commonly used built-in data types in Python:

1. Numeric Types:

 int: Represents integer values, such as 5, -10, 100.

 float: Represents floating-point numbers, such as 3.14, -2.5, 1.0.

2. Sequence Types:

 str: Represents a sequence of characters, such as "hello", "world".

 list: Represents an ordered collection of elements, enclosed in square brackets ([]).

 tuple: Represents an immutable ordered collection of elements, enclosed in parentheses (()).

3. Mapping Type:

 dict: Represents a collection of key-value pairs, enclosed in curly braces ({}) with a colon (:)
separating the key and value.

4. Set Types:

 set: Represents an unordered collection of unique elements, enclosed in curly braces ({}).

 frozenset: Represents an immutable version of set, enclosed in curly braces ({}).

5. Boolean Type:

 bool: Represents a boolean value, either True or False.

6. None Type:

 None: Represents a special value indicating the absence of a value or the null value.

 These built-in data types provide the foundation for representing and manipulating different kinds of data in
Python. They have various methods and operations associated with them, allowing you to perform operations
and transformations specific to each data type.

 It's worth noting that Python also supports other advanced data types, such as datetime objects, regular

14
expressions, and more, through built-in modules and libraries.

Sample program:

# Numeric Types
x=5

y = 3.14

# Sequence Types
name = "Alice"
my_list = [1, 2, 3, 4, 5]

my_tuple = (10, 20, 30)

# Mapping Type

person = {"name": "Bob", "age": 25, "city": "New York"}

# Set Types

my_set = {1, 2, 3, 4, 5}

my_frozenset = frozenset([10, 20, 30, 40, 50])

# Boolean Type
is_true = True
is_false = False

# None Type
no_value = None

# Printing the values and their types


print(x, type(x))

print(y, type(y))
print(name, type(name))

print(my_list, type(my_list))
print(my_tuple, type(my_tuple))
print(person, type(person))
print(my_set, type(my_set))
15
print(my_frozenset, type(my_frozenset))
print(is_true, type(is_true))
print(is_false, type(is_false))
print(no_value, type(no_value))

Output:

5 <class 'int'>

3.14 <class 'float'>


Alice <class 'str'>

[1, 2, 3, 4, 5] <class 'list'>

(10, 20, 30) <class 'tuple'>

{'name': 'Bob', 'age': 25, 'city': 'New York'} <class 'dict'>

{1, 2, 3, 4, 5} <class 'set'>

frozenset({10, 20, 30, 40, 50}) <class 'frozenset'>


True <class 'bool'>

False <class 'bool'>

None <class 'NoneType'>

Output Statements

 Python provides the print() function to display output on the console. You can pass multiple arguments to
print() to concatenate and display them. For example:

name = "John"
age = 25

print("Name:", name, "Age:", age) #Output: Name: John Age: 25

Input Statements

 Input statements in Python allow you to interactively receive input from the user during the execution of
a program.

 The input() function is used to prompt the user for input and capture the input value as a string. Here's
how input statements work:

# Input Statement Example

16
name = input("Enter your name: ")
print("Hello, " + name + " ! How are you?")

 In this program, the user is prompted to enter their name using the input() function. The entered name is
stored in the variable name. The program then displays a greeting message using the entered name.

Example output:

Enter your name: chilamb


Hello, chilamb ! How are you?

Comments

 In Python, comments are used to add explanatory or descriptive statements within the code that are ignored
by the interpreter during program execution. Comments are helpful for providing information about the
code, documenting its purpose, making notes, or disabling specific code temporarily. Here are a few key
points about comments in Python:

 Comments are preceded by the hash symbol (#).

 Anything after the # symbol on a line is considered a comment and is not executed by the interpreter.

 Comments can appear on a line by itself or at the end of a line of code.

 Comments are used to improve code readability and maintainability.


Here are a few examples of comments in Python:

# This is a single-line comment

name = "Alice" # Assigning a value to the variable name

"""

This is a multi-line comment.

It can span across multiple lines.

Useful for longer explanations or documentation.


"""

# print("This line is commented out")


# TODO: Implement this function later

# Use comments to explain the logic behind complex code sections

# or to provide reminders for future improvements or fixes.

17
 Comments are a valuable tool for making code more understandable and for communicating information to
other developers or yourself in the future. They help in clarifying the purpose and functionality of code
segments, making it easier to maintain and modify the code as needed.

Indentation

 In Python, indentation is a significant aspect of the language syntax and plays a crucial role in determining
the structure and execution flow of the code. Unlike other programming languages that use braces or keywords
to define code blocks, Python uses indentation to indicate the grouping and nesting of statements within
blocks. Here are a few key points about indentation in Python:

 Indentation is typically done using spaces or tabs. However, it is recommended to use spaces for
indentation to ensure consistent formatting across different platforms and editors.

 Indentation helps define the scope of control structures such as loops, conditionals, and function
definitions.

 Statements that have the same level of indentation belong to the same block.

 Indentation levels should be consistent within the same block. Mixing tabs and spaces for indentation can
result in indentation errors.

 The standard convention in Python is to use four spaces for each level of indentation.
Here's an example to illustrate the use of indentation in Python:

if x > 0:

print("x is positive")

print("This statement is inside the if block")


else:

print("x is non-positive")

print("This statement is inside the else block")


print("This statement is outside the if-else block")

 In this example, the indentation determines the blocks of code belonging to the if and else clauses. The
statements indented under the if clause are executed if the condition is true, and the statements indented under
the else clause are executed if the condition is false. The final print statement is outside both blocks and is
executed unconditionally.

18
 Indentation is not just a matter of style in Python but is essential for the proper interpretation of the code. It is
important to ensure consistent and correct indentation to avoid syntax errors and unintended program
behavior.

Operators

 Here are the operators along with examples:

1. Arithmetic Operators:

 Addition (+) : 2 + 3 returns 5.

 Subtraction (-) : 5 - 3 returns 2.

 Multiplication (*) : 2 * 3 returns 6.

 Division (/) : 10 / 2 returns 5.0 (float division).

 Modulo (%) : 10 % 3 returns 1 (remainder of division).

 Exponentiation (**) : 2 ** 3 returns 8.

 Floor Division (//) : 10 // 3 returns 3 (quotient without remainder).

2. Comparison (Relational) Operators:

 Equal to (==) : 5 == 5 returns True.

 Not equal to (!=) : 5 != 3 returns True.

 Greater than (>) : 5 > 3 returns True.

 Less than (<) : 5 < 3 returns False.

 Greater than or equal to (>=) : 5 >= 3 returns True.

 Less than or equal to (<=) : 5 <= 3 returns False.

3. Unary Operators:

 Unary Plus (+): +5 returns 5.

 Unary Minus (-) : -5 returns -5.

 Logical NOT (not) : not True returns False.

4. Bitwise Operators:
19
 Bitwise AND (&) : 5 & 3 returns 1.

 Bitwise OR (|) : 5 | 3 returns 7.

 Bitwise XOR (^) : 5 ^ 3 returns 6.

 Bitwise NOT (~) : ~5 returns -6.

 Left Shift (<<) : 5 << 1 returns 10.

 Right Shift (>>) : 5 >> 1 returns 2.

5. Shift Operators:

 Left Shift (<<) : 5 << 1 returns 10.

 Right Shift (>>) : 5 >> 1 returns 2.

6. Logical Operators:

 Logical AND (and) : True and False returns False.

 Logical OR (or) : True or False returns True.

 Logical NOT (not) : not True returns False.

7. Membership and Identity Operators:

 Membership test (in) : 2 in [1, 2, 3] returns True.

 Negated membership test (not in) : 4 not in [1, 2, 3] returns True.

 Identity test (is): x is y checks if x and y refer to the same object.

 Negated identity test (is not): x is not y checks if x and y refer to different objects.

8. Assignment Operators:

 Simple assignment (=) : x = 5 assigns the value 5 to the variable x.

 Add and assign (+=) : x += 2 is equivalent to x = x + 2.

 Subtract and assign (-=) : x -= 2 is equivalent to x = x - 2.

 Multiply and assign (*=) : x *= 2 is equivalent to x = x * 2.

 Divide and assign (/=) : x /= 2 is equivalent to x = x / 2.

 Modulo and assign (%=) : x %= 2 is equivalent to x = x % 2.

 Exponentiate and assign (**=) : x **= 2 is equivalent to x = x ** 2.

20
 Floor divide and assign (//=): x //= 2 is equivalent to x = x // 2.

9. Special Operators:

 Ternary Operator (if-else): x = 5 if condition else 10.

 Attribute Access (.) : object.attribute.

 These examples demonstrate the usage of different operators in Python for performing various operations and comparisons.

Operator Precedence

 Operator precedence determines the order in which operators are evaluated in an expression.

 It helps to clarify the order of operations when an expression contains multiple operators. In Python,
operators have different levels of precedence, and higher precedence operators are evaluated before lower
precedence operators.

 If two operators have the same precedence, their evaluation order is determined by their associativity (left-
to-right or right-to-left).

 Here is a summary of the operator precedence in Python (from highest to lowest):

1. Parentheses: ( )

 Parentheses are used to group expressions and override the default precedence.

2. Exponentiation: **

 Exponentiation operators raise a number to a power.

3. Multiplication, Division, and Modulo: *, /, %, //

 These operators perform multiplication, division, and modulo (remainder) calculations.

4. Addition and Subtraction: +, -

 These operators perform addition and subtraction operations.

5. Bitwise Shifts: <<, >>

 Bitwise shift operators shift the bits of a number to the left or right.

6. Bitwise AND: &

 The bitwise AND operator performs a bitwise AND operation on two numbers.

7. Bitwise XOR: ^

 The bitwise XOR operator performs a bitwise exclusive OR operation on two numbers.

21
8. Bitwise OR: |

 The bitwise OR operator performs a bitwise OR operation on two numbers.

9. Comparison Operators: ==, !=, <, >, <=, >=, in, not in, is, is not

 Comparison operators compare values and return Boolean results.

10. Logical NOT: not

 The logical NOT operator negates the truth value of an expression.

Sample Program:

# Example 1: Arithmetic Operations


result1 = 10 + 2 * 3

print("Example 1 Result:", result1) # Example 1 Result: 16

# Example 2: Logical Operations


value = True or False and True

print("Example 2 Result:", value) # Example 2 Result: True

# Example 3: Parentheses Override Precedence


result2 = (4 + 2) * 3

print("Example 3 Result:", result2) # Example 3 Result: 18

Expressions

 Expressions in Python can be based on both position and data types. The position refers to the order of
operands in an expression, while data types determine the specific operations that can be performed on the
operands. Here are examples of expressions based on position and data types:

1. Positional Expressions:

 Arithmetic Expression:

a=5

b=3

sum_result = a + b

In this expression, the + operator adds the values of a and b based on their position. The
expression evaluates to 8, which is assigned to the variable sum_result.

 String Concatenation:
22
greeting = "Hello" name = "Alice" message = greeting + ", " + name + "!"

In this expression, the + operator concatenates the strings greeting, ", ", name, and "!" based
on their position. The expression evaluates to the string "Hello, Alice!", which is assigned to the
variable message.

2. Expressions based on Data Types:

 Numeric Expression:

num1 = 10 num2 = 3 division_result = num1 / num2

In this expression, the / operator performs division on the numeric values num1 and num2. The
expression evaluates to 3.3333333333333335 (floating-point division), which is assigned to the
variable division_result.

 Logical Expression:

x = True
y = False

logical_result = x and y

In this expression, the and operator performs a logical AND operation on the boolean values x

and y. The expression evaluates to False, which is assigned to the variable logical_result.

 Comparison Expression:

a=5

b=3

comparison_result = a > b

In this expression, the > operator compares the values of a and b to determine if a is greater
than b. The expression evaluates to True, which is assigned to the variable comparison_result.

 These examples demonstrate how expressions in Python can be influenced by both the position of operands
and the data types involved. By understanding the position and the behavior of operators with different data
types, you can construct meaningful expressions that produce the desired results.

Type conversions.

 Type conversions, also known as type casting or type coercion, refer to the process of changing
the data type of a value to a different data type. Python provides several built-in functions and
methods for performing type conversions.
23
 Here are the commonly used type conversion functions:

# Type Conversion Examples

# Integer to Float
x = float(5)

print("Integer to Float:", x) # Output: 5.0

# Float to Integer
y = int(3.14)

print("Float to Integer:", y) # Output: 3

# Integer to String
z = str(10)

print("Integer to String:", z) # Output: '10'

# String to Integer
a = int("20")

print("String to Integer:", a) # Output: 20

# Boolean to Integer
b = int(True)

print("Boolean to Integer:", b) # Output: 1

# Float to String
c = str(3.14)

print("Float to String:", c) # Output: '3.14'

# String to Float
d = float("2.5")

print("String to Float:", d) # Output: 2.5

# Boolean to String
e = str(True)

print("Boolean to String:", e) # Output: 'True'

# String to Boolean
f = bool("True")

24
print("String to Boolean:", f) # Output: True

# List to Tuple

g = tuple([1, 2, 3])

print("List to Tuple:", g) # Output: (1, 2, 3)

# Tuple to List
h = list((4, 5, 6))

print("Tuple to List:", h) # Output: [4, 5, 6]

# List to Set

i = set([1, 2, 2, 3])

print("List to Set:", i) # Output: {1, 2, 3}

# Set to List

j = list({4, 5, 6})

print("Set to List:", j) # Output: [4, 5, 6]

# List of Tuples to Dictionary


k = dict([('a', 1), ('b', 2)])

print("List of Tuples to Dictionary:", k) # Output: {'a': 1, 'b': 2}

Type Casting vs Type Coercion

 Type casting and type coercion are two concepts related to changing the data type of a value in programming.
While they serve a similar purpose, there are slight differences between the two:

Type Casting:

25
 Type casting is an explicit conversion where the programmer explicitly specifies the desired data type.

 It is typically done using specific type conversion functions or constructors.

 Type casting may involve potential data loss or precision loss, as the value is forced to fit into the
target data type.

 Examples of type casting in Python include using functions like int(), float(), str(), etc.

Type Coercion:

 Type coercion is an implicit conversion where the programming language automatically converts one
data type to another in certain situations.

 It is done automatically based on predefined rules and compatibility between data types.

 Type coercion aims to preserve data integrity and make operations compatible between different data
types.

Python Arrays: Defining and Processing Arrays


Python Arrays:

Defining and Processing Arrays

Arrays in Python are a way to store and manipulate collections of elements of the same type. They provide
efficient and convenient operations for working with large sets of data. Python arrays can be created and
manipulated using the built-in array module.

1. Importing the array module:

To use arrays in Python, you need to import the array module. You can do this by including the following
line at the beginning of your code:

from array import array

2. Creating an array:

To create an array, you need to specify the type of elements it will hold. The most common types are:

 'b': signed integer of size 1 byte

 'B': unsigned integer of size 1 byte

 'i': signed integer of size 2 bytes

 'I': unsigned integer of size 2 bytes

26
 'l': signed integer of size 4 bytes

 'L': unsigned integer of size 4 bytes

 'f': floating-point number of size 4 bytes

 'd': floating-point number of size 8 bytes


Here's an example of creating an array of integers:

numbers = array('i', [1, 2, 3, 4, 5])

3. Accessing array elements:

You can access individual elements of an array using indexing, just like with regular lists. The index starts
at 0 for the first element. Here's an example:

numbers = array('i', [1, 2, 3, 4, 5])


print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3

4. Modifying array elements:

You can modify array elements by assigning new values to specific indices. Here's an example:

numbers = array('i', [1, 2, 3, 4, 5])

numbers[1] = 10

print(numbers) # Output: array('i', [1, 10, 3, 4, 5])

5. Array methods:

Arrays in Python provide several useful methods for manipulation. Here are some commonly used methods:

 append(x): Adds element x to the end of the array.


numbers = array('i', [1, 2, 3, 4, 5])
numbers.append(6)

print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6])

27
 insert(i, x): Inserts element x at index i.
numbers = array('i', [1, 2, 3, 4, 5])

numbers.insert(2, 10)

print(numbers) # Output: array('i', [1, 2, 10, 3, 4, 5])

 remove(x): Removes the first occurrence of element x.


numbers = array('i', [1, 2, 3, 4, 5])
numbers.remove(3)

print(numbers) # Output: array('i', [1, 2, 4, 5])

 pop(i): Removes and returns the element at index i.


numbers = array('i', [1, 2, 3, 4, 5])

x = numbers.pop(2)
print(x) # Output: 3

print(numbers) # Output: array('i', [1, 2, 4, 5])

 index(x): Returns the index of the first occurrence of element x.


numbers = array('i', [1, 2, 3, 4, 5])

idx = numbers.index(3)
print(idx) # Output: 2

 count(x): Returns the number of occurrences of element x.


numbers = array('i', [1, 2, 3, 4, 5, 3])

count = numbers.count(3)
print(count) # Output: 2

 reverse(): Reverses the order of elements in the array.


numbers = array('i', [1, 2, 3, 4, 5])
numbers.reverse()

print(numbers) # Output: array('i', [5, 4, 3, 2, 1])

28
 extend(iterable): Appends elements from the iterable to the end of the array.

numbers = array('i', [1, 2, 3])

numbers.extend([4, 5, 6])

print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6])

Array Operations

Various operations can be performed on arrays, such as arithmetic operations, slicing, and concatenation.

Array Operations with the array module:

 Slicing: You can slice arrays using indices, similar to lists.


 Concatenation: Arrays can be concatenated using the + operator.

Example:
import array
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
print(arr1[1:]) # Output: array('i', [2, 3])
arr3 = arr1 + arr2
print(arr3)

Output:
array('i', [2, 3])
array('i', [1, 2, 3, 4, 5, 6])
Numpy Array Operations:
 Element-wise Operations: You can perform arithmetic operations on arrays element-wise.
 Matrix Operations: Using numpy, you can perform matrix multiplication, transpose, etc.

Example:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr_sum = arr1 + arr2
print("Element-wise sum:", arr_sum)
arr_prod = arr1 * arr2
print("Element-wise product:", arr_prod)
arr3 = np.array([[1, 2], [3, 4]])
arr4 = np.array([[5, 6], [7, 8]])
matrix_prod = np.dot(arr3, arr4)
print("Matrix product:")
29
print(matrix_prod)

Output:
Element-wise sum: [5 7 9]
Element-wise product: [ 4 10 18]
Matrix product:
[[19 22]
[43 50]]

2 Mark:

1. Who is the creator of Python, and when was it first released?


Python was created by Guido van Rossum and was first released in 1991.
2. Why was Python created?
Python was created to be easy to read and write, offering an alternative to languages that were more complex,
with a focus on code readability.
3. Name two key features of Python
 Python is an interpreted language, meaning it executes code line by line.
 Python supports dynamic typing, meaning variables do not need explicit declarations of data types
4. How does Python handle memory management?
Python has an inbuilt garbage collector for memory management, which automatically handles the allocation
and deallocation of memory.
5. What are literal constants in Python?
Literal constants are fixed values directly used in the code, such as numbers (5, 3.14) or strings ("Hello").
6. Give examples of three types of literal constants in Python.
Integer (10), Floating-point (3.14), and String ("Python").
7. What is a variable in Python?
A variable is a name that refers to a memory location where data is stored, and it can be assigned values
dynamically.
8. How do you declare a variable in Python?
Variables in Python are declared by simply assigning a value to them, e.g., x = 10.
9. What are identifiers in Python?
Identifiers are names used to identify variables, functions, classes, etc. They must start with a letter or an
underscore and can be followed by letters, digits, or underscores.
10. What are the rules for naming identifiers in Python?
Identifiers must begin with a letter (A-Z or a-z) or underscore _ and can be followed by any number of
30
letters, digits, or underscores. Identifiers cannot use keywords or special characters like @, #, $.
11. What are keywords in Python?
Keywords are reserved words in Python that have a special meaning and cannot be used as identifiers.
Examples include if, else, for, while, and def.
12. Give two examples of keywords in Python.
while, return.

13. What are the built-in data types in Python?


Python has several built-in data types, including int (integers), float (floating-point numbers), str
(strings), bool (boolean), and list (lists).
14. Give examples of two mutable and two immutable data types in Python.
 Mutable: list, dict
 Immutable: int, str
15. How do you display output in Python?
Output in Python is displayed using the print() function, e.g., print("Hello, World!").
16. Write a statement to print the value of a variable x.
print(x).

17. What is the purpose of the input() function in Python?


The input() function is used to take user input as a string from the console.
18. How do you take an integer input from a user in Python?
You can take an integer input by using int(input()). For example, x = int(input("Enter a number:
")).

19. What are comments in Python, and why are they used?
Comments are notes in the code that the Python interpreter ignores. They are used to explain and document
code. Single-line comments start with #.
20. How do you write multi-line comments in Python?
Multi-line comments are written inside triple quotes, either ''' or """.
21. Why is indentation important in Python
Indentation in Python is used to define the structure and scope of code blocks, such as loops, conditionals,
and functions. It replaces braces {} used in other languages.
22. What happens if indentation is not correct in Python?
Incorrect indentation will result in an IndentationError or other syntax errors, as Python relies on
indentation to determine code blocks.

31
23. What are operators in Python?
Operators are symbols that perform operations on variables and values. Examples include arithmetic
operators (+, -, *, /), comparison operators (==, >, <), and logical operators (and, or, not).
24. What are logical operators in Python? Give examples.
Logical operators are used to combine conditional statements. Examples include and, or, and not. For
example, x and y, x or y.

25. What is an expression in Python?


An expression is a combination of values, variables, and operators that are evaluated to produce a result. For
example, 5 + 3 is an expression that evaluates to 8.
26. Give an example of a Python expression.
a + b * c is an expression that combines variables and operators to produce a result.
27. What is type conversion in Python?
Type conversion is the process of converting one data type into another, such as converting a string to an
integer using int(), or a float to a string using str().
28. Give an example of explicit type conversion in Python.
int("123") converts the string "123" to the integer 123.
29. How do you define an array using the array module in Python?
Arrays in Python can be created using the array module. For example, import array and arr =
array.array('i', [1, 2, 3]) defines an array of integers.
30. What is the difference between a Python list and an array?
A Python list can hold elements of different data types, while an array (using the array module) is more
memory-efficient and can only hold elements of the same data type.
31. What is the append() method in arrays?
The append() method adds an element to the end of the array. For example, arr.append(6) adds the value
6 to the array.
32. How do you remove an element from an array in Python?
You can remove an element from an array using the remove() method, which removes the first occurrence
of the specified element, or the pop() method to remove an element by index.

||********* END OF UNIT – I *********||

32
UNIT – II

Control Statements:

Selection/Conditional Branching statements: if, if-else, nested if and if-elif-else statements.

 Control statements are an essential part of programming that allow you to control the flow of execution based
on certain conditions. In Python, there are several selection or conditional branching statements that you can
use:

1. If Statement: The if statement is the simplest form of a conditional statement. It allows you to execute a
block of code only if a specific condition is true. The syntax is as follows:

if condition:

# code to be executed if the condition is true

If the condition evaluates to true, the code block is executed.

If the condition is false, the code block is skipped.

Example:

x = 10

if x > 0:

print("x is positive") #x is positive

2. if-else Statement: The if-else statement extends the functionality of the if statement by providing an
alternative block of code to be executed when the condition is false. The syntax is as follows:

33
if condition:

# code to be executed if the condition is true

else:

# code to be executed if the condition is false

If the condition is true, the code inside the if block is executed.


If the condition is false, the code inside the else block is
executed.

Example:

x=5

if x > 0:

print("x is positive") #x is positive

else:

print("x is non-positive")

34
3. Nested if Statements: Nested if statements allow you to include an if statement inside another if
statement. This allows for more complex decision-making based on multiple conditions.
The syntax is as follows:

if condition1:

# code to be executed if condition1 is true

if condition2:

# code to be executed if both condition1 and condition2 are true

Nested if statements can be extended further with additional levels of nesting.

Example:

x = 10

y=5

if x > 0:

if y > 0:

print("Both x and y are positive") # Both x and y are positive

4. If-elif-else Statement: The if-elif-else statement provides multiple alternative conditions to be checked.
It allows you to specify multiple conditions and corresponding code blocks to be executed based on the
first true condition. The syntax is as follows:

if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition1 is false and condition2 is true
else:
# code to be executed if both condition1 and condition2 are false

35
 The conditions are evaluated in order, and the code block corresponding to the first true condition is executed.
If none of the conditions are true, the code inside the else block is executed.

 These control statements provide flexibility in executing different blocks of code based on specific conditions.

By using if, if-else, nested if, and if-elif-else statements, you can create dynamic and conditional logic in your
Python programs.

Example: day=input(“enter day”)

if day == Monday":

print("It's Monday")
elif day == "Tuesday":

print("It's Tuesday")
elif day == "Wednesday":

print("It's Wednesday")

else:

print("It's some other day")

Run the program

enter day

Wednesday

o/p It's Wednesday

Iterative Statements: while loop, for loop, else suite in loop and nested loops.

 Iterative statements, such as while loops, for loops, else suite in loops, and nested loops, allow you to repeat
a block of code multiple times. Let's explore each of these statements:
36
1. While Loop: A while loop executes a block of code repeatedly as long as a given condition is true. The
syntax is as follows:

while condition:

# code to be executed

The condition is checked before each iteration, and if it is true, the


code block is executed. The loop continues until the condition
becomes false.

Example:

count = 0

while count < 5:

print(count)

count += 1

# Output: 0 1 2 3 4

2. for Loop: A for loop is used to iterate over a sequence (such as a list, string, or range) or any iterable
object. It executes a block of code for each element in the sequence. The syntax is as follows:

for element in sequence:

# code to be executed

The loop variable "element" takes on the value of each item in the sequence during each iteration.

37
Range() function:

 The range( ) function is a built-in function in Python that is used to iterate over a
sequence of numbers.

Syntax:

range(beg, end, [step])

 The range( ) produces a sequence of numbers starting with beg (inclusive) and
ending with one less than the number end.

 The step argument is option (that is why it is placed in brackets). By default, every
number in the range is incremented by 1 but we can specify a different increment
using step. It can be both negative and positive, but not zero.

Example: Program to print first n numbers using the range() in a for loop

 If range( ) function is given a single argument, it produces an object with values from 0 to
argument-1. For example: range(10) is equal to writing range(0, 10).

 If range( ) is called with two arguments, it produces values from the first to the second. For
example, range(0, 10) gives 0-9.

38
Example 1:

fruits = ["apple", "banana", "cherry"]for


fruit in fruits:

print(fruit)

Output 1:

apple
banana
cherry

Example 2 :

n = 5 # Change the value of n as per your requirement

# Initialize a variable to store the sum


sum_of_numbers = 0

# Iterate from 1 to n using a for loop


for i in range(1, n+1):

sum_of_numbers += i

# Print the sum

print("The sum of the first", n, "numbers is:", sum_of_numbers)

Output 2:

The sum of the first 5 numbers is: 15

3. else suite in Loops: Python allows an else suite to be associated with both while and for loops. The code
in the else block is executed when the loop terminates naturally (i.e., when the loop condition becomes
false or the sequence is exhausted).

Example with a while loop:


39
count = 0

while count < 5:

print(count)
count += 1

else:

print("Loop completed")

Output:

Loop completed
Example with a for loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

else:

print("All fruits have been printed")

Output:

apple
banana
cherry

All fruits have been printed

4. Nested Loops: Nested loops are loops within loops, allowing for more complex iterations. You can have
a for loop inside another for loop, a while loop inside a for loop, or vice versa.
40
Example of nested loops:
for i in range(3):

for j in range(2):

print(i, j)

Output:

0 0

0 1

1 0

1 1

2 0

2 1

In this example, the outer loop iterates from 0 to 2, and for each iteration, the inner loop iterates from 0 to

1. The print statement displays the values of both loop variables. These iterative statements provide the
ability to repeat code execution based on specific conditions or sequences. You can use while loops, for
loops, else suites in loops, and nested loops to perform various repetitive tasks and control the flow of
your program.

Condition-controlled and Counter-controlled Loops :

41
Jump Statements:

break, continue and pass statements.

 Jump statements in Python, including the break, continue, and pass statements, allow you to control the
flow of a loop or program execution. Let's explore each of these statements:

1. break Statement: The break statement is used to terminate the execution of a loop prematurely. When
encountered within a loop, it immediately exits the loop and continues with the next statement following
the loop. It is commonly used to exit a loop when a specific condition is met. The break statement can be
used with both for and while loops.

Example:

for i in range(1, 6):

if i == 3:

break

print(i) #Output: 1 2

o In this example, the loop runs from 1 to 5, but when the value of i becomes 3, the break statement is
encountered, and the loop is terminated.

o Hence, the break statement is used to exit a loop from any point with in its body, by
passing its normal termination expression. Below, Figure shows the transfer of control
when the break statement is encountered.

2. continue Statement: The continue statement is used to skip the rest of the code within a loop for the
current iteration and proceed to the next iteration. It allows you to bypass specific iterations of a loop

42
based on a certain condition. The continue statement can be used with both for and while loops.

Example:

for i in range(1, 6):

if i == 3:

continue

print(i) #Output: 1 2 4 5

 In this example, when the value of i is 3, the continue statement is encountered, causing the
remaining code within the loop for that iteration to be skipped.

3. pass Statement: The pass statement is a placeholder statement that does nothing. It is used when a
statement is syntactically required but you want to do nothing. It is often used as a placeholder for code
that will be implemented later. It allows you to avoid getting a syntax error when an empty block is not
allowed.

Example:

for i in range(1, 6):

if i == 3:

pass

else:

print(i) #Output: 1 2 4 5

 In this example, when the value of i is 3, the pass statement is encountered, which does nothing. The

43
program continues with the next iteration of the loop without executing any code specific to that
condition.

Example:

These jump statements, break, continue, and pass, provide control over the flow of a loop or program
execution. They allow you to modify the default behavior of loops and handle specific conditions as
needed.

Difference between break, continue and pass

 The break statement terminates the execution of the nearest enclosing loop in which it appears.

 The continue statement skips the rest of the statements in the loop transfer the control un-conditionally to
the loop-continuation portion of the nearest enclosing loop.

 The pass statement is a do-nothing statement in a loop. It is just added to make the loop syntactically
correct. i.e, a pass statement is written as we can not have an empty body of the loop.

The lse Statement Used With Loops:

 In Python you can have the else statement associated with a loop statements.

 If the else statement is used with a for loop, the else statement is executed when the
loophas completed iterating.

 But when used with the while loop, the else statement is executed when the
conditionbecomes false.

Example:

44
Sample Programs:

Python program that tests whether a given number is even or odd:


Program 1:

# Take input from the user

number = int(input("Enter a number: "))

# Check if the number is even or odd


if number % 2 == 0:

print(number, "is even")


else:

print(number, "is odd")

Output:

Enter a number: 7
7 is odd

Program 2:

# Take input from the user

number = int(input("Enter a number: "))

# Initialize the factorial to 1


factorial = 1

45
# Calculate the factorial using a for loop
for i in range(1, number + 1):

factorial *= i

# Print the factorial

print("The factorial of", number, "is", factorial)

Output:

Enter a number: 5

The factorial of 5 is 120

Using while loop to find factorial of a given number or n!

f=1

n=int(input(“enter value”))

i=1

while(i<=n):

f=f*i

i=i+1

# Print the factorial

print("The factorial of", number, "is", f)

Output:

enter value 5

The factorial of 5 is 120

46
Dynamic Programming in Python
Definition:
Dynamic programming in Python refers to the ability of a program to change its structure, behavior, or state
during runtime. This is accomplished by dynamically creating, modifying, or executing Python code. It allows
greater flexibility, enabling you to manipulate code, such as adding functions or altering classes at runtime.
Syntax:
Python supports dynamic programming with constructs like:
 exec(): Executes Python code dynamically.
 eval(): Evaluates expressions dynamically.
 getattr(), setattr(), delattr(): Dynamically get, set, or delete attributes.
 First-class functions: Functions are treated as objects and can be passed around, assigned to variables, or
modified at runtime.
Example:
code = '''def greet(name):return f"Hello, {name}" '''
exec(code)
print(greet("Alice")) # Output: Hello, Alice
result = eval("5 + 3 * 2")
print(result)

# Output: 11
Explanation:
In the example:
 exec() dynamically defines a function greet(), which is then called like a regular function.
 eval() evaluates the mathematical expression at runtime.
Dynamic programming allows Python to be flexible and adaptable at runtime, making it powerful for developing
dynamic frameworks or APIs.

Meta-programming in Python
Definition:
47
Meta-programming is a programming technique where programs have the ability to treat code as data. In Python,
meta-programming allows you to create functions, modify or inspect code, and alter classes or functions
dynamically. Meta-programming typically involves manipulating class definitions or functions.
Syntax:
Common meta-programming tools in Python include:
 Decorators: Functions that modify the behavior of other functions or methods.
 Metaclasses: Special classes that define how other classes behave.
 type(): Dynamically creates a class.
 __call__, __new__, and __init__ methods**: Control instance creation and initialization.
Example:
def debug(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} and {kwargs}")
return func(*args, **kwargs)
return wrapper
def add(a, b):
return a + b
print(add(2, 3)) # Output: Calling add with (2, 3) and {} \n 5
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
Explanation:
 Decorators: The debug decorator modifies the behavior of the add function, printing debug information
before calling the original function.
 Metaclasses: Meta is a metaclass that intercepts the class creation process. When MyClass is defined, the
metaclass prints a message.
Meta-programming is useful for writing flexible and reusable code that can adapt dynamically to the
context in which it is used, such as frameworks and libraries.

Control Flow in Python


Definition:
48
Control flow refers to the order in which individual statements, instructions, or function calls are executed or
evaluated in a Python program. Python provides various constructs to control the flow of execution based on
conditions or iterations.
Control Flow Constructs:
1. Conditional Statements: if, elif, else
2. Looping Statements: for, while
3. Control Statements: break, continue, pass
4. Exception Handling: try, except, finally
Syntax:
if condition:
elif another_condition:
# block of code if another_condition is true
else:
# block of code if both conditions are false

for item in iterable:


# block of code

while condition:
# block of code
break # Exits the loop
continue # Skips to the next iteration
pass # Placeholder statement
Example:
python
Copy code
# Conditional statement
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

# Loop with control statements


49
for i in range(5):
if i == 3:
break # Breaks out of the loop when i is 3
print(i)

# Output: 0, 1, 2
Explanation:
 The if-else block checks a condition and executes the corresponding block of code based on whether the
condition is True or False.
 In the loop example, the break statement terminates the loop when i == 3, preventing further iterations.
Control flow structures allow a program to make decisions and repeat actions, which are essential for
creating flexible and efficient programs.

2 marks
1. What is an if statement in Python?
The if statement is a conditional branching statement that executes a block of code if a given condition
evaluates to True.
Example:
if x > 10:
print("x is greater than 10")
2. What is the purpose of an if-else statement in Python? The if-else statement allows for an alternative code block
to be executed when the if condition is False.
Example:
if x > 10:
print("x is greater than 10")
else:
print("x is not greater than 10")
3. What is a nested if statement in Python?
A nested if statement is an if statement inside another if statement, allowing for multiple levels of condition
checks. Example:
if x > 10:
if x < 20:
print("x is between 10 and 20")
4. How does the if-elif-else statement work in Python?
50
The if-elif-else statement is used when there are multiple conditions to check. If the first condition is false, the
elif statements are checked sequentially until one is true.
Example:
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than 20")
else:
print("x is 10 or less")
5. What is a while loop in Python? A while loop repeatedly executes a block of code as long as a given condition is
True.
Example:
while x < 10:
print(x)
x += 1
6. How does a for loop work in Python?
A for loop iterates over a sequence (e.g., list, tuple, string) and executes the block of code for each element.
Example:
for i in range(5):
print(i)
7. What is the else suite in loops in Python?
The else clause in a loop is executed after the loop finishes its iteration, unless the loop is terminated by a break
statement.
Example:
for i in range(5):
print(i)
else:
print("Loop completed")
8. What is a nested loop in Python?
A nested loop is a loop inside another loop, allowing for iterating over multiple sequences or ranges.
Example:
for i in range(3):
for j in range(2):
print(i, j)
51
9. What does the break statement do in Python?
The break statement is used to exit a loop prematurely when a specific condition is met. Example:
for i in range(5):
if i == 3:
break
print(i)
10. What is the purpose of the continue statement?
The continue statement skips the current iteration of a loop and proceeds to the next iteration.
Example:
for i in range(5):
if i == 3:
continue
print(i)
11. What is the pass statement used for in Python?
The pass statement is a placeholder that does nothing and is used where a statement is syntactically required but
no action is needed.
Example:
if x > 0:
pass
12. What is dynamic programming in Python?
Dynamic programming in Python refers to the ability to modify or create code during runtime using constructs
like exec(), eval(), or dynamic function creation.
Example:
code = 'print("Hello")'
exec(code) # Outputs: Hello
13. What is meta-programming in Python?
Meta-programming refers to writing code that manipulates other code, such as using decorators, metaclasses, or
manipulating attributes dynamically.
Example:
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)

||********* END OF UNIT – II *********||


52
UNIT – III

Functions:

 A function is a block of organized and reusable program code that performs a single, specific, and
well-defined task.

 Python enables its programmers to break up a program into functions, each of which can be written
more or less independently of the others. Therefore, the code of one function is completely insulated
from the codes of the other functions.

Figure 1: Calling a function

 In figure 1 which explains how a function func1() is called to perform a well- defined task. As soon
as func1() is called, the program control is passed to the first statement in the function. All the
statements in the function are executed and then the program control is passed to the statement
following the one that called the function.

Figure 2: Function calling another function

 In figure 2 func1() calls function named func2(). Therefore, func1() is known as the calling function
and func2() is known as the called function. The moment the compiler encounters a function call,
instead of executing the next statement in the calling function, the control jumps to the statements
that are a part of the
53
Need for functions:

 Each function to be written and tested separately.

 Understanding, coding and testing multiple separate functions are far easier than doing the same
for one huge function.

 When a big program is broken into comparatively smaller functions, then different
programmers working on that project can divide the workload by writing different
functions.

 All the libraries in Python contain pre-defined and pre-tested functions which the
programmers are free to use directly in their programs, without worrying about their code details.
This speed up program development.

 Like Python libraries, programmers can also make their own functions and use them from
different points in the main program or any other program that needs its

functionalities. So code reuse is one of the most prominent reasons to use functions.

Figure 3: Top-down approach of solving a problem

Function Definition

Function Declaration and Definition:

 A function, f that uses another function g, is known as the calling function and g is known as
the called function.

 The inputs that the function takes are known as arguments/parameters.

 When a called function returns some result back to the calling function, it is said to return that

54
result.

 The calling function may or may not pass parameters to the called function. If the called
function accepts arguments, the calling function will pass parameters, else not.

• Function declaration is a declaration statement that identifies a function with its name, a list of
arguments that it accepts and the type of data it returns.

• Function definition consists of a function header that identifies the function, followed by
the body of the function containing the executable code for that function.

Function Definition

 There are two basic types of functions

1. built-in functions eg: dir(), len(), abs() etc.,

2. user defined functions.

 Function blocks starts with the keyword def.

 The keyword is followed by the function name and parentheses (( )).

 After the parentheses a colon (:) is placed.

 Parameters or arguments that the function accept are placed within parentheses.

 The first statement of a function can be an optional statement – the Docstring describe
what the function does.

 The code block within the function is properly indented to form the block code.

 A function may have a return[expression] statement. That is, the return statement is
optional.

 You can assign the function name to a variable. Doing this will allow you to call same

55
function using the name of that variable.

Figure 4: Program that subtracts two numbers using a function.

Figure 5: The syntax of a function definition.

Function Call

 In Python, to call or invoke a function, you simply use the function name followed by parentheses,
optionally passing any required arguments within the parentheses. The function call executes the
code inside the function body and returns any specified result (if applicable).

 Here is the syntax for calling a function in Python:

function_name(argument1, argument2, ...)

 Let's use an example to demonstrate a function call:

Example:

def greet(name):

print("Hello, " + name + "!")


# Call the function

greet("Alice")
Output:

Hello, Alice!

56
 In this example, the function greet is defined with a single parameter name. To call the function,
we use greet("Alice"), passing the argument "Alice" within the parentheses. The function is
executed, and the message "Hello, Alice!" is printed to the console.

 You can call functions with different arguments depending on their defined parameters. It's
important to provide the correct number and order of arguments to match the function's parameter
requirements.

Example 1:

a function that displays string repeatedly.

Example 2:

Program to demonstrate mismatch of name of function parameters and arguments.

Note: Names of variables in function call and header of function definition may vary.

57
Example 3:

Arguments may be passed in the form of expressions to the called function.

Example 3:

Program to add two integers using functions

Variable Scope and its Lifetime-Return Statement.

Variable scope and lifetime:

 In python, you cannot just access any variable from any part of your program. Some of the variables
may not even exist for the entire duration of the program. In which part of the program you can
access a variable and in which parts of the program a variable exits depends on how the variable has

58
been declared. Therefore, we need to understand these two things:

1. Scope of the variable: Part of the program in which a variable is accessible is called its scope.

2. Lifetime of the variable: Duration for which the variable exits it‟s called its lifetime.

Local and Global variables:

 A variable which is defined within a function is local to that function. A local variable can be
accessed from the point of its definition until the end of the function in which it is defined. It exists
as long as the function is executing.

 Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside a function, a new local variable is created.

 Global variables are those variables which are defined in the main body of the program file.
They are visible throughout the program file. As a good programming habit, you must try to avoid
the use of global variables because they may get altered by mistake and then result in erroneous
output.

Python program that demonstrates the differences between global and local variables:
Program:

# Global variable
global_var = 10

def modify_global():

# Accessing global variable


global global_var
global_var += 5

print("Inside modify_global():", global_var)

def modify_local():
# Local variable

59
local_var = 5

local_var += 2

print("Inside modify_local():", local_var)

# Main program

print("Global variable (before modification):", global_var)


modify_global()

print("Global variable (after modification):", global_var)

print("")

modify_local()

# Attempt to access the local variable outside the function will raise an error
print("Local variable (outside function):", local_var)

Output:

Global variable (before modification): 10


Inside modify_global(): 15

Global variable (after modification): 15

Inside modify_local(): 7
Traceback (most recent call last):

File "program.py", line 22, in <module>

print("Local variable (outside function):", local_var)


NameError: name 'local_var' is not defined

60
Explanation:

Python program that demonstrates the differences between global and local variables:

1. We start by declaring a global variable global_var with an initial value of 10.

2. The modify_global() function is defined to access the global variable using the global
keyword. It increments the value of global_var by 5 and prints the modified value.

3. The modify_local() function defines a local variable local_var with an initial value of 5.
It then increments local_var by 2 and prints the modified value.

4. In the main program, we first print the value of global_var before any modifications.

5. Next, we call the modify_global() function, which modifies the global variable global_var
by adding 5. We then print the value of global_var after the modification.

6. After that, we call the modify_local() function, which modifies the local variable
local_var by adding 2. However, when we try to access local_var outside the function, it
will raise a NameError because it is a local variable and not accessible in the global scope.

By running this program, you'll observe the difference between global and local
variables. The global variable can be accessed and modified both inside and outside
functions, while local variables are only accessible within the scope of the function where
they are defined.

Comparison between global and local variables

Global variables Local variables

They are defined in the main body of They are defined within a function and

the program file. is local to that function.

They can be accessed throughout the program life. They can be accessed from the point of its definition
until the end of the block

in which it is defined.

61
Global variables are accessible to all functions in the They are not related in any way to other variables
program. with the same names

used outside the function.

Using the Global Statement

 To define a variable defined inside a function as global, you must use the global statement. This
declares the local or the inner variable of the function to have module scope.

Key points to remember:

 You can have a variable with the same name as that of a global variable in the program. In such a
case a new local variable of that name is created which is different from the global variable.

Example 1: Program to demonstrate the use of global statement.

Resolution of names

 Scope defines the visibility of a name within a block. If a local variable is defined in a block, its
scope is that particular block. If it is defined in a function, then its scope is all blocks within that
function.

62
 When a variable name is used in a code block, it is resolved using the nearest enclosing scope. If no
variable of that name is found, then a NameError is raised. In the code given below, str is a global
string because it has been defined before calling the function.

 Following Program that demonstrates using a variable defined in global namespace.

The Return Statement

• The syntax of return statement is, return [expression]

• The expression is written in brackets because it is optional. If the expression is present, it is


evaluated and the resultant value is returned to the calling function. However, if no expression is
specified then the function will return none.

• The return statement is used for two things.

 Return a value to the caller

 To end and exit a function and go back to its caller.

 The following Program to write another function which returns an integer to the caller.

63
Function Arguments:

 In this section we will discuss some more ways of defining a function.

1. Required arguments

2. Keyword arguments

3. Default arguments

4. Variable-length arguments

Required Arguments

 In the required arguments, the arguments are passed to a function in correct positional order.
Also, the number of arguments in the function call should exactly match with the number of
arguments specified in the function definition

Example:

Keyword Arguments

 When we call a function with some values, the values are assigned to the arguments based on
their position. Python also allow functions to be called using keyword arguments in which the
order (or position) of the arguments can be changed. The values are not assigned to arguments
according to their position but based on their name (or keyword).

 Keyword arguments are beneficial in two cases.

 First, if you skip arguments.

 Second, if in the function call you change the order of parameters.

64
Example:

Default Arguments and Variable Length Arguments

Default Arguments:

 Python allows users to specify function arguments that can have default values. This means that
a function can be called with fewer arguments than it is defined to have.

 That is, if the function accepts three parameters, but function call provides only two arguments,
then the third parameter will be assigned the default (already specified) value. The default value
to an argument is provided by using the assignment operator (=). Users can specify a default
value for one or more arguments.

Example:

65
Variable Length Arguments

 In some situations, it is not known in advance how many arguments will be passed to a function.
In such cases, Python allows programmers to make function calls with arbitrary (or any) number
of arguments.

 When we use arbitrary arguments or variable length arguments, then the function definition use
an asterisk (*) before the parameter name. The syntax for a function using variable arguments
can be given as,

Example:

Recursion.

Lambda Functions or Anonymous Functions

 Lambda or anonymous functions are so called because they are not declared as other functions
using the def keyword. Rather, they are created using the lambda keyword.

 Lambda functions are throw-away functions, i.e. they are just needed where they have been
created and can be used anywhere a function is required. The lambda feature was added to Python
due to the demand from LISP programmers.

 Lambda functions contain only a single line. Its syntax can be given as,
66
Example:

Documentation Strings

 Docstrings (documentation strings) serve the same purpose as that of comments, as they are
designed to explain code. However, they are more specific and have a proper syntax.

Example:

Python Strings:

 In Python, strings are sequences of characters and can be accessed using indexing and traversing
techniques. Let's explore how to perform these operations:
67
1. Indexing: String indexing allows you to access individual characters within a string by referring
to their position. The indexing starts from 0 for the first character and goes up to length-1 for the
last character.

Example:

my_string = "Hello, World!"


print(my_string[0]) # Output: 'H'
print(my_string[7]) # Output: 'W'
print(my_string[-1]) # Output: '!'

Negative indexing is also possible, where -1 refers to the last character, -2 refers to the second-
last character, and so on.

2. Traversing: Traversing a string means iterating over each character in the string. You can use
loops, such as for or while, to traverse the string and perform operations on each character.

Example using a for loop:

my_string = "Hello, World!"


for char in my_string:
print(char)

Output:

Hello,World!

Example using a while loop:


my_string = "Hello, World!"
i=0

while i < len(my_string):

print(my_string[i])
i += 1

Output: Same as the previous example

68
Concatenating, Appending and Multiplying Strings

 In Python, you can concatenate, append, and multiply strings to create new strings or modify
existing ones. Here's how you can perform these operations:

1. Concatenating Strings: Concatenation allows you to combine multiple strings together into a
single string using the + operator.

Example:

str1 = "Hello"
str2 = "World"

result = str1 + ", " + str2

print(result) # Output: "Hello, World"

In this example, we concatenate the strings str1, ", ", and str2 to create a new string result.

2. Appending to Strings: In Python, strings are immutable, so you cannot directly append or
modify an existing string. However, you can create a new string by concatenating the existing
string with another string.

Example:

str1 = "Hello"
str2 = " World"
result = str1 + str2

print(result) # Output: "Hello World"

Here, we concatenate str1 and str2 to create a new string result, effectively appending str2 to

str1.

3. Multiplying Strings: You can multiply a string by an integer to repeat it multiple times.

Example:

str1 = "Hello"
multiplied_str = str1 * 3

print(multiplied_str) # Output: "HelloHelloHello"

 In this example, we multiply str1 by 3, resulting in the string being repeated three times.

 Remember, when performing these operations, you are creating new strings rather than

69
modifying the original ones due to the immutability of strings in Python.

String operations

Immutable Strings

 In Python, strings are immutable, which means that once a string is created, it cannot be changed.
If you try to modify a string, it will result in creating a new string object rather than modifying the
original one.

 Here's an example to illustrate the immutability of strings:

my_string = "Hello, World!"

# Attempting to modify the string

my_string[0] = 'J' # This will raise a TypeError


# Concatenating to create a new string
new_string = 'J' + my_string[1:]
print(new_string) # Output: "Jello, World!"

 As you can see, when we tried to modify the first character of my_string, it resulted in a TypeError
because strings do not support item assignment. Instead, we created a new string new_string by
concatenating the desired character with the rest of the original string.

 This immutability property of strings ensures that once a string is created, its contents remain
unchanged, providing consistency and safety when working with strings in Python.

String Formatting Operator

 The % operator takes a format string on the left (that has %d, %s, etc) and the corresponding values
in a tuple on the right.

 The format operator, % allow users to construct strings, replacing parts of the strings with the
data stored in variables. The syntax for the string formatting operation is:

 "<Format>" % (<Values>)
Example:

70
Built-in String Methods and Functions

 Python provides a variety of built-in string methods and functions to manipulate and operate on
strings. Here are some commonly used ones:

1. String Methods:

 str.upper(): Converts the string to uppercase.

 str.lower(): Converts the string to lowercase.

 str.capitalize(): Capitalizes the first character of the string.

 str.title(): Capitalizes the first character of each word in the string.

 str.strip(): Removes leading and trailing whitespace from the string.

 str.startswith(prefix): Checks if the string starts with the specified prefix.

 str.endswith(suffix): Checks if the string ends with the specified suffix.

 str.replace(old, new): Replaces occurrences of the specified substring with a new


substring.

 str.split(separator): Splits the string into a list of substrings based on the separator.

 str.join(iterable): Joins elements of an iterable (e.g., a list) into a string using the
specified string as a separator.

Example:

my_string = " Hello, World! "

print(my_string.upper()) # Output: " HELLO, WORLD! "


print(my_string.strip()) # Output: "Hello, World!"
print(my_string.startswith("Hello")) # Output:True
print(my_string.split(",")) # Output: [' Hello', ' World! ']
71
2. String Functions:

 len(str): Returns the length (number of characters) of the string.

 str.find(substring): Searches for the first occurrence of the substring in the string and returns
its index. Returns -1 if not found.

 str.count(substring): Returns the number of occurrences of the substring in the string.

 str.upper(), str.lower(), str.capitalize(), str.title(): Similar to the corresponding string methods


mentioned above.

Example:

my_string = "Hello,World!"
print(len(my_string)) # Output: 12
print(my_string.find("World")) # Output: 6
print(my_string.count("l")) # Output: 3

 These are just a few examples of the built-in string methods and functions available in Python.

 There are many more that you can explore in the Python documentation.

 These methods and functions provide powerful tools for string manipulation and analysis.

String Comparison.

 In Python, you can compare strings using comparison operators to determine their relative order or
equality. Here are the commonly used comparison operators for string comparison:

1. Equality (==): The equality operator (==) compares two strings and returns True if they have
the same characters in the same order, and False otherwise.

Example:

pythonCopy code
str1 = "Hello"
str2 = "Hello"
str3 = "World"

print(str1 == str2) # Output: True


print(str1 == str3) # Output: False

2. Inequality (!=): The inequality operator (!=) checks if two strings are not equal and returns

True if they are different, and False if they are equal.


72
Example:

str1 = "Hello"
str2 = "Hello"
str3 = "World"

print(str1 != str2) # Output: False


print(str1 != str3) # Output: True

3. Comparison Operators (<, <=, >, >=): The comparison operators (<, <=, >, >=) compare
strings lexicographically based on their ASCII values. The comparison is done character by
character from left to right.

Example:

str1 = "apple"
str2 = "banana"

print(str1 < str2) # Output: True


print(str1 <= str2) # Output: True
print(str1 > str2) # Output: False
print(str1 >= str2) # Output: False

 In this example, "apple" is lexicographically less than "banana" because the first differing
character 'a' in "apple" has a lower ASCII value than 'b' in "banana".

 It's important to note that string comparison is case-sensitive. Uppercase letters are considered
different from lowercase letters during comparison.

 These comparison operators can be used to compare strings based on their equality, inequality,
or lexicographical order, allowing you to perform various string comparisons and make
decisions based on the results.

Modules:

 In Python, modules are files containing Python definitions and statements that provide additional
functionality. Modules allow you to organize your code into reusable and self-contained units. They
can contain functions, classes, variables, and other objects that can be used in other Python
programs.

 Python comes with a standard library that includes a wide range of modules covering various

73
domains, such as mathematics, file I/O, networking, data processing, and more. Additionally, there
is a vast ecosystem of third-party modules and libraries available that extend Python's capabilities
even further.

Import Statement

 In Python, the import statement is used to import and make use of external modules or libraries in
your code. Modules are Python files that contain definitions and statements that provide additional
functionality.

 There are a few different ways to use the import statement:

1. Importing an Entire Module: You can import the entire module by using the import keyword
followed by the module name.

Example:

import math

print(math.sqrt(16)) # Output: 4.0

 In this example, the math module is imported, and the sqrt() function from the math

module is used to calculate the square root of 16.

2. Importing Specific Items from a Module: If you only need certain items from a module, you can
import them directly by specifying their names using the from keyword.

Example:

from math import sqrt, pi


print(sqrt(16)) # Output: 4.0

print(pi) # Output: 3.141592653589793

In this example, only the sqrt() function and the constant pi are imported from the math module.

3. Importing a Module with an Alias: You can give a module an alias to simplify its usage in your
code by using the as keyword.

Example:

import math as m
print(m.sqrt(16)) # Output: 4.0

 Here, the math module is imported with the alias m, so m.sqrt() is used to access the

74
sqrt() function.

 By using the import statement, you can access various modules and leverage the functions, classes,
and variables they provide. Python has a rich ecosystem of modules and libraries that extend its
capabilities, allowing you to perform a wide range of tasks.

The Python module

 Here are some commonly used modules in Python:

 math: Provides mathematical functions and constants.

 random: Allows you to generate random numbers and make random selections.

 os: Provides operating system-related functionalities, such as file and directory manipulation.

 datetime: Enables working with dates, times, and time deltas.

 json: Allows for JSON (JavaScript Object Notation) encoding and decoding.

 requests: Simplifies making HTTP requests and working with APIs.

 numpy: Provides advanced mathematical operations and data manipulation capabilities.

 pandas: Offers data manipulation and analysis tools, particularly for structured data.

 matplotlib: Enables the creation of visualizations and plots.

 tkinter: Provides a GUI (Graphical User Interface) toolkit for creating desktop applications.

 To use a module in your Python code, you typically need to import it using the import statement.
Once imported, you can access the functions, classes, and variables defined in the module and use
them in your program.

dir() function

 In Python, the dir() function is a built-in function that returns a sorted list of names in the current
local scope or the names of an object's attributes if an object is passed as an argument. The dir()
function can be used to explore the available attributes and methods of an object or to examine the
variables and functions in the current scope.

 Here are a few ways you can use the dir() function:

1. Without an Argument: Calling dir() without any argument returns a list of names in the current
local scope. It provides the names of variables, functions, and other objects defined in the current
scope.

75
Example:

x = 10

y = "Hello"

print(dir()) # Output: ['__builtins ', '__doc ', '__loader__', '__name__', '__package ', '__spec__', 'x', 'y']

 In this example, the dir() function returns a list of names in the current local scope,
including the variables x and y.

2. With an Object as an Argument: Passing an object as an argument to dir() returns a sorted list
of attributes and methods available for that object.

Example:

my_list = [1, 2, 3]
print(dir(my_list))

 The output of this example will be a sorted list of attributes and methods available for the my_list

object, including methods like append(), pop(), and attributes like count and index.

 The dir() function is useful for exploring the available attributes and methods of an object or
examining the names defined in the current scope. It can help you discover what functionality is
provided by a module, class, or object and assist in understanding how to interact with them.

Modules and Namespace

 In Python, modules play a crucial role in organizing and encapsulating code. They provide a way to
group related functions, classes, and variables into separate namespaces. A namespace is a mapping
from names to objects, and it serves as a container for those objects.

 When a module is imported, it creates a separate namespace, allowing you to refer to its contents
using the module name as a prefix. This prevents naming conflicts and provides better code
organization. Each module has its own namespace, and different modules can define objects with
the same name without causing conflicts.

 For example, let's consider a module named "math_functions.py" that contains various
mathematical functions:

# math_functions.py
def square(x):

return x ** 2
76
def cube(x):

return x ** 3
PI = 3.14159

 To use this module and its functions in another Python file, you can import it using the import

statement:

import math_functions
print(math_functions.square(5)) # Output: 25

print(math_functions.PI) # Output: 3.14159

 In this example, the math_functions module is imported, and its functions and variable PI can be
accessed using the module name as a prefix.

 You can also use the from keyword to import specific items from a module directly into the current
namespace:

from math_functions
import square, PI

print(square(5)) # Output: 25

print(PI) # Output: 3.14159

 In this case, you can directly use the square() function and PI variable without referencing the
module name.

 Namespaces provided by modules help in organizing code, avoiding naming conflicts, and
promoting code reusability. It allows you to use modules as self-contained units, bringing in only
the necessary objects into your code's namespace, thus improving clarity and maintainability.

Defining our own modules.

 In Python, you can define your own modules to encapsulate related functions, classes, and variables into
separate files for reusability. This allows you to organize your code and create custom libraries.

Here's an example of how to define your own module:

1. Create a new Python file with a .py extension. For example, let's create a module named my_module.py.

77
2. Define functions, classes, and variables in the module file. These will be the contents of your module.

# my_module.py
def greet(name):

print("Hello, " + name + "!")


def square(x):

return x ** 2
PI = 3.14159

3. Save the file.

Now that you have created your module, you can use it in other Python files by importing it. To import your
module, make sure that the module file (my_module.py in this case) is in the same directory as the file that
you want to import it into.

Here's an example of how to import and use the my_module module:

import my_module

my_module.greet("Alice") # Output: Hello, Alice!


print(my_module.square(5)) # Output: 25
print(my_module.PI) # Output: 3.14159

In this example, the my_module module is imported using the import statement, and its functions greet()

and square(), as well as the variable PI, can be accessed using the module name as a prefix.

You can also import specific items from the module directly into the current namespace using the from

keyword:

from my_module import greet, square,


PIgreet("Bob") # Output: Hello, Bob!
print(square(3)) # Output: 9

print(PI) # Output: 3.14159

By defining your own modules, you can create reusable code units that can be easily imported and used in
other Python programs. This allows for better code organization, modularity, and promotes code reuse
across multiple projects.

78
1. What is a function definition in Python?
A function definition in Python specifies a block of reusable code that can be called to perform a task. It is
defined using the def keyword.
Example:
def greet():
print("Hello")
2. What is a function call in Python?
A function call is the execution of a defined function. You call the function by using its name followed by
parentheses.
Example:
greet() # Calls the greet function
3. What is variable scope and its lifetime in Python?
Scope refers to the area of the program where a variable is accessible. A variable's lifetime is the duration it
exists in memory. Local variables exist within a function and are destroyed once the function ends.
4. What is the return statement in Python?
The return statement is used in a function to send a value back to the caller and exit the function
Example:
def add(a, b):
return a + b
5. What are function arguments in Python?
Function arguments are values passed to a function when it is called. These values are used by the function to
perform operations.
Example:
def add(a, b):
return a + b
6. What is a function decorator in Python?
A function decorator is a function that takes another function as an argument, extends or alters its behavior,
and returns a new function.
Example:
@decorator
def function():
pass

7. What are required arguments in Python functions?


79
Required arguments must be passed when calling a function; otherwise, Python raises an error.
Example:
def add(a, b):
return a + b
8. What are keyword arguments in Python?
Keyword arguments are passed to a function by explicitly naming the parameter and assigning a value,
regardless of the order.
Example:
add(a=5, b=10)
9. What are default arguments in Python?
Default arguments are parameters that assume a default value if no argument is provided during a function
call.
Example:
def greet(name="User"):
print(f"Hello, {name}")
10. What are variable-length arguments in Python?
Variable-length arguments allow a function to accept any number of arguments. They are defined using *args
for positional and **kwargs for keyword arguments.
Example:
def func(*args):
for arg in args:
print(arg)
11. What is recursion in Python?
Recursion is when a function calls itself to solve a problem. It must have a base case to avoid infinite loops.
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
12. What are string operations in Python?
String operations include concatenation (+), repetition (*), slicing ([]), and membership (in).
Example:
s = "hello"
80
print(s[1:4]) # "ell"
13. What does it mean that strings are immutable in Python?
In Python, strings are immutable, meaning once created, they cannot be changed. Any modification creates a
new string.
Example:
s = "hello"
s[0] = "H" # Raises an error
14. Name a few built-in string methods in Python.
Some common string methods include upper(), lower(), strip(), replace(), and find(). Example:
s = "hello"
print(s.upper()) # "HELLO"
15. How are strings compared in Python?
Strings are compared lexicographically, meaning character by character according to their Unicode values.
Example:
print("apple" < "banana") # True
16. What is the purpose of the import statement in Python?
The import statement is used to include external modules or libraries in a Python program, making their
functions and variables accessible.
Example:
import math
print(math.sqrt(4)) # 2.0
17. What is a Python module?
A module is a file containing Python code (functions, variables, classes) that can be imported and used in
other Python scripts.
Example: math, os, sys are standard modules.
18. What is the dir() function used for in Python?
The dir() function returns a list of all the attributes and methods of an object, including modules, classes, and
functions.
Example:
import math
print(dir(math)) # Lists all functions in the math module
19. What is a namespace in Python?
A namespace is a container that holds names (variables, functions, etc.) and their corresponding values.
Different namespaces prevent naming conflicts in Python.
81
20. How do you define your own module in Python?
To define your own module, create a .py file containing Python code (functions, variables). You can then
import it in another script using the import statement.
Example:
# mymodule.py
def greet():
print("Hello")
# main.py
import mymodule
mymodule.greet() # Output: Hello

||********* END OF UNIT – III *********||

82
UNIT - IV

Lists

Creating a List

 To create a list in Python, you can use square brackets [] and separate the elements with commas.
Here's an example:

my_list = [1, 2, 3, 4, 5]

 You can create a list with elements of different types, such as numbers, strings, or even other lists.

Accessing Values in a List:

 You can access individual elements in a list by using indexing. The index of the first element is 0,
the second element is 1, and so on. You can also use negative indexing to access elements from the
end of the list. Here's an example:

my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 5

Updating Values in a List:

 You can update the values in a list by assigning a new value to a specific index. Here's an example:

my_list = [1, 2, 3, 4, 5]

my_list[2] = 10

print(my_list) # Output: [1, 2, 10, 4, 5]


Nested Lists:

 You can have lists within lists, which are called nested lists. This allows you to create a

multidimensional structure. Here's an example:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(nested_list[0][1]) # Output: 2

 Basic List Operations: There are several basic operations you can perform on lists:

 Concatenation: You can concatenate two lists using the + operator.

 Repetition: You can repeat a list a certain number of times using the * operator.
83
 Length: You can find the length of a list using the len() function.

 Membership: You can check if an element is present in a list using the in keyword.

List Methods:

 Lists in Python have built-in methods that allow you to perform various operations on them. Here
are some commonly used list methods:

 append(): Adds an element to the end of the list.

 insert(): Inserts an element at a specified position.

 remove(): Removes the first occurrence of a specified element.

 pop(): Removes and returns the element at a specified index.

 index(): Returns the index of the first occurrence of a specified element.

 sort(): Sorts the list in ascending order.

 reverse(): Reverses the order of the elements in the list.

 These are just a few examples of list methods available in Python. You can explore more methods
in the Python documentation. Remember that lists in Python are mutable, which means you can
change their elements after they are created.

Sample program using lists:

def get_names():
names = []

num_names = int(input("Enter the number of names: "))


for i in range(num_names):

name = input("Enter name: ")


names.append(name)

return names

def display_names(names):
print("List of names:")
for name in names:

84
print(name)

# Main program
names_list = get_names()
display_names(names_list)

Output:

Enter the number of names: 3


Enter name: Alice

Enter name: Bob


Enter name: Carol
List of names:

Alice
Bob
Carol

Here's an example of how you can use a list as a stack in Python:


Program:

stack = []

# Pushing elements onto the stack


stack.append(1)

stack.append(2)
stack.append(3)

print("Stack:", stack) # Output: Stack: [1, 2, 3]

# Popping elements from the stack


popped_element = stack.pop()
85
print("Popped Element:", popped_element) # Output: Popped Element: 3
print("Stack:", stack) # Output: Stack: [1, 2]

 In the code above, we start with an empty list called stack. To push elements onto the stack, we use
the append() method, which adds elements to the end of the list. In this example, we push the
elements 1, 2, and 3 onto the stack.

 To pop elements from the stack, we use the pop() method, which removes and returns the last
element from the list (which is the top of the stack). The popped element can be stored in a variable
for further use.

 After popping an element, we print the updated stack to verify the changes. In the end, the stack
contains the elements 1 and 2.

 This demonstrates the basic implementation of a stack using a list in Python. Remember that the
list's append() and pop() methods maintain the last-in, first-out (LIFO) behavior of a stack.

Dictionaries

 Let's go through the operations related to creating, accessing, updating, and deleting elements in a
dictionary, as well as some commonly used functions and methods for dictionaries:

Creating a Dictionary:

o You can create a dictionary by enclosing key-value pairs within curly braces {}.
Here's an example:

my_dict = {'name': 'John', 'age': 25, 'city': 'London'}


Accessing Elements in a Dictionary:

o You can access the value associated with a specific key in a dictionary. Here's an example:

my_dict = {'name': 'John', 'age': 25, 'city': 'London'}


print(my_dict['name']) # Output: 'John'
print(my_dict['age']) # Output: 25

Updating Elements in a Dictionary:

o You can update the value associated with a key in a dictionary. If the key doesn't exist, a new
key-value pair will be added. Here's an example:

my_dict = {'name': 'John', 'age': 25, 'city': 'London'}


my_dict['age'] = 30 # Update the value of 'age' key to 30
my_dict['occupation'] = 'Engineer' # Add a new key-value pair
86
print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'London', 'occupation': 'Engineer'}

Deleting Elements in a Dictionary:

o You can delete elements from a dictionary using the del statement or the pop() method. Here
are examples of both methods:

my_dict = {'name': 'John', 'age': 25, 'city': 'London'}

del my_dict['age'] # Delete the key-value pair with key 'age'


print(my_dict) # Output: {'name': 'John', 'city': 'London'}
my_dict.pop('city') # Delete the key-value pair with key 'city'
print(my_dict) # Output: {'name': 'John'}

Dictionary Functions and Methods:

 len(dictionary): Returns the number of key-value pairs in the dictionary.

 keys(): Returns a list of all keys in the dictionary.

 values(): Returns a list of all values in the dictionary.

 items(): Returns a list of tuples containing key-value pairs.

 clear(): Removes all key-value pairs from the dictionary.

 copy(): Returns a shallow copy of the dictionary.

Here's an example showcasing some of these functions and methods:


pythonCopy code

my_dict = {'name': 'John', 'age': 25, 'city': 'London'}


print(len(my_dict)) # Output: 3
print(my_dict.keys()) # Output: ['name', 'age', 'city']

print(my_dict.values()) # Output: ['John', 25, 'London']

print(my_dict.items()) # Output: [('name', 'John'), ('age', 25), ('city', 'London')]


my_dict.clear() # Remove all key-value pairs from the dictionary
print(my_dict) # Output: {}

 These are some of the common operations and functions/methods related to dictionaries in Python.
They allow you to create, access, update, and delete elements efficiently, as well as perform various
operations on dictionaries.
87
Difference between Lists and Dictionaries.

Aspect Lists Dictionaries

Structure Ordered collection of items Unordered collection of key-value pairs

Accessing
Elements
Accessed by index Accessed by unique key

Example my_list = [1, 2, 3] my_dict = {'name': 'John', 'age': 25, 'city': 'London'}

Mutable Yes Yes

Duplicate Values Allowed Not allowed

Indexing Numeric indexing (0-based) No indexing

Key-Value Pairs Not applicable Contains key-value pairs

Iteration Iterate over elements using loops or functions Iterate over keys, values, or items using loops or functions

Common Use
Cases
Storing an ordered collection of data Mapping data with unique identifiers or labels

Python File Handling:

Introduction to Files:

 When a program is being executed, its data is stored in RAM. Though RAM can be accessed faster
by the CPU, it is also volatile, which means when the program ends, or the computer shuts down,
all the data is lost. If you want to use the data in future, then you need to store this data on a
permanentor non- volatile storage media such as hard disk, USB drive and DVD etc.,

 A file is a collection of data stored on a secondary storage device like hard disk.

 A file is basically used because real-life applications involve large amounts of data and in such
situations the console oriented I/O operations pose two major problems:

 First, it becomes cumbersome and time consuming to handle huge amount of data through terminals.

 Second, when doing I/O using terminal, the entire data is lost when either the program is terminated
or computer is turned off. Therefore, it becomes necessary to store data on a permanent storage
(the disks) and read whenever necessary, without destroying the data.

88
Types of files in Python

 Like C and C++,Python also supports two types of files

 ASCII Text Files

 Binary Files

ASCII Text Files

 A text file is a stream of characters that can be sequentially processed by a computer in forward
direction. For this reason a text file is usually opened for only one kind of operation (reading, writing,
or appending) at any given time.

 Because text files can process characters, they can only read or write data one character at a time. In
Python, a text stream is treated as a special kind of file.

 Depending on the requirements of the operating system and on the operation that has to be performed
(read/write operation) on the file, the newline characters may be converted to or from carriage-
return /linefeed combinations.

 Besides this, other character conversions may also be done to satisfy the storage requirements of the
operating system. However, these conversions occur transparently to process a text file. In a text file,
each line contains zero or more characters and ends with one or more characters.

 Another important thing is that when a text file is used, there are actually two representations of data-
internal or external. For example, an integer value will be represented as a number that occupies 2 or
4 bytes of memory internally but externally the integer value will be represented as a string of
characters representing its decimal or hexadecimal value.

Note: In a text file, each line of data ends with a newline character. Each file ends with a special
character called end-of-file (EOF) Marker.

Binary Files

 A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes. It includes files such as word processing documents, PDFs,
images, spreadsheets, videos, zip files and other executable programs.

 Like a text file, a binary file is a collection of bytes. A binary file is also referred to as a character
stream with following two essential differences.

89
 A binary file does not require any special processing of the data and each byte of data is transferred
to or from the disk unprocessed.

 Python places no constructs on the file, and it may be read from, or written to, in any manner the
programmer wants.

 While text files can be processed sequentially, binary files, on the other hand, can be either
processed sequentially or randomly depending on the needs of the application.

Note: Binary files store data in the internal representation format. Therefore, an integer value will be
stored in binary form as 2 byte value. The same format is used to store data in memory as well as in
files. Like Text files, Binary files also ends with an EOF Marker

File Path:

 Files that we use are stored on a storage medium like the hard disk in such a way that they can be
easily retrieved as and when required.

 Every file is identified by its path that begins from the root node or the root folder. In Windows, C:\
(also known as C drive) is the root folder but you can also have a path that starts from other drives
like D:\, E:\, etc. The file path is also known as pathname.

 In order to access a file on a particular disk we have two paths.

 Absolute Path

 Relative Path

 While an absolute path always contains the root and the complete directory list to specify the exact
location the file.

 Example: To access BCA.docx, The absolute path is C:\Students\Under Graduate\BCA.docx

 Relative path needs to be combined with another path in order to access a file. It starts with
respect to the current working directory and therefore lacks the leading slashes.

 Example: Suppose you are working on current directory Under Graduate in order to access
BTech_CS.docx, The Relative path is

90
File Operations
Opening and Closing files

 When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.

 Python has many in-built functions and methods to manipulate files.These

 Hence, in Python, a file operation takes place in the following order.

1. Open a file

2. Read or write (perform operation)

3. Close the file

Opening A File

 Before reading from or writing to a file, you must first open it using Python‟s built-in open()
function. This function creates a file object, which will be used to invoke methods associated
with it.

 The Syntax of open() is:

fileObj = open(file_name [, access_mode])

 Where file_name is a string value that specifies name of the file that you want to access.
access_mode indicates the mode in which the file has to be opened, i.e., read, write, append,
etc.

 Example: Write a Program to print the details of file object

 Note: Access mode is an optional parameter and the default file access mode is read(r).

Access modes

 Here are some important notes regarding file access modes in Python:

91
1. Default mode: If you don't specify an access mode when opening a file, the default mode is 'r'
(read mode). So, open('filename.txt') is equivalent to open('filename.txt', 'r').

2. File Truncation: When opening a file in write mode ('w') or write and read mode ('w+'), if the
file already exists, its contents will be completely erased and replaced with the new data you
write. Exercise caution to avoid unintended data loss.

3. File Creation: If the file you want to open does not exist, Python will create a new file with
the specified name when using write mode ('w'), append mode ('a'), or append and read mode
('a+').

4. Read and Write Position: When opening a file in read and write mode ('r+'), write and read
mode ('w+'), or append and read mode ('a+'), the initial position for both reading and writing is
at the beginning of the file. If you want to append data without overwriting existing content,
you need to move the file pointer to the end of the file using the seek() method.

5. File Not Found: If you try to open a file that does not exist in read mode ('r'), read and write
mode ('r+'), or append and read mode ('a+'), a FileNotFoundError will be raised. Make sure the
file exists or handle the exception appropriately.

6. Closing Files: After you finish working with a file, it's important to close it using the close()
method or by utilizing the file object as a context manager (with statement). Failing to close
files can result in resource leaks and may prevent other processes from accessing the file.

The File Object Attributes

 Once a file is successfully opened, a file object is returned. Using this file object,
you can easily access different type of information related to that file. This
information can be obtained by reading values of specific attributes of the file.

 The Following table shows list attributes related to file object.

92
Program to open a file and print its attribute values:

def print_file_attributes(filename):
file = open(filename, 'r')

print("File Name:", file.name, end=" ") # Output: File Name: example.txt


print("File Mode:", file.mode, end=" ") # Output: File Mode: r

print("Is Closed:", file.closed, end=" ") # Output: Is Closed: False


print("Encoding:", file.encoding) # Output: Encoding: UTF-8

file.close()

# Example usage

filename = 'example.txt' # Replace with the actual file name


print_file_attributes(filename)

Closing a File

 The close() method is used to close the file object. Once a file object is closed, you cannot further
read from or write into the file associated with the file object.

 While closing the file object the close() flushes any unwritten information. Although, Python
automatically closes a file when the reference object of a file is reassigned to another file, but as
a good programming habit you should always explicitly use the close() method to close a file.

 The syntax of close() is fileObj.close()

 The close() method frees up any system resources such as file descriptors, file locks, etc. that are
associated with the file.

 Once the file is closed using the close() method, any attempt to use the file object will result in an
error.

Example: Write a Python program to assess if a file is closed or not.

def is_file_closed(filename):
93
file = open(filename, 'r')
file_closed = file.closed
file.close()

return file_closed

# Example usage

filename = 'example.txt' # Replace with the actual file name


closed_status = is_file_closed(filename)

if closed_status:

print("The file is closed.")


else:

print("The file is not closed.")

Reading and Writing files

Reading from a File:

 To read from a file, you can use the read() or readline() methods of the file object:

# Opening a file in read mode


file = open('filename.txt', 'r')

# Read the entire contents of the file


content = file.read()

print(content)

# Read one line at a time


line = file.readline()
print(line)

94
# Close the file
file.close()

 In the above example, the file 'filename.txt' is opened in read mode ('r'). The read() method is used
to read the entire contents of the file, while the readline() method is used to read one line at a time.
After reading from the file, it is important to close it using the close() method.

Writing to a File:

 To write to a file, you can use the write() method of the file object:

# Opening a file in write mode


file = open('filename.txt', 'w')
# Write content to the file
file.write("Hello, World!")
file.write("This is a new line.")
# Close the file

file.close()

write() and writelines() methods- append() method


The write() Method:

 The write() method is used to write data to a file. It takes a string as an argument and writes that
string to the file.

# Opening a file in write mode


file = open('filename.txt', 'w')

# Write a single line to the file


file.write("Hello, World!")

# Close the file


file.close()

 In this example, the write() method is used to write the string "Hello, World!" to the file

'filename.txt'.

95
The writelines() Method:

 The writelines() method is used to write a list of strings to a file. Each string in the list will be
written as a separate line in the file.

# Opening a file in write mode


file = open('filename.txt', 'w')

# Write multiple lines to the file

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]


file.writelines(lines)

# Close the file


file.close()

 Certainly! Let's delve into the write(), writelines(), and append() methods for file handling in
Python:

The append() Method:

 The append() method is used to append data to an existing file. It opens the file in append mode
('a') and allows you to add content to the end of the file without overwriting the existing contents.

# Opening a file in append mode


file = open('filename.txt', 'a')

# Append data to the file


file.write("This is additional content.")

96
# Close the file
file.close()

 In this example, the file 'filename.txt' is opened in append mode ('a'). The append() method is
then used to add the string "This is additional content." to the end of the file.

 Remember to close the file after using the write(), writelines(), or append() methods to ensure
proper handling of the file and its contents.

read() and readlines() methods

The read() Method:

 The read() method is used to read the entire contents of a file as a single string. It reads from the
current position of the file pointer until the end of the file.

# Opening a file in read mode


file = open('filename.txt', 'r')

# Read the entire contents of the file


content = file.read()

# Close the file


file.close()

# Print the contents


print(content)

o/p salem tamilnadu

The readlines() Method:

 The readlines() method is used to read a file and return a list of strings, where each string represents
a line in the file. It reads from the current position of the file pointer until the end of the file, splitting
it into lines.

# Opening a file in read mode


97
file = open('filename.txt', 'r')

# Read the file line by line


lines = file.readlines()

# Close the file


file.close()

# Print the lines


for line in lines:
print(line)

with keyword

 Using the with statement is a recommended approach for opening and working with files in Python.
It ensures that the file is properly closed, even if an exception occurs. Here's an example of opening
a file using the with keyword:

# Opening a file using 'with' statement


with open('filename.txt', 'r') as file:

# Perform operations on the file


content = file.read()
print(content)

# Continue with other file operations if needed

# The file is automatically closed outside the 'with' block

 In this example, the file 'filename.txt' is opened in read mode ('r') using the open() function within
a with statement. The file object is assigned to the variable file.

 You can then perform various operations on the file within the with block, such as reading the
contents using the read() method and printing them.

 Once the execution flow exits the with block, the file is automatically closed, even if an exception
occurs within the block. This eliminates the need for explicitly calling the close() method.

98
 Using the with statement ensures proper file handling and prevents resource leaks. It is considered
a best practice when working with files in Python.

Splitting words

 To split a string into individual words, you can use the split() method in Python. The split()
method divides a string into a list of substrings based on a specified delimiter.

# Splitting a string into words

sentence = "I love programming in Python"


words = sentence.split()

# Print the individual words


for word in words:

print(word)

 In this example, the string "I love programming in Python" is split into words using the split()
method without specifying any delimiter. By default, the method splits the string at whitespace
characters and returns a list of individual words.

 The resulting list, words, contains the individual words from the string. The program then iterates
over the list using a loop and prints each word on a separate line.

 When you run this code, the output will be:

love
programming
in

Python

99
File Methods

 Python provides several methods for working with files. Here are some commonly used file
methods:

 open(): Opens a file and returns a file object.

 read(): Reads the entire contents of a file as a string.

 readline(): Reads a single line from the file.

 readlines(): Reads all lines from the file and returns them as a list of strings.

 write(): Writes a string to a file.

 writelines(): Writes a list of strings to a file, with each string representing a line.

 close(): Closes the file and releases system resources.

File Positions

 When reading from or writing to a file, the file object maintains a "file position" that keeps track
of the current location within the file. Some methods can change the file position:

 seek(): Sets the file position to a specified offset.

 tell(): Returns the current file position.

 These methods allow you to control where reading or writing operations occur within the file.

100
Renaming and Deleting Files

 To rename a file in Python, you can use the os.rename() function from the os module. Here's an
example:

import os

# Rename a file

os.rename('old_filename.txt', 'new_filename.txt')

In this example, the file 'old_filename.txt' is renamed to 'new_filename.txt' using the os.rename()
function.

To delete a file, you can use the os.remove() function:

import os

# Delete a file
os.remove('filename.txt')

 In this example, the file 'filename.txt' is deleted using the os.remove() function.

 Note that when renaming or deleting a file, make sure to provide the correct file name or path.
Additionally, exercise caution when performing file operations to avoid unintentional changes or
data loss.

 Remember to import the os module before using its functions for file renaming and deletion.

2 MARK

1. How do you create a list in Python?


A list in Python is created by placing elements inside square brackets [], separated by commas.
Example:
my_list = [1, 2, 3, "apple"]

101
2. How do you access values in a list?
List elements can be accessed by their index using square brackets.
Example:
my_list = [1, 2, 3]
print(my_list[1]) # Output: 2
3. How can you update values in a list?
List elements can be updated by assigning a new value to a specific index.
Example:
my_list = [1, 2, 3]
my_list[1] = 10
4. What is a nested list in Python?
A nested list is a list that contains other lists as elements.
Example:
nested_list = [[1, 2], [3, 4]]
5. What are basic list operations in Python?
Basic list operations include concatenation (+), repetition (*), slicing ([:]), and membership (in).
Example:
my_list = [1, 2] + [3, 4] # [1, 2, 3, 4]
6. Name a few list methods in Python.
Common list methods include append(), extend(), insert(), remove(), and pop().
Example:
my_list = [1, 2]
my_list.append(3) # [1, 2, 3]
7. How do you create a dictionary in Python?
A dictionary is created using curly braces {} with key-value pairs separated by commas. Example:
my_dict = {"name": "John", "age": 25}
8. How do you access elements in a dictionary?
Elements are accessed by their key using square brackets or the get() method.
Example:
print(my_dict["name"]) # Output: John
9. How do you update elements in a dictionary?
Dictionary elements can be updated by assigning a new value to an existing key. Example:
my_dict["age"] = 30

102
10. How do you delete elements in a dictionary?
Elements can be deleted using the del statement or the pop() method. Example:
del my_dict["age"]
11. What are dictionary functions and methods?
Common dictionary methods include keys(), values(), items(), update(), and pop(). Example:
my_dict.update({"city": "New York"})
12. What is the difference between lists and dictionaries?
Lists store elements in a sequence and are accessed by index, while dictionaries store key-value pairs and are
accessed by keys.
13. How can dictionaries be merged in Python?
Dictionaries can be merged using the update() method or the ** unpacking operator in Python 3.9+.
Example:
dict1.update(dict2)
14. What are the types of files in Python?
The two main types of files in Python are text files and binary files.
15. How do you open and close a file in Python?
Files are opened using the open() function and closed using the close() method.
Example:
file = open("file.txt", "r")
file.close()
16. How do you write to a file using write() method?
The write() method is used to write a string to a file.
Example:
file = open("file.txt", "w")
file.write("Hello, World!")
file.close()
17. How is the writelines() method used in Python?
The writelines() method writes a list of strings to a file without adding new lines. Example:
file.writelines(["Hello", "World"])
18. How is the append() method used in file handling?
The append() method ("a" mode) adds content to the end of a file without overwriting existing data.
Example:
file = open("file.txt", "a")
file.write("Appended text")
103
19. How do the read() and readlines() methods work in Python?
The read() method reads the entire file as a string, while readlines() reads the file line by line into a list.
Example:
content = file.read()
lines = file.readlines()
20. What is the use of the with keyword in file handling?
The with keyword is used to open files, ensuring that they are properly closed after the block of code is executed.
Example:
with open("file.txt", "r") as file:
content = file.read()
21. How can you split words in a file using Python?
Words in a file can be split using the split() method after reading the content.
Example:
words = content.split()

||********* END OF UNIT – IV *********||

104
UNIT-V
PYTHON AND MYSQL

1. Introduction to MySQL
Definition:
MySQL is a popular open-source relational database management system (RDBMS) that uses Structured
Query Language (SQL) for managing and interacting with databases.
Key Concepts:
 Relational database: Stores data in tables (rows and columns).
 SQL: Language for querying and managing data in relational databases.

2. Python and SQL Connectivity


Definition:
Python can interact with MySQL databases using libraries like MySQL Connector, PyMySQL, or
SQLAlchemy. The mysql-connector-python library is widely used for connecting Python to MySQL.
Syntax for connecting Python to MySQL:
import mysql.connector
# Establishing connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
# Creating a cursor object to interact with the database
cursor = conn.cursor()
Explanation:
1. The mysql.connector.connect() method is used to establish a connection with the MySQL
database.
2. The cursor object allows us to execute SQL queries.

3. CRUD Operations in Python with MySQL


CRUD stands for Create, Read, Update, and Delete — the four basic operations for managing data in a
database.
105
3.1 Create (INSERT)
Syntax:
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
values = ("John", 25)
cursor.execute(sql, values)
conn.commit() # Save the changes
Explanation:
 INSERT INTO is used to add a new row to the table.
 conn.commit() is required to make the changes permanent in the database.
Sample Program:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root", password="password",
database="mydatabase")
cursor = conn.cursor()
# Insert data
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
values = ("John", 25)
cursor.execute(sql, values)
conn.commit() # Save the changes
# Output
print(f"{cursor.rowcount} record inserted.")
Output:
csharp
1 record inserted.
3.2 Read (SELECT)
Syntax:
sql = "SELECT * FROM users"
cursor.execute(sql)
result = cursor.fetchall()
Explanation:
 SELECT is used to fetch data from the database.
 fetchall() retrieves all records from the result set.

106
Sample Program:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root", password="password",
database="mydatabase")
cursor = conn.cursor()
# Retrieve data
sql = "SELECT * FROM users"
cursor.execute(sql)
result = cursor.fetchall()
# Output
for row in result:
print(row)
Output:
arduino
('John', 25)
3.3 Update
Syntax:
sql = "UPDATE users SET age = %s WHERE name = %s"
values = (30, "John")
cursor.execute(sql, values)
conn.commit()
Explanation:
 UPDATE modifies existing records in the database.
Sample Program:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root", password="password",
database="mydatabase")
cursor = conn.cursor()
# Update data
sql = "UPDATE users SET age = %s WHERE name = %s"
values = (30, "John")
cursor.execute(sql, values)
107
conn.commit()
# Output
print(f"{cursor.rowcount} record(s) updated.")
Output:
1 record(s) updated.
3.4 Delete
Syntax:
sql = "DELETE FROM users WHERE name = %s"
value = ("John",)
cursor.execute(sql, value)
conn.commit()
Explanation:
 DELETE removes specific records from the database.
Sample Program:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(host="localhost", user="root", password="password",
database="mydatabase")
cursor = conn.cursor()
# Delete data
sql = "DELETE FROM users WHERE name = %s"
value = ("John",)
cursor.execute(sql, value)
conn.commit()
# Output
print(f"{cursor.rowcount} record(s) deleted.")
Output:
1 record(s) deleted.
4. Working with Complex Queries
Complex queries involve using JOIN, GROUP BY, HAVING, and subqueries. These queries are used
to analyze and process data across multiple tables.
Syntax for JOIN:
sql = """
SELECT orders.order_id, customers.name
108
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
"""
cursor.execute(sql)
result = cursor.fetchall()
Explanation:
 INNER JOIN combines records from two tables based on a related column.
5. Data Handling and Analysis
Data analysis involves using SQL queries to retrieve and summarize data. Python’s pandas library can
be integrated for further analysis.
Example:
import pandas as pd
import mysql.connector
# Fetching data
sql = "SELECT * FROM users"
cursor.execute(sql)
result = cursor.fetchall()
# Convert to DataFrame for analysis
df = pd.DataFrame(result, columns=['Name', 'Age'])
print(df.describe())
Explanation:
 The pandas library allows for more advanced data analysis on the retrieved data.

6. Project Development
In a real-world project, Python and MySQL can be integrated into web applications, data pipelines, or
standalone desktop applications. Flask and Django are popular Python frameworks for developing web
applications with MySQL backends.
Sample Flow for a Python-MySQL Project:
1. Connect Python to MySQL using mysql.connector.
2. Perform CRUD operations based on user input or application logic.
3. Process and analyze data using pandas or similar libraries.
4. Display data on a web interface (Flask/Django) or save it for reports.

109
Sample End-to-End Program for Python and MySQL Integration
import mysql.connector
# Step 1: Connect to MySQL database
conn = mysql.connector.connect(host="localhost", user="root", password="password",
database="mydatabase")
cursor = conn.cursor()
# Step 2: Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),age INT)""")
# Step 3: Insert a record
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
values = ("Alice", 28)
cursor.execute(sql, values)
conn.commit()
# Step 4: Read and display the inserted data
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
for row in result:
print(row)
# Step 5: Update the record
cursor.execute("UPDATE users SET age = 29 WHERE name = 'Alice'")
conn.commit()
# Step 6: Delete the record
cursor.execute("DELETE FROM users WHERE name = 'Alice'")
conn.commit()
# Step 7: Close the connection
conn.close()
Explanation:
This program demonstrates creating a table, performing CRUD operations, and managing the database
using Python and MySQL connectivity.

110
2 MARKS
1. What is MySQL?
MySQL is an open-source relational database management system (RDBMS) that uses Structured Query
Language (SQL) for managing and manipulating databases. It is widely used for web applications and data
storage.
2. How can Python connect to a MySQL database?
Python can connect to a MySQL database using libraries such as mysql-connector-python or PyMySQL.
The connection is established using the connect() method by providing the host, user, password, and
database name.
3. What are CRUD operations in the context of databases?
CRUD operations refer to the four basic functions of persistent storage: Create (insert data), Read (retrieve
data), Update (modify existing data), and Delete (remove data) in a database.
4. How do you insert data into a MySQL table using Python?
Data is inserted using the INSERT INTO SQL statement along with the execute() method of a cursor
object.
For example:
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
cursor.execute(sql, ("John", 25))
5. How do you retrieve data from a MySQL table in Python?
Data is retrieved using the SELECT SQL statement followed by the execute() and fetchall() methods.
For example:
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
6. What is the syntax for updating a record in a MySQL table using Python?
Records are updated using the UPDATE SQL statement, like this:
sql = "UPDATE users SET age = %s WHERE name = %s"
cursor.execute(sql, (30, "John"))
7. How do you delete a record from a MySQL table in Python?
A record is deleted using the DELETE FROM SQL statement, for example:
cursor.execute("DELETE FROM users WHERE name = %s", ("John",))
8. What is the purpose of complex queries in SQL?
Complex queries are used to retrieve data from multiple tables using joins, group data for aggregation, and
perform advanced filtering. They enhance data analysis capabilities in databases.

111
9. How can Python be used for data analysis with MySQL?
Python can fetch data from MySQL using SQL queries and analyze it using libraries like pandas. Data can
be converted into a DataFrame for further manipulation and visualization.
10. What is the role of Python and MySQL in project development?
In project development, Python serves as the programming language for backend logic, while MySQL acts
as the database for storing and managing application data, enabling efficient data retrieval and manipulation.

||********* END OF UNIT – V *********||


All the best….!

112

You might also like