Python_Programming NOTES _I_CS_FINAL AUTONOMOUS
Python_Programming NOTES _I_CS_FINAL AUTONOMOUS
(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+
24S1UCS01
Python Programming
1
SENGUNTHAR ARTS AND SCIENCE COLLEGE, TIRUCHENGODE
AUTONOMOUS
(Affiliated to Periyar University, Salem)
DEPARTMENT OF COMPUTER SCIENCE
UNIT - I
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.
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.
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.
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.
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
Literal Constants
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
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
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
In this case, the boolean literal False is assigned to the variable is_greater since the condition x
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:
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:
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:
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
\\ - Backslash
Example 1 :
print(new_line)
Output 1:
This is a string
with a new line.
8
Example 2:
name = 'kumar'
Output 2:
Hello, World!
My name is kumar
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
9
characters and are essential for multilingual applications.
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
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:
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:
path = r'C:\Users\username\Documents\file.txt'
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:
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.
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.
They can consist of letters (a-z, A-Z), digits (0-9), and underscores (_).
They are case-sensitive (e.g., count and Count are different identifiers).
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)
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.
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:
2. Sequence Types:
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 ({}).
5. Boolean Type:
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]
# Mapping Type
# Set Types
my_set = {1, 2, 3, 4, 5}
# Boolean Type
is_true = True
is_false = False
# None Type
no_value = None
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'>
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
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:
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:
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:
Anything after the # symbol on a line is considered a comment and is not executed by the interpreter.
"""
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("x is non-positive")
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
1. Arithmetic Operators:
3. Unary Operators:
4. Bitwise Operators:
19
Bitwise AND (&) : 5 & 3 returns 1.
5. Shift Operators:
6. Logical Operators:
Negated identity test (is not): x is not y checks if x and y refer to different objects.
8. Assignment Operators:
20
Floor divide and assign (//=): x //= 2 is equivalent to x = x // 2.
9. Special Operators:
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).
1. Parentheses: ( )
Parentheses are used to group expressions and override the default precedence.
2. Exponentiation: **
Bitwise shift operators shift the bits of a number to the left or right.
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: |
9. Comparison Operators: ==, !=, <, >, <=, >=, in, not in, is, is not
Sample Program:
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.
Numeric Expression:
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:
# Integer to Float
x = float(5)
# Float to Integer
y = int(3.14)
# Integer to String
z = str(10)
# String to Integer
a = int("20")
# Boolean to Integer
b = int(True)
# Float to String
c = str(3.14)
# String to Float
d = float("2.5")
# Boolean to String
e = str(True)
# String to Boolean
f = bool("True")
24
print("String to Boolean:", f) # Output: True
# List to Tuple
g = tuple([1, 2, 3])
# Tuple to List
h = list((4, 5, 6))
# List to Set
i = set([1, 2, 2, 3])
# Set to List
j = list({4, 5, 6})
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.
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.
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.
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:
2. Creating an array:
To create an array, you need to specify the type of elements it will hold. The most common types are:
26
'l': signed integer of size 4 bytes
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:
You can modify array elements by assigning new values to specific indices. Here's an example:
numbers[1] = 10
5. Array methods:
Arrays in Python provide several useful methods for manipulation. Here are some commonly used methods:
27
insert(i, x): Inserts element x at index i.
numbers = array('i', [1, 2, 3, 4, 5])
numbers.insert(2, 10)
x = numbers.pop(2)
print(x) # Output: 3
idx = numbers.index(3)
print(idx) # Output: 2
count = numbers.count(3)
print(count) # Output: 2
28
extend(iterable): Appends elements from the iterable to the end of the array.
numbers.extend([4, 5, 6])
Array Operations
Various operations can be performed on arrays, such as arithmetic operations, slicing, and concatenation.
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:
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.
32
UNIT – II
Control 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:
Example:
x = 10
if x > 0:
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:
else:
Example:
x=5
if x > 0:
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:
if condition2:
Example:
x = 10
y=5
if x > 0:
if y > 0:
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.
if day == Monday":
print("It's Monday")
elif day == "Tuesday":
print("It's Tuesday")
elif day == "Wednesday":
print("It's Wednesday")
else:
enter day
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
Example:
count = 0
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:
# 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:
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:
print(fruit)
Output 1:
apple
banana
cherry
Example 2 :
sum_of_numbers += i
Output 2:
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).
print(count)
count += 1
else:
print("Loop completed")
Output:
Loop completed
Example with a for loop:
else:
Output:
apple
banana
cherry
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.
41
Jump 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:
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:
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:
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.
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.
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:
Output:
Enter a number: 7
7 is odd
Program 2:
45
# Calculate the factorial using a for loop
for i in range(1, number + 1):
factorial *= i
Output:
Enter a number: 5
f=1
n=int(input(“enter value”))
i=1
while(i<=n):
f=f*i
i=i+1
Output:
enter value 5
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.
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.")
# 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)
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.
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.
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:
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.
Function Definition
A function, f that uses another function g, is known as the calling function and g is known as
the called function.
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
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.
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).
Example:
def greet(name):
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:
Example 2:
Note: Names of variables in function call and header of function definition may vary.
57
Example 3:
Example 3:
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.
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():
def modify_local():
# Local variable
59
local_var = 5
local_var += 2
# Main program
print("")
modify_local()
# Attempt to access the local variable outside the function will raise an error
print("Local variable (outside function):", local_var)
Output:
Inside modify_local(): 7
Traceback (most recent call last):
60
Explanation:
Python program that demonstrates the differences between global and local variables:
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.
They are defined in the main body of They are defined within a function and
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
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.
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.
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.
The following Program to write another function which returns an integer to the caller.
63
Function Arguments:
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).
64
Example:
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 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:
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.
Output:
Hello,World!
print(my_string[i])
i += 1
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"
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
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
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.
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.
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.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:
str.find(substring): Searches for the first occurrence of the substring in the string and returns
its index. Returns -1 if not found.
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"
2. Inequality (!=): The inequality operator (!=) checks if two strings are not equal and returns
str1 = "Hello"
str2 = "Hello"
str3 = "World"
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"
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.
1. Importing an Entire Module: You can import the entire module by using the import keyword
followed by the module name.
Example:
import math
In this example, the math module is imported, and the sqrt() function from the math
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:
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.
random: Allows you to generate random numbers and make random selections.
os: Provides operating system-related functionalities, such as file and directory manipulation.
json: Allows for JSON (JavaScript Object Notation) encoding and decoding.
pandas: Offers data manipulation and analysis tools, particularly for structured data.
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.
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
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
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.
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.
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):
return x ** 2
PI = 3.14159
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.
import my_module
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:
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
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.
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
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
You can have lists within lists, which are called nested lists. This allows you to create a
print(nested_list[0][1]) # Output: 2
Basic List Operations: There are several basic operations you can perform on lists:
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:
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.
def get_names():
names = []
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:
Alice
Bob
Carol
stack = []
stack.append(2)
stack.append(3)
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:
o You can access the value associated with a specific key in a dictionary. Here's an example:
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:
o You can delete elements from a dictionary using the del statement or the pop() method. Here
are examples of both methods:
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.
Accessing
Elements
Accessed by index Accessed by unique key
Example my_list = [1, 2, 3] my_dict = {'name': 'John', 'age': 25, 'city': 'London'}
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
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
Binary 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.
Absolute Path
Relative Path
While an absolute path always contains the root and the complete directory list to specify the exact
location the file.
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.
1. Open a 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.
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.
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.
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.
92
Program to open a file and print its attribute values:
def print_file_attributes(filename):
file = open(filename, 'r')
file.close()
# Example usage
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 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.
def is_file_closed(filename):
93
file = open(filename, 'r')
file_closed = file.closed
file.close()
return file_closed
# Example usage
if closed_status:
To read from a file, you can use the read() or readline() methods of the file object:
print(content)
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:
file.close()
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.
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.
Certainly! Let's delve into the write(), writelines(), and append() methods for file handling in
Python:
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.
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.
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.
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.
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:
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.
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.
love
programming
in
Python
99
File Methods
Python provides several methods for working with files. Here are some commonly used file
methods:
readlines(): Reads all lines from the file and returns them as a list of strings.
writelines(): Writes a list of strings to a file, with each string representing a line.
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:
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.
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
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()
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.
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.
112