Python Programming Lab Manual (3)
Python Programming Lab Manual (3)
Laboratory Manual
1
VISION OF THE UNIVERSITY
Alliance University’s vision is to be a world-class University that nurtures talent and catalytically
transforms the lives of millions through excellence in teaching, research, service and community
development. To uphold a commitment to shaping lives through scholarly teaching and learning, and that
which contributes to an equitable and holistic transformation of society at large.
University Strives to
• Prepare students for leadership through enlightened learning partnerships with faculty mentors
and the community.
• Support faculty and other scholars in pursuing world-class research: clinical, theoretical,
empirical, experiential and foster creative endeavour.
• Promote and preserve academic freedom, diversity, equality, harmony and justice.
• Develop mastery of disciplines and professions and instil confidence among its key constituents
in their application for a future of meaningful pursuits and productive work in the service of
humanity.
• Channelise faculty and student talent for professionally related service to the university, the
community and society at large.
Core Values
2
ALLIANCE COLLEGE OF ENGINEERING AND DESIGN
VISION:
To be a technical institution of repute nationally and internationally in higher learning and research and
to produce creative solutions to societal needs.
MISSION:
To provide every individual with a conducive environment suitable to achieve career goals, with a strong
emphasis on personality development, and to offer resources to the academically inclined, to gain quality
education in all spheres of engineering, applied sciences and management, without compromising the
quality and code of ethics to each student of the Institution.
Mission
M1. Facilitate meaningful connections between our students and leading industry partners, empowering
them to secure rewarding career opportunities based on the industry's competency requirement that align
with their skills, interests, and aspirations, thereby fostering a thriving professional community.
M2. Conduct pioneering research that advances the frontiers of computer applications, exploring novel
technologies and methodologies to address complex societal challenges and drive innovation in the digital
era.
M3. Cultivate an entrepreneurial mindset among our students, providing them with the resources,
mentorship, and support needed to transform innovative ideas into successful ventures, driving nation's
economic growth and societal impact.
M4. Empower graduates to pursue higher education opportunities at esteemed worldwide institutions,
nurturing their intellectual curiosity and leadership potential to become future pioneers and thought
leaders in the field of computer applications.
PROGRAM DETAILS
Program Educational Objectives
DATA SCIENCE:
3
PEO 1. Critically evaluate and interpret data using statistical, machine learning and Data Science
techniques
PEO 2. Apply creative problem-solving approaches to develop novel solutions that leverage data science
techniques for societal and organizational benefit.
PEO 3. Apply critical thinking skills for solving Complex Data Science problems to make informed
decisions.
PEO 4. Raise awareness of concerns pertaining to cyber health, safety, law, the environment, and national
and international cultural diversity.
AI&ML:
1. Apply creative and innovative thinking to develop novel AI & ML solutions, contributing to
advancements in technology and addressing emerging challenges in industry and society.
2. Evaluate the performance of AI & ML models through experimentation and validation.
3. Critically analyzing data, evaluating AI & ML models, and making informed decisions to improve
system performance and outcomes.
GAME DEVELOPMENT:
1. Embrace ethical considerations and social responsibility in game development, including diversity,
inclusion, and representation in games.
2. Creatively solve problems encountered during the game development process, including game design
challenges, technical issues, and project management hurdles.
3. Drive innovation and enrich gameplay experiences, using advancing technologies and trends within
the gaming industry, including virtual reality (VR), augmented reality (AR), artificial intelligence (AI),
and procedural generation.
PROGRAM OUTCOMES
PO 1: Disciplinary/Interdisciplinary Knowledge: Apply comprehensive interdisciplinary knowledge,
practical skills, and entrepreneurial mindset to address diverse challenges and innovate in chosen fields,
fostering adaptability and problem-solving capacity beyond to multidisciplinary field
PO 2: Complex Problem Solving: Solve different kinds of problems in familiar and non-familiar
contexts and apply the learning to real-life situations.
PO 3: Critical Thinking: Apply critical thinking skills to analyze, evaluate, and synthesize diverse
information, arguments, and evidence to formulate coherent arguments, identify logical flaws, and draw
valid conclusions supported by evidence.
4
PO 4: Creativity: Demonstrate versatility by creatively approaching diverse scenarios, tackling
complex problems innovatively, employing multiple perspectives, and leveraging imaginative, lateral
thinking, interpersonal skills, and emotional intelligence.
PO 5: Communication Skills: Apply Effectively communicate complex information with clarity and
sensitivity through attentive listening, analytical reading, precise writing, articulate oral expression,
confident sharing of views, construction of logical arguments using appropriate technical language, and
respectful language inclusive of diverse groups.
PO 6: Analytical reasoning/ thinking: Developing critical thinking skills to assess evidence reliability,
detect logical fallacies, analyze diverse data, draw valid conclusions, and effectively address opposing
viewpoints.
PO 7: Research-Related Skills: Demonstrate proficiency in observing, questioning, problematizing,
synthesizing, formulating hypotheses, designing methodologies, employing analytical tools, executing
experiments ethically, and reporting findings.
PO 8: Coordinating/Collaborating with each other: Collaborate respectfully within diverse teams, to
foster cooperation and efficiently contribute towards common goals.
PO 9: Leadership Readiness/qualities: Formulating an inspiring vision, assembling a capable team,
and employing effective management to navigate towards organizational goals while motivating and
engaging team members with the vision.
PO 10: Learning how to learn skills: Developing lifelong learning skills for personal, professional, and
societal adaptation, encompassing self-directed learning, resource identification, organizational and time
management, and fostering a proactive attitude towards continuous development.
PO 11: Digital and Technological Skills: Utilizing ICT for diverse learning and work scenarios,
including accessing, evaluating, and employing various information sources, along with utilizing
appropriate software for data analysis.
PO 12: Multiculture competence and inclusive spirit: Fostering cultural awareness, multicultural
competency, inclusive leadership, gender sensitivity, and empathy towards marginalized groups to
promote diversity, equity, and collaboration in various contexts.
PO 13: Value Inculcation: Embracing and embodying constitutional, humanistic, and moral values while
promoting responsible global citizenship, ethical conduct, sustainability, and integrity in all endeavors,
fostering a culture of truth, peace, and inclusivity.
PO 14: Autonomy, Responsibility and Accountability: Embracing and embodying constitutional,
humanistic, and moral values while promoting responsible global citizenship, ethical conduct,
sustainability, and integrity in all endeavors, fostering a culture of truth, peace, and inclusivity.
PO 15: Enviornmental Awareness and Action: Addressing environmental degradation, climate change,
and pollution through effective waste management, biodiversity conservation, forest and wildlife
preservation, and promotion of sustainable development practices.
PO 16: Community Engagement and Service: Demonstrate the capability to participate in community-
engaged services/ activities for promoting the wellbeing of society.
5
PO 17: Empathy: Demonstrate the ability to identify with or understand the perspective, experiences, or
points of view of another individual or group, and to identify and understand other people’s emotions
AI&ML:
1. Propose novel algorithms or techniques to improve the performance or efficiency of existing AI & ML
models.
2. Implement AI and machine learning algorithms for classification, regression, clustering, and
optimization.
3. Analyze datasets to extract meaningful insights and patterns using AI & ML tools.
GAME DEVELOPMENT:
1. Implement advanced game physics and sound effects to simulate realistic interactions within the game
environment.
2. Integrate artificial intelligence algorithms to create intelligent and dynamic non-player characters
(NPCs) and enemies.
3. Adhere to ethical and legal standards in the development and distribution of the game project, including
respect for intellectual property rights and responsible use of resources.
6
Objectives of the Lab
This Python programming lab aims to equip you with the essential skills to write and execute Python code
effectively. By the end of this lab, students will have a solid understanding of Python programming
fundamentals, allowing them to develop, debug, and optimize code for various applications. This lab
focuses on building a strong foundation in Python syntax, control structures, and basic problem-solving
techniques.
Common Goals:
Discipline Instructions
Code of Conduct:
• Adhere to all lab rules and instructions provided by the lab supervisor or instructor.
• Maintain professional behavior and respect towards peers, instructors, and lab staff.
• No food, drinks, or unauthorized electronic devices are allowed in the lab.
Use of Equipment:
• Use lab equipment only for its intended purpose and within the scope of your training.
• Do not modify or disassemble equipment without permission from the lab supervisor.
• Return all tools and equipment to their designated places after use.
Cleanliness and Organization:
• Keep your work area clean and organized.
• Dispose of any waste materials in appropriate containers and clean up spills immediately
Attendance Instructions
Punctuality:
• Arrive on time for all scheduled lab sessions. Late arrivals may not be allowed to participate in
the lab activities for safety reasons.
• Sign in upon arrival and sign out when leaving the lab.
Attendance Requirements:
• Attend all scheduled lab sessions. If you cannot attend, notify the lab supervisor in advance and
provide a valid reason.
• Make up for any missed lab sessions according to the lab supervisor’s instructions.
Participation:
8
Syllabus
School: ACED Program: BCA
Course Code: E1CAA202 Course Title: Lab - Python Programming
Credits: 4 Course Type: Core
Total Hours: 120 Hours/Week: 8 Hours
Course This course covers the fundamental concepts of Python programming Lab,
Overview including data types, control structures, functions, modules, and object-
oriented programming. It also includes practical applications of Python in
various fields such as web development, data analysis, and machine learning.
The course is designed to provide hands-on experience through practical
exercises and projects.
Course 1. Understand the basics of Python programming language.
Objectives 2. Develop problem-solving skills using Python.
3. Learn to write efficient and readable code.
4. Gain practical experience through hands-on projects.
5. Explore the applications of Python in various domains.
Course Outcomes
CO Description BT Level
1 Use Python programs using basic constructs. 3
9
List of Experiments
Text Books:
1. Mark Lutz, "Learning Python," O'Reilly Media, 5th Edition.
2. Zed A. Shaw, "Learn Python the Hard Way," Addison-Wesley.
Reference Books:
1. Al Sweigart, "Automate the Boring Stuff with Python," No Starch Press.
2. Eric Matthes, "Python Crash Course," No Starch Press.
MOOC:
1. https://www.coursera.org/specializations/python-3-programming
2. Python tutorials on Codecademy and W3Schools
Case Studies:
1. Automating Data Entry and Reporting
2. Web Scraping and Data Analysis
Assessment methods
Sl.No Assessment Description Weightage Course Outcomes To be Duration/
Type in marks Assessed Time line
10
CO1 CO2 CO3 CO4 CO5
1 CA Assignment 15 √ √ √ √ √ 24 Hrs
Practical
2 PE 20 √ √ 2 Hrs
Examination
3 QZ Quiz 10 √ √ √ 30 Mins
4 MP Mini Project 10 √ 7 Days
5 AT Attendance 5 √ √ √ √ √ 120 Hrs
Semester
6 SEE End- 40 √ √ √ 3 Hrs
Examination
CO-PO Mapping
Course P P P P P P P P P P P P P P P P P
Outco O O O O O O O O O O O O O O O O O
me 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
CO1 3 3 2 1 N 1 2 2 N 2 2 N N N N N N
A A A A A A A A
CO2 3 3 1 1 N 1 3 1 N 2 2 N N N N N N
A A A A A A A A
CO3 3 3 2 2 N 1 2 2 N 2 2 N N N N N N
A A A A A A A A
CO4 3 3 2 1 N 1 2 1 N 2 2 N N N N N N
A A A A A A A A
CO5 3 3 3 2 N 2 3 2 N 2 2 N N N N N N
A A A A A A A A
CO PSO Mapping
Program Specific Outcome
CO1 3 2 3 1 3 1 3 2 3
CO2 3 3 3 1 3 1 3 3 3
CO3 3 3 3 1 2 1 3 3 3
CO4 3 2 3 1 2 2 3 2 3
11
CO5 3 3 3 1 3 1 3 3 3
12
List of Experiments
13
Ex.No.1 Overview of Python
Date:
Aim:
To understand the basic concepts of Python programming language, its structure, syntax, and usage in
computational problem solving.
Requirements: Python-3
Theory:
Python is a high-level, interpreted, and general-purpose programming language, known for its simplicity
and readability. It was created by Guido van Rossum and first released in 1991. Python is widely used for
a variety of applications, including web development, data analysis, artificial intelligence, automation,
and scientific computing.
• Simple and Easy to Learn: Python’s syntax resembles English, making it easier to read and
understand.
• Interpreted Language: Python executes code line by line, which makes debugging easier and
allows for interactive testing.
• Object-Oriented: Python supports object-oriented programming (OOP) which helps in organizing
complex programs into simpler, reusable structures.
• Cross-platform: Python is available on multiple platforms (Windows, macOS, Linux, etc.),
making it highly portable.
• Extensive Libraries: Python has a large standard library and supports a wide range of third-party
packages for different purposes.
Python Basics:
1. Data Types: Python supports various data types such as integers, floats, strings, and booleans.
2. Variables: Variables store data values and do not need explicit declaration. The type of data is
determined during runtime.
3. Operators: Python supports arithmetic, comparison, logical, and bitwise operators.
4. Control Structures: Python allows the use of conditionals (if-else), loops (for, while), and
functions for effective control flow.
5. Functions: Functions allow code modularity and reusability. They are defined using the def
keyword.
6. Modules and Libraries: Python has a rich set of built-in libraries and external modules that extend
its functionality.
Python’s versatility and simplicity make it an ideal choice for beginners as well as experts for complex
applications, from web development to machine learning.
14
Ex.No. 2 Install Python and set up the programming environment
Date:
Aim:
To install Python and set up the programming environment for writing and executing Python programs.
Requirements: Python-3
Theory:
Python is a widely-used programming language known for its simplicity and ease of use. Before writing
Python code, it is essential to have Python installed on the system and a suitable programming
environment configured to ensure efficient development.
Steps for Installation and Setup:
1. Download Python:
- Python is available for download on the official website (https://www.python.org/). Both Python 3.x
and Python 2.x versions are available, but Python 3.x is recommended as Python 2.x is no longer
supported.
2. Installation Process:
- After downloading the installer, follow the steps specific to the operating system (Windows, macOS,
Linux):
- Windows: Run the installer and select 'Add Python to PATH' to make Python accessible from the
command line. Choose 'Install Now' for a typical setup.
- macOS: Python 2.x may be pre-installed, but users can install the latest version of Python 3.x using
Homebrew (brew install python3) or by downloading the installer from the official website.
- Linux: Python is often pre-installed on most Linux distributions. However, the latest version can be
installed using the package manager (e.g., sudo apt install python3 on Ubuntu).
3. Verify Installation:
- After installation, verify Python is installed correctly by opening the terminal (or command prompt)
and typing:
python --version
or
python3 --version
This should display the installed Python version.
4. Set up the Programming Environment:
- Integrated Development Environment (IDE): An IDE provides an enhanced environment for coding
and debugging. Popular IDEs for Python include:
- PyCharm: A dedicated Python IDE with powerful debugging tools, code refactoring, and testing
features.
- Visual Studio Code: A lightweight code editor with Python support and extensions.
- Jupyter Notebook: A web-based interactive computing environment ideal for data analysis and
visualization.
- Install Python Package Manager (pip): Pip is the default package manager for Python, used to install
additional libraries and frameworks. It often comes pre-installed with Python. Check if pip is installed
15
by running:
pip --version
If not installed, follow instructions to install pip from the official guide
(https://pip.pypa.io/en/stable/installation/).
5. Writing and Running a Python Program:
- Once Python is installed, create a simple 'Hello, World!' program to ensure everything is working
properly:
1. Open a text editor or IDE.
2. Write the following Python code:
print('Hello, World!')
3. Save the file with a .py extension (e.g., hello.py).
4. Open the terminal or command prompt, navigate to the directory where the file is saved, and run
the program using the command:
python hello.py
6. Setting Up Virtual Environments (Optional but Recommended):
- A virtual environment is used to create isolated Python environments for different projects, ensuring
dependencies for one project do not interfere with others. It can be set up using the venv module:
python -m venv myenv
To activate the virtual environment, use:
- Windows: myenv\Scripts\activate
- macOS/Linux: source myenv/bin/activate
Conclusion:
Installing Python and setting up the programming environment is an essential first step to begin
programming in Python. Proper configuration of the environment allows developers to write, execute,
and debug Python programs efficiently.
16
Ex.No.3 Write and execute simple Python programs
Date:
Aim:
To write and execute simple Python programs to understand the basic structure, syntax, and execution of
Python code.
Requirements: Python-3
Theory:
Python is an easy-to-learn programming language that is widely used due to its simplicity and
readability. Python supports various features like input/output operations, variables, data types, and
basic control flow using loops and conditionals. Learning how to write and execute basic programs
helps in understanding how Python handles these features.
In this experiment, we will go through some basic Python programs covering basic operations like
printing output, arithmetic operations, and simple loops.
Program:
Code:
Output:
Explanation:
The print() function outputs text to the console. In this case, it prints the message "Welcome to Python
programming!".
Code:
a=5
b=7
17
# Adding the numbers
result = a + b
Output:
Explanation:
The + operator adds them, and the result is stored in the variable result.
Code:
x=4
y=3
product = x * y
Output:
18
Explanation:
The * operator is used to multiply the numbers x and y, and the result is stored in product.
Code:
num = 6
Output:
Explanation:
To find the square, we multiply num by itself, and the result is stored in the variable square.
Code:
print(i)
19
Output:
Explanation:
The for loop iterates over a range of numbers from 1 to 5 (inclusive), and each number is printed using
print().
Conclusion:
By writing and executing basic Python programs, we have explored fundamental concepts such as output
using print(), arithmetic operations like addition and multiplication, and basic loops like for. These
programs help in building a foundation for understanding more complex Python concepts.
20
Ex.No.4 Perform operations on strings
Date:
Aim:
To perform various operations on strings using Python and understand how to manipulate and analyze
string data.
Requirements: Python-3
Theory:
In Python, strings are sequences of characters. They are immutable, meaning once created, they cannot
be changed. Python provides many built-in methods and operators for performing different operations
on strings, such as slicing, concatenation, case transformation, and searching within strings. Common
string operations include:
Program:
String initialization
string1 = "Hello"
string2 = "World"
1. Concatenation
concatenated_string = string1 + " " + string2
print("Concatenated String:", concatenated_string)
2. Slicing
sliced_string = concatenated_string[0:5]
print("Sliced String (First 5 characters):", sliced_string)
3. Changing case
upper_case_string = concatenated_string.upper()
lower_case_string = concatenated_string.lower()
print("Uppercase:", upper_case_string)
print("Lowercase:", lower_case_string)
5. Finding a substring
position = concatenated_string.find("World")
print("'World' found at position:", position)
21
6. Replace a substring
replaced_string = concatenated_string.replace("World", "Python")
print("String after replacement:", replaced_string)
Output:
Concatenated String: Hello World
Sliced String (First 5 characters): Hello
Uppercase: HELLO WORLD
Lowercase: hello world
Length of the concatenated string: 11
'World' found at position: 6
String after replacement: Hello Python
Conclusion:
In this experiment, we successfully performed various operations on strings in Python. We learned how
to concatenate, slice, change cases, find substrings, and replace parts of strings using built-in functions.
These operations are essential for effective string manipulation in programming.
22
Ex.No.5 Implement Loops and Conditional Statements
Date:
Aim:
To implement and understand the use of conditional statements (if, elif, else) and loops (for, while, and
nested loops`) in Python to control the flow of a program and perform repetitive tasks efficiently.
Requirements: Python-3
Theory:
In programming, control flow refers to the order in which individual statements, instructions, or
function calls are executed or evaluated. Python provides several control flow tools, including
conditional statements and loops, which allow the execution of code based on conditions or repetitions.
1. Conditional Statements:
Conditional statements allow the execution of certain blocks of code based on whether a condition is
True or False. Python's conditional statements include:
• if Statement: Executes a block of code only if the condition is true.
• elif Statement: Allows checking multiple conditions in sequence.
• else Statement: Executes if none of the conditions are true.
2. Loops:
Loops are used to execute a block of code repeatedly based on a condition or sequence. Python provides
two primary loop constructs:
• For Loop: Iterates over a sequence (like a list, tuple, dictionary, string, or range) and executes a block
of code for each element.
• While Loop: Runs a block of code as long as the condition is True.
• Nested Loops: Involves having one loop inside another, used for multi-level data structures.
Program:
if num > 0:
print(f"{num} is a positive number.")
elif num < 0:
print(f"{num} is a negative number.")
else:
print(f"{num} is zero.")
23
# While Loop Example
n=5
while n > 0:
print(n)
n -= 1
Output:
Enter a number: 3
3 is a positive number.
For Loop: 1, 2, 3, 4, 5
While Loop: 5, 4, 3, 2, 1
Multiplication Table (1 to 3)
Conclusion:
We successfully implemented conditional statements and loops in Python. These constructs help in
decision-making and repetitive tasks, making them crucial for efficient programming.
24
Ex.No.6 Manipulating Lists and List Comprehensions
Date:
Aim:
To perform various operations on lists such as appending, removing, slicing, and sorting. Additionally,
use list comprehensions to create and manipulate lists efficiently.
Requirements: Python-3
Theory:
A list in Python is a collection of items that are ordered, changeable, and allow duplicate values. Lists are
one of the most versatile data types in Python. You can perform several operations on lists such as
appending elements, removing elements, slicing lists, and sorting lists.
List comprehensions provide a concise way to create lists based on existing lists or other iterables. They
consist of brackets containing an expression followed by a for clause, and then zero or more if or for
clauses.
Where:
• expression: the output expression producing the elements of the new list.
• item: the variable representing each element in the iterable.
• iterable: the sequence or iterable to iterate over.
• condition (optional): a condition to filter elements.
Program:
my_list.append(60)
25
print("After appending 60:", my_list)
my_list.remove(30)
sliced_list = my_list[:3]
Output:
After appending 60: [10, 20, 30, 40, 50, 60]
After removing 30: [10, 20, 40, 50, 60]
Sliced list (first 3 elements): [10, 20, 40]
List sorted in descending order: [60, 50, 40, 20, 10]
26
List of squares from 1 to 10: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Squares of even numbers from 1 to 10: [4, 16, 36, 64, 100]
Even numbers from the list: [2, 4, 6, 8, 10]
Conclusion:
In this experiment, we successfully manipulated lists by performing operations such as appending,
removing, slicing, and sorting. We also used list comprehensions to create new lists efficiently based on
existing ones. List comprehensions offer a concise and readable way to work with lists, especially when
applying conditions or transformations.
27