Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python essential 1 report

The document is a summer internship report by Ganesh Sai Santosh Chivukula, submitted for a Bachelor of Technology in Computer Science and Engineering at GITAM University. It details his three-month internship focused on mastering Python essentials for web application development, including frameworks like Flask and Django, and skills in web scraping and database integration. The report also outlines the structure of the internship, the learning modules covered, and the significance of programming and Python as a language.

Uploaded by

gchivuku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python essential 1 report

The document is a summer internship report by Ganesh Sai Santosh Chivukula, submitted for a Bachelor of Technology in Computer Science and Engineering at GITAM University. It details his three-month internship focused on mastering Python essentials for web application development, including frameworks like Flask and Django, and skills in web scraping and database integration. The report also outlines the structure of the internship, the learning modules covered, and the significance of programming and Python as a language.

Uploaded by

gchivuku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

PYTHON ESSENTIALS

A summer internship report submitted in partial fulfilment of the


requirements for the award of degree of

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING

Submitted by

Ganesh Sai Santosh HU22CSEN0101777


Chivukula
Under the guidance of

Dr. Yaswanth
Gavini
Associate
Professor

Department of Computer Science and Engineering


GITAM School of Technology
GITAM Deemed to be University
Hyderabad Campus -502329
March -2025
GANDHI INSTITUTE OF TECHNOLOGY AND MANAGEMENT
(GITAM)
(Declared as Deemed-to-be-University u/s 3 of UGC Act 1956)
HYDERABAD CAMPUS

DECLARATION
I hereby declare that the summer internship report entitled “PYTHON ESSENTISLS” is an
original work done in the Department of Computer Science and Engineering, GITAM School of
Technology, GITAM (Deemed to be University) submitted in partial fulfilment of the
requirements for the award of the degree of “Bachelor of Technology” in Computer Science and
Engineering. The work had not been submitted to any other college or university for the award
of any degree or diploma.

Place-HYDERABD

Date-06-03-2025
Ganesh Sai Santosh
Chivukula
(HU22CSEN0101777)

2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GITAM SCHOOL OF TECHNOLOGY

GITAM
(DEEMED TO BE UNIVERSITY)
HYDERABAD CAMPUS

CERTIFICATE

This is to certify that the Internship report entitled “PYTHON ESSENTIALS” is a Bonafide record of
work carried out by Ganesh Sai Santosh Chivukula (HU22SCEN0101777) submitted in partial
fulfillment of the requirement for the award of the degree of Bachelors of Technology in Computer
Science and Engineering.

Dr. Yaswanth Gavini


Associate Professor

3
CERTIFICATE OF COMPLETION

4
ABSTRACT
This report presents a comprehensive reflection on my three-month
internship , where I focused on mastering Python essentials for web application
development. During the internship, I worked extensively with key Python
frameworks, such as Flask and Django, learning how to integrate them with
databases like SQLite and MySQL to develop dynamic, data-driven
applications. Additionally, I gained hands-on experience in web scraping using
libraries like BeautifulSoup and Scrapy, enabling efficient extraction of
valuable data from websites.My responsibilities included developing, testing,
and optimizing Python code, integrating APIs, and collaborating with senior
developers on real-world projects. The internship presented challenges that
enhanced my ability to solve programming problems, debug errors, and write
clean, efficient code. Furthermore, it reinforced the significance of unit testing,
version control (Git), and teamwork in a professional development
environment.This internship was a transformative learning experience,
allowing me to apply theoretical concepts to real-world projects while adapting
to a professional work culture. I acquired invaluable insights into software
development best practices, time management, and collaboration. Ultimately,
this experience has strengthened my Python web development skills, preparing
me for future roles in the field while enhancing my problem-solving and
communication abilities.

5
Table of Contents
1. Introduction to Python and Computer Programming

o What is Programming?

o Overview of Python as a programming language

o Setting up the Python runtime environment

o First Python program: "Hello, World!"

o Understanding the role of interpreters in programming

2. Module 2: Data Types, Variables, Basic Input/Output, and Operators

o Basic Data Types: Integers, Floats, Strings, and Booleans

o Variables and Memory Allocation

o Input and Output operations in Python

o Basic Arithmetic Operators and Expressions

o String Manipulation

o Type Casting and Conversion

o Introduction to Input/Output functions (e.g., input(), print())

3. Module 3: Boolean Values, Conditional Execution, Loops, Lists and


List Processing

o Boolean Logic: True and False values

o Conditional Statements: if, elif, else

o Comparison and Logical Operators

6
o Introduction to Loops: for and while loops

o List data structure: Creating, accessing, and manipulating lists

o List Processing: List comprehensions, filtering, and sorting

o Bitwise operators in Python

4. Module 4: Functions, Tuples, Dictionaries, Exceptions, and Data Processing

o Functions in Python: Defining and calling functions

o Tuples: Immutable sequences

o Dictionaries: Key-value pairs and dictionary operations

o Handling Exceptions: try, except, finally

o Data Processing with Python: Reading and writing files, using


libraries (e.g., csv, json)

7
CHAPTER 1

Module 1: Introduction to Python and Computer Programming


This module introduces the concepts of computer programming and the Python programming language. The
topics include:

 What is Programming?: An overview of the role of programming in solving real-world problems and creating
applications.
 Overview of Python: Why Python is popular—simple syntax, powerful libraries, and its role in web development,
data analysis, and automation.
 Setting up Python Environment: Installation of Python on different operating systems, IDEs (like
PyCharm, VSCode), and setting up virtual environments.
 Your First Python Program: Writing a basic "Hello, World!" program to understand how Python works.
 Role of the Interpreter: The Python interpreter's function in translating code into executable instructions and how
it helps debug code.

Module 2: Data Types, Variables, Basic Input/Output, and Operators


In this module, you'll focus on data types and basic operations in Python. Key points covered include:

 Data Types: Explore Python's built-in types like integers, floating-point numbers, strings, and booleans.
 Variables: Learn how Python manages data with variables and how to assign values to them.
 Basic I/O: Learn how to accept input from the user and display output using input() and print().
 Operators: Understand Python's arithmetic operators, comparison operators, and logical operators for
manipulating data.

Module 3: Boolean Values, Conditional Execution, Loops, Lists and List Processing
This module delves into control flow and data structures like lists. Key topics include:

 Boolean Values: Understand the concept of truth values (True and False) and their importance in
decision- making.
 Conditional Execution: Learn how to use if-else statements for decision-making and apply logic to control the flow
of a program.
 Loops: Master loops, including for and while loops, for repeating tasks.
 Lists: Lists are Python's ordered, mutable collections. Learn how to create, modify, and access list elements.
 List Processing: Discover list comprehensions, a Pythonic way to process lists. Explore methods like
filtering, mapping, and sorting.

Module 4: Functions, Tuples, Dictionaries, Exceptions, and Data Processing


This module teaches more advanced concepts and tools for Python programming:

 Functions: Functions allow you to bundle code into reusable blocks. Learn how to define and call functions,
pass arguments, and return results.
 Tuples: Tuples are immutable sequences in Python. Explore how they differ from lists and their use cases.
 Dictionaries: Learn how to work with key-value pairs in dictionaries and perform operations like adding, updating,
and deleting elements.
 Exceptions: Learn about Python's exception-handling mechanism with try, except, and finally to manage
errors.
 Data Processing: Learn basic techniques for reading and writing data files, such as CSV and JSON.
Understand libraries and techniques used for data extraction and processing.

What Makes a Programming Language: The Interpreter


A programming language is defined not only by its syntax and structure but also by its interpreter. The
interpreter is a crucial component in the development process, and Python, being an interpreted language,
offers several advantages.
Interpreter: Role and Challenges

 The interpreter translates high-level Python code into machine-readable instructions and executes the program.
This happens line by line, which allows for rapid development and testing.
 Error Reporting: When a program has an issue, the interpreter attempts to pinpoint the problem's location.
However, the error messages it provides might not always point directly to the root cause. Errors are detected when
the interpreter reaches a point where it cannot understand or execute the code as intended.
 Misleading Error Messages: Sometimes the interpreter identifies the location of an error, but this might be
misleading because Python does not always trace the issue to the correct line or statement. This is especially
true when the error occurs within a complex expression, or when the cause of the issue is earlier in the code.

Examples of Interpreter Behavior:

 Syntax Errors: These occur when the syntax does not follow the rules of Python. The interpreter will stop
execution and report the error location.
 Runtime Errors: These happen when the program is executed but encounters an issue (e.g., division by zero, file not
found). The interpreter will attempt to handle this via error messages and traceback

Module 1: Introduction to Python and Computer Programming


1.1 What is Programming?
Programming is the process of designing and creating software by writing code in a programming language. In this
section, we will understand:

 Definition: Programming is a way to communicate with computers and tell them what tasks to perform.
It involves using a set of instructions to control the behavior of a machine.
 Importance of Programming:
o Problem Solving: Programming allows us to solve complex problems by breaking them down into
smaller, manageable parts. It’s a structured way to automate processes, perform calculations, and manage
data.
o Automation: Many routine tasks (e.g., data entry, file management) can be automated using code, making
systems more efficient and error-free.
o Technological Development: Almost every modern application, from smartphones to web services, relies on
programming for development. Programming skills empower individuals to create solutions and contribute
to technological innovations.
 Programming Languages: There are many programming languages (like Python, Java, C++, etc.), and
each has its syntax and strengths. Python, for example, is favored for its simplicity and readability,
making it ideal for beginners and professionals alike.
 Application of Programming: Programming is used in various fields:
o Web Development: Building websites and web applications.
o Data Science: Analyzing and processing data for insights.
o Automation: Writing scripts for repetitive tasks.
o Game Development: Creating games and interactive entertainment.
o Artificial Intelligence: Developing algorithms that allow machines to learn and make decisions.

1.2 Overview of Python as a Programming Language


In this section, we explore why Python has become one of the most popular programming languages for various
applications.

 History and Evolution:


o Python was developed by Guido van Rossum and first released in 1991. It was designed with an emphasis on
code readability and simplicity, making it accessible to both beginners and experienced developers.
o Python’s syntax is simple and intuitive, resembling natural language. This allows developers to write
less code to achieve the same functionality as in other languages like C++ or Java.
 Key Features of Python:
o Readability: Python uses indentation rather than brackets to define code blocks, which improves
the readability and maintainability of the code.
o Versatility: Python can be used for a wide variety of applications—from web development to machine
learning, data science, artificial intelligence, automation, and more.
o Large Standard Library: Python comes with a huge standard library that offers built-in tools for various
tasks like working with files, databases, and even web scraping.
o Cross-Platform: Python can run on various operating systems (Windows, macOS, Linux)
without modification to the code.
o Community Support: Python has a vibrant and active community. As a result, it has extensive
documentation, online tutorials, and a wealth of third-party libraries.
 Why Python for Beginners?
o Python’s simple and easy-to-learn syntax makes it the preferred choice for beginners. There is no need
to worry about complex syntax or memory management, as Python handles those behind the scenes.
o Python’s syntax closely resembles pseudocode, making it great for understanding fundamental
programming concepts without getting bogged down by technicalities.

1.3 Setting up Python Environment


Before we start coding, it's crucial to set up the necessary tools and environment for running Python programs. This
section covers the following:

 Installing Python:
o Visit the official Python website at python.org and download the latest version for your operating system.
o Follow the installation instructions for Windows, macOS, or Linux. On Windows, ensure that the option
to "Add Python to PATH" is checked during installation.
 Setting up an Integrated Development Environment (IDE):
o An IDE helps you write, debug, and run Python code efficiently. Some popular Python IDEs include:
 PyCharm: A powerful, feature-rich IDE for Python.
 VSCode: A lightweight and customizable code editor with Python support through extensions.
 Jupyter Notebooks: A popular choice for data science and interactive coding.
o Text Editors: For those who prefer lighter editors, you can use Sublime Text or Atom, which support
Python with the help of plugins.
 Creating a Python Virtual Environment:
o A virtual environment isolates your project’s dependencies from other Python projects. This ensures
that different projects with different package requirements don’t interfere with each other.
o Create a virtual environment with:

bash
Copy
python -m venv myenv

o Activate the virtual environment:


 On Windows: myenv\Scripts\activate
 On macOS/Linux: source myenv/bin/activate
o You can now install any packages required for your project without affecting your system-wide Python
installation.

1.4 Your First Python Program: "Hello, World!"


Writing your first program is an exciting step! In this section, we will write a simple Python program to display
"Hello, World!" on the screen.

 Understanding the Syntax:


o Python is straightforward in terms of syntax, which makes writing your first program an easy and
rewarding experience.

python
Copy
print("Hello, World!")

o What happens here?


 The print() function is a built-in function in Python that outputs the string inside the parentheses
to the console.
 "Hello, World!" is a string—a sequence of characters enclosed in quotation marks.
 Why "Hello, World!"?
o The "Hello, World!" program is the simplest example used by programmers worldwide when they begin
learning a new language. It demonstrates how to display output to the user and serves as a starting point
for understanding how to structure code in Python.

1.5 Role of the Interpreter in Python


In this section, we will discuss interpreters and how they play a key role in running Python code.

 What is an Interpreter?:
o An interpreter is a program that executes Python code by translating it line-by-line into machine code
that the computer can understand. Unlike compilers, which translate the entire program at once,
interpreters translate and execute the code at runtime.
o Python is an interpreted language, meaning the code is executed directly by the Python interpreter
rather than being compiled into machine code first.
 The Python Interpreter:
o The Python interpreter is invoked when you run a Python program. It reads your code, processes it, and
gives feedback in the form of results or error messages.
 Error Handling in the Interpreter:
o The interpreter helps identify errors and exceptions in the code. However, sometimes error messages may
not directly point to the exact location of the error. This is because the interpreter processes code line-by-line
and might find an issue later, but the actual mistake could be several lines above.
 Common Python Errors:
o Syntax Errors: Occur when Python doesn’t understand the structure of the code (e.g., missing parentheses).
o Runtime Errors: Happen when the code is executed but encounters an issue (e.g., dividing by zero).
o Logic Errors: These are harder to spot and occur when the program runs but doesn’t perform the
desired task.

Chapter-2
Module 2: Data Types, Variables, Basic Input/Output, and Operators
2.1 Data Types in Python
Understanding data types is one of the most fundamental aspects of programming. In Python, every value has a
specific type, and knowing how to work with these types is essential for performing operations on data.

 Definition of Data Types: Data types define the kind of data a variable can hold and the operations that
can be performed on that data. Python supports several built-in data types, which are classified into
primitive types and composite types.
 Primitive Data Types:
o Integers (int): Whole numbers, positive or negative, without decimals.
 Example: x = 10
o Floating-Point Numbers (float): Numbers that contain a decimal point.
 Example: y = 3.14
o Strings (str): A sequence of characters enclosed in either single or double quotes.
 Example: name = "Python"
o Booleans (bool): Represents two values: True or False.
 Example: is_valid = True
 Composite Data Types:
o Lists: Ordered, mutable collections of items that can store multiple data types.
 Example: my_list = [1, 2, 3, "apple", True]
o Tuples: Ordered, immutable collections of items.
 Example: coordinates = (10.0, 20.5)
o Dictionaries: Unordered collections of key-value pairs, where each key is unique.
 Example: person = {"name": "John", "age": 30, "is_student": False}
 Type Checking and Conversion:
o You can check the data type of a variable using the built-in type() function:

python
Copy
x = 10
print(type(x)) # Output: <class 'int'>

o Type casting (also known as type conversion) is the process of converting one data type to another, using
functions like int(), float(), str(), etc.

python
Copy
x = "10"
y = int(x) # Converts string to integer
2.2 Variables and Memory Allocation
In Python, variables are symbolic names associated with values. They act as containers for storing data that can be
referenced and manipulated throughout a program.

 Variable Assignment:
o In Python, you assign a value to a variable using the assignment operator (=).

python
Copy
x = 5 # Assigns the value 5 to the variable x
name = "Alice" # Assigns the string "Alice" to the variable name

 Naming Variables:
o Variable names in Python must begin with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits,
or underscores.
o Example of valid names: my_variable, x1, _counter
o Python Naming Rules:
 Variables are case-sensitive (Age and age are different variables).
 Avoid using Python keywords (e.g., if, else, True, None) as variable names.
 Memory Allocation:
o Python automatically handles memory allocation and deallocation using a mechanism called automatic
garbage collection. This makes Python less memory-intensive compared to languages that require manual
memory management (like C).
 Reassigning Variables:
o Python allows you to reassign values to variables during runtime. If you assign a new value to an
existing variable, the old value is overwritten.

python
Copy
x = 10 # x initially holds the value 10
x = 20 # Now x holds the value 20, and the value 10 is discarded

2.3 Basic Input and Output in Python


Input and output are essential for interacting with users or other systems. Python provides simple functions for
handling input and output operations.

 Output with print():


o The print() function is used to display output on the screen. You can print variables, strings, numbers,
or even complex expressions.

python
Copy
print("Hello, World!") # Prints a string to the console
name = "Alice"
print("Hello, " + name) # Concatenates and prints "Hello, Alice"

 Input with input():


o The input() function allows you to take input from the user. The value is returned as a string, which can
be converted to other types (e.g., integer or float) as needed.

python
Copy
age = input("Enter your age: ") # The value is stored as a string
age = int(age) # Converts the string to an integer

 Formatted Output:
o You can also format output strings using f-strings or the format() method:

python
Copy
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # Using f-string
Or using format():
python
Copy
print("My name is {} and I am {} years old.".format(name, age))

2.4 Basic Operators in Python


Python provides various operators to perform arithmetic, comparison, and logical operations. These operators are
essential for manipulating data and making decisions within a program.

 Arithmetic Operators:
o Used for performing mathematical operations on numbers (integers or floats).

python
Copy
x = 10
y = 5
print(x + y) # Addition: 15
print(x - y) # Subtraction: 5
print(x * y) # Multiplication: 50
print(x / y) # Division: 2.0 (always returns a float)
print(x // y) # Floor Division: 2 (integer result)
print(x % y) # Modulus (remainder): 0
print(x ** y) # Exponentiation: 100000

 Comparison Operators:
o Used for comparing two values and returning a boolean result (True or False).

python
Copy
x = 10
y = 5
print(x > y) # Greater than: True
print(x == y) # Equal to: False
print(x != y) # Not equal to: True
print(x <= y) # Less than or equal to: False
print(x >= y) # Greater than or equal to: True

 Logical Operators:
o Used for combining conditional statements. Logical operators include and, or, and not.

python
Copy
x = 10
y = 5
print(x > 5 and y < 10) # True
print(x > 5 or y > 10) # True
print(not(x > 5)) # False

 Assignment Operators:
o Used to assign values to variables. Python supports shorthand assignment operators.

python
Copy
x = 10
x += 5 # x = x + 5
print(x) # Output: 15
x *= 2 # x = x * 2
print(x) # Output: 30

 Identity and Membership Operators:


o Identity Operators: is and is not are used to compare memory locations of objects.

python
Copy
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False: Different memory locations
print(a == b) # True: Equal values

o Membership Operators: in and not in check if a value exists in a sequence (list, tuple, etc.).

python
Copy
a = [1, 2, 3]
print(2 in a) # True
print(4 not in a) # True

2.5 Summary of Module 2


Module 2 covered the essential concepts related to data types, variables, input/output, and operators. Here are
the key points:

 Data Types: Python has several built-in data types like integers, floats, strings, and booleans, as well as
composite types like lists, tuples, and dictionaries.
 Variables: Variables are used to store data, and Python handles memory management automatically.
 Basic Input and Output: The input() function is used to take user input, and the print() function
displays output. We also learned how to format strings and display dynamic content.
 Operators: Python supports a wide range of operators—arithmetic, comparison, logical, assignment,
and membership/identity operators.

Chapter-3

Module 3: Boolean Values, Conditional Execution, Loops, Lists, and List


Processing

3.1 Boolean Values

Boolean values are fundamental to programming and decision-making. Python has


a built-in bool data type that represents one of two possible values: True or False.
Boolean values are used in conditional statements, loops, and logical operations.

 Definition of Boolean Values:

o A Boolean represents a binary state: either True or False. These values


are often the result of comparisons or logical operations.

python

Copy

x=5

y = 10

print(x == y) # False: 5 is not equal to 10

 Common Uses:

o Conditionals: In if statements, Booleans determine which block of code


to execute.

o Loops: Boolean values are used to control the flow of loops.

o Logical Operations: Combine multiple conditions using logical


operators like and, or, and not.

 Comparison to Other Data Types:

o Python uses False to represent values that are considered "falsy" in


conditional statements (e.g., 0, None, empty strings, empty lists), while
anything non-zero or non-empty is considered True.

python

Copy

x=0

if x:

print("This is True.")

else:

print("This is False.") # Output: "This is False."


3.2 Conditional Execution

Conditional execution refers to making decisions in the program based on certain


conditions. Python provides several ways to perform these decisions, such as if,
elif, and else.

 If Statements:

o An if statement evaluates a condition, and if the condition is True, the


code block inside the if statement is executed.

python

Copy

age =

18

if age >= 18:

print("You are an adult.") # Output: You are an adult.

 Elif (Else If) Statement:

o If the initial if condition is False, Python checks the condition of the elif
statement.

o If an elif condition is True, its corresponding block of code is executed.

python

Copy

age =

15

if age >= 18:

print("You are an adult.")

elif age >= 13:

print("You are a teenager.") # Output: You are a teenager.


 Else Statement:

o The else block is executed when all preceding if and elif conditions are
False.

python

Copy

age =

10

if age >= 18:

print("You are an adult.")

elif age >= 13:

print("You are a teenager.")

else:

print("You are a child.") # Output: You are a child.

 Nested Conditional Statements:

o You can nest if statements inside each other to evaluate multiple


conditions in a hierarchy.

python

Copy

age =

25

if age >= 18:

if age < 21:

print("You are an adult, but not yet 21.") # Output: You are an adult, but not
yet 21.

else:

print("You are 21 or older.")


3.3 Loops in Python

Loops allow repetitive execution of a block of code. Python provides two main
types of loops: for loops and while loops.

 For Loop:

o The for loop is used to iterate over a sequence (like a list, tuple, string, or
range) and execute a block of code for each element.

python

Copy

for i in range(5): # Iterates over the range 0 to 4

print(i) # Output: 0 1 2 3 4

o Range Function: The range() function generates a sequence of numbers,


and is commonly used with for loops.

 range(start, stop, step): Generates a sequence starting at start,


ending at stop, with an optional step between numbers.

python

Copy

for i in range(2, 10, 2): # Output: 2 4 6 8

print(i)

 While Loop:

o The while loop repeats a block of code as long as a given condition


evaluates to True.

python

Copy

count = 0

while count < 5:

print(count) # Output: 0 1 2 3 4

count += 1

o Be careful to avoid infinite loops, which occur when the loop condition
never becomes False.

 Break and Continue:

o Break: Exits the loop prematurely.

o Continue: Skips the current iteration and moves to the next one.

python

Copy

for i in range(5):

if i == 3:

break # Exit the loop when i is 3

print(i) # Output: 0 1 2

for i in range(5):

if i == 3:

continue # Skip the iteration when i is 3

print(i) # Output: 0 1 2 4

3.4 Lists in Python

Lists are one of the most common and flexible data structures in Python. They are
ordered, mutable, and can store multiple data types.

 Defining Lists:

o Lists are created by enclosing items in square brackets [], separated by


commas.

python

Copy

my_list = [1, 2, 3, 4, 5]
 Accessing List Elements:

o You can access elements of a list using indexing (starting from index 0)
or slicing.

python

Copy

first_item = my_list[0] # Access the first item (1)

last_item = my_list[-1] # Access the last item (5)

sublist = my_list[1:4] # Access a sublist: [2, 3, 4]

 Modifying Lists:

o Lists are mutable, meaning their elements can be modified.

python

Copy

my_list[2] = 100 # Modify the third element

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

 Common List Methods:

o Append: Adds an element to the end of the list.

o Insert: Adds an element at a specific index.

o Remove: Removes the first occurrence of a specified value.

o Pop: Removes and returns the element at a specific index.

python

Copy

my_list.append(6) # Adds 6 to the end of the list

my_list.insert(2, 50) # Inserts 50 at index 2

my_list.remove(100) # Removes the first occurrence of 100


popped_item = my_list.pop() # Removes the last item (6)

 List Length:

o You can find the number of items in a list using the len() function.

python

Copy

length = len(my_list)

print(length) # Output: 5

3.5 List Processing and List Comprehensions

Python allows powerful ways to process and manipulate lists, and one of the most
Pythonic methods is list comprehensions.

 List Comprehensions:

o List comprehensions provide a concise way to create lists. They consist


of an expression followed by a for loop, and optionally, a condition.

python

Copy

squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]

 Filtering with List Comprehension:

o You can filter items in a list by adding a condition.

python

Copy

even_numbers = [x for x in range(10) if x % 2 == 0] # Output: [0, 2, 4, 6, 8]

 Nested List Comprehensions:

o You can also use nested list comprehensions to process multidimensional


data structures.
python

Copy

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

flattened = [x for row in matrix for x in row]

print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

 List Methods:

o Sorting: The sort() method sorts the list in place, while sorted() returns a
new sorted list.

o Reversing: The reverse() method reverses the list in place.

3.6 Summary of Module 3

Module 3 delved into several core concepts in Python that control the flow of
execution and enable us to handle lists and their processing efficiently. Here are
the key takeaways:

 Boolean Values: Essential for decision-making and controlling program flow.

 Conditional Execution: Use if, elif, and else statements to make decisions.

 Loops: Both for and while loops are used to repeat code. Break and continue
statements provide control over loop execution.

 Lists: Powerful data structures that store ordered, mutable collections. Learn
how to access, modify, and process lists.

 List Processing: Use list comprehensions to succinctly create and manipulate


lists, along with filtering and processing data.

With these tools at hand, you can build more interactive, dynamic, and efficient
programs. The next module will focus on functions and advanced data structures
such as dictionaries and exceptions.

Chapter-4
Module 4: Functions, Tuples, Dictionaries, Exceptions, and Data Processing
4.1 Functions in Python
Functions are a fundamental concept in programming, allowing you to organize your code into reusable blocks that
can be executed when called. In Python, functions are defined using the def keyword.

 Defining a Function:
o Functions allow you to group related statements together. A function can take parameters (inputs) and return
a result (output).

python
Copy
def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

 Function Parameters and Arguments:


o Parameters are variables defined in the function definition, and arguments are the values passed when
calling the function.

python
Copy
def add(a, b):
return a + b

result = add(3, 4) # Output: 7

 Default Parameters:
o You can define default values for parameters, which will be used if no argument is passed for that parameter.

python
Copy
def greet(name="Guest"):
return f"Hello, {name}!"

print(greet()) # Output: Hello, Guest!


print(greet("Bob")) # Output: Hello, Bob!

 Returning Values:
o Functions can return values, which can then be used by other parts of the program.

python
Copy
def multiply(a, b):
return a * b

result = multiply(2, 5) # result = 10

 Variable Scope:
o Local variables are defined within a function and can only be accessed inside that function.
o Global variables are defined outside of any function and can be accessed throughout the program.

python
Copy
x = 10 # Global variable

def func():
x = 5 # Local variable
print(x) # Output: 5
func()
print(x) # Output: 10 (global x remains unchanged)

 Lambda Functions:
o A lambda function is a small anonymous function defined with the lambda keyword. It’s used for
short, throwaway functions.

python
Copy
square = lambda x: x ** 2
print(square(4)) # Output: 16

4.2 Tuples in Python


A tuple is an ordered, immutable collection of items, and it is commonly used to store data that should not change
after creation. Tuples are similar to lists but with the key distinction that their contents cannot be modified.

 Defining Tuples:
o Tuples are defined using parentheses () and can contain any type of data.

python
Copy
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)

 Accessing Tuple Elements:


o Like lists, you can access tuple elements by their index (starting from 0).

python
Copy
print(my_tuple[0]) # Output: 1

 Tuple Immutability:
o Once a tuple is created, its elements cannot be changed, which makes them more efficient in memory
and performance when compared to lists.

python
Copy
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: 'tuple' object does not support item assignment

 Nested Tuples:
o Tuples can contain other tuples or collections.

python
Copy
nested_tuple = (1, (2, 3), 4)
print(nested_tuple[1]) # Output: (2, 3)

 Tuple Packing and Unpacking:


o You can "pack" values into a tuple and "unpack" them into variables.

python
Copy
my_tuple = (1, 2, 3)
a, b, c = my_tuple # Unpacking
print(a, b, c) # Output: 1 2 3

4.3 Dictionaries in Python


A dictionary is an unordered collection of key-value pairs. Dictionaries are useful for representing data where each
value is associated with a unique key.

 Defining a Dictionary:
o Dictionaries are created using curly braces {} with key-value pairs separated by a colon :. The key must
be unique.

python
Copy
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

 Accessing Dictionary Values:


o You can access values using their keys.

python
Copy
print(my_dict["name"]) # Output: Alice

 Modifying Dictionary:
o You can add or update key-value pairs in a dictionary.

python
Copy
my_dict["age"] = 26 # Update value for 'age'
my_dict["email"] = "alice@example.com" # Add new key-value pair

 Removing Elements:
o Use del to remove a key-value pair.

python
Copy
del my_dict["city"]
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}

 Dictionary Methods:
o keys(): Returns a view of all the keys in the dictionary.
o values(): Returns a view of all the values.
o items(): Returns a view of all the key-value pairs.

python
Copy
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'email'])
print(my_dict.values()) # Output: dict_values(['Alice', 26, 'alice@example.com'])

4.4 Exceptions in Python


An exception is an event that disrupts the normal flow of the program. Python uses try-except blocks to handle
exceptions, allowing the program to continue running instead of crashing.

 Handling Exceptions:
o The try block contains the code that might raise an exception, and the except block handles the error if
it occurs.

python
Copy
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!") # Output: Cannot divide by zero!

 Catching Multiple Exceptions:


o You can handle different types of exceptions by specifying multiple except blocks.

python
Copy
try:
x = int("hello") # This will raise a ValueError
except ValueError:
print("Value error occurred!")
except ZeroDivisionError:
print("Zero division error occurred!")

 The else and finally Clauses:


o The else block is executed if no exceptions occur, and the finally block is always executed, regardless
of whether an exception was raised.

python
Copy
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division was successful!")
finally:
print("This block is always executed.")

4.5 Data Processing in Python


Python provides various tools and libraries for efficient data processing, especially when working with large
datasets.

 List Processing:
o As seen earlier, lists are commonly used to store and process data. You can use list comprehensions and
map/filter functions to efficiently process data.

python
Copy
# List comprehension
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]

# Using map to apply a function to a list


numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x**2, numbers)) # Output: [1, 4, 9, 16]

# Using filter to get even numbers


even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # Output: [2, 4]
 Working with Files:
o Python allows you to read from and write to files, which is essential for data processing tasks.

python
Copy
# Writing to a file
with open("data.txt", "w") as file:
file.write("Hello, World!")

# Reading from a file


with open("data.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, World!

 Using Libraries for Data Processing:


o Python libraries like NumPy, Pandas, and Matplotlib provide powerful tools for scientific and
statistical data processing, analysis, and visualization.

4.6 Summary of Module 4


Module 4 introduced essential advanced concepts that will greatly enhance your ability to structure, manipulate,
and process data effectively in Python:

 Functions: Used to organize code into reusable blocks with parameters and return values.
 Tuples: Immutable data structures that store ordered collections of items.
 Dictionaries: Unordered collections of key-value pairs used to represent mappings.
 Exceptions: Used to handle errors and ensure smooth program execution even when things go wrong.
 Data Processing: Includes techniques for manipulating lists, working with files, and using libraries to process
and analyze data.

With these tools, you can begin building more robust and complex applications, particularly those that involve data
manipulation, error handling, and modular code design.

You might also like