Python Programming Lab Introduction
Python Programming Lab Introduction
Introduction:
Python is one of the most popular programming languages due to its simplicity and readability. It
is widely used in web development, data science, artificial intelligence, and automation. Before
diving into Python programming, it is essential to set up the environment in which Python code
will be written, executed, and debugged. This experiment will guide you through the installation
process and introduce you to the basic structure and syntax of a Python program.
Python uses a straightforward syntax that makes it accessible to beginners while still being
powerful for experienced developers. By understanding the basic setup and writing a simple
program, you will take the first step toward mastering Python.
1. Install Python:
o Description: Python can be downloaded from its official website
(https://www.python.org). Ensure you download the latest stable version. During
installation, make sure to check the option "Add Python to PATH" to enable you to run
Python from the command line.
o Instructions:
Download Python from the official website.
Follow the installation wizard and make sure to add Python to the system path.
Verify installation by opening the command prompt and typing python --version.
2. Install an Integrated Development Environment (IDE):
o Description: An IDE provides a user-friendly interface for writing, testing, and
debugging code. Some popular IDEs for Python include PyCharm, Visual Studio Code
(VSCode), and Jupyter Notebooks.
o Steps:
Choose and download an IDE such as PyCharm or VSCode.
Set up the IDE by following the installation instructions. For VSCode, you may
need to install the Python extension.
3. Write and Run a Simple "Hello, World!" Program:
o Description: The "Hello, World!" program is traditionally the first program written in
any language. It helps ensure that the environment is set up correctly and introduces you
to the basics of syntax and execution.
Program:
print("Hello, World!")
Output:
After running the "Hello, World!" program, the output on the console should be:
Hello, World!
Steps:
Description: Python syntax is simple and uses indentation to define code blocks, unlike
other languages that use curly braces ({}) or keywords. You will explore some basic
Python syntax, including variable declaration, basic arithmetic operations, and printing
outputs to the console.
Indentation: Python uses indentation (usually four spaces) to define blocks of code. This is
different from most programming languages that use curly braces {}.
Comments: In Python, comments begin with the # symbol. They are ignored by the interpreter
and are useful for explaining the code.
Functions and Control Flow: Python supports functions and control flow constructs such as
loops (for, while) and conditionals (if, else, elif).
Experiment 2: Basic Python Programming
Introduction:
Python is a versatile and beginner-friendly language that uses simple syntax and semantics. In
this experiment, you will explore the foundational constructs needed to write Python programs.
These include variables for storing data, data types for defining the kind of data, and operators
for manipulating data. Furthermore, the experiment covers control structures that help make
decisions in a program or repeat a set of instructions.
Mastering these basic programming constructs is essential for developing more complex logic
and algorithms in later stages of learning.
Variables are names given to memory locations that store values. In Python, you don’t need
to declare the type of a variable explicitly. It’s inferred based on the value assigned.
Data Types: Python supports several data types, including:
Integers: Whole numbers (e.g., x = 5)
Floats: Decimal numbers (e.g., y = 5.5)
Strings: Sequences of characters (e.g., message = "Hello")
Booleans: Represent True or False (e.g., is_active = True)
Operators:
Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division)
Comparison Operators: == (equal), != (not equal), > (greater than), < (less than)
Logical Operators: and, or, not
Input/Output Functions:
input(): Used to take input from the user as a string.
print(): Used to display output to the console. It supports string formatting using f-strings
(e.g., print(f"Hello, {name}")).
Control Structures:
If Statements: Used to execute code based on conditions.
For Loops: Iterate over sequences (lists, strings, ranges).
While Loops: Repeat a block of code as long as a condition is true.
Experiment 3: Functions and Modules
Introduction:
Functions are essential building blocks in any programming language, including Python. They
allow you to group a set of instructions under a name, which can be reused as needed. Functions
make code more organized, reusable, and easy to debug. Python also comes with many built-in
modules that provide pre-written code for common tasks, such as working with dates, random
numbers, or file input/output. By using functions and modules, developers can write more
efficient and organized code.
1. Functions:
o Function Definition: A function is defined using the def keyword followed by the
function name, parameters in parentheses, and a colon. The function body is indented.
o Calling Functions: After defining a function, you can call it by its name, passing
arguments if required.
o Return Values: A function can return values using the return keyword. If no return is
used, the function returns None by default.
o Types of Arguments:
Positional Arguments: These are passed to the function based on their position.
Keyword Arguments: These are passed by specifying the argument name.
Default Arguments: Provide default values for arguments, making them
optional.
Variable-Length Arguments: Use *args for positional arguments and **kwargs
for keyword arguments to pass an arbitrary number of values.
1. Define and Call Functions with Different Types of Arguments and Return Values:
o Description: Functions can accept arguments (inputs) and return values (outputs). Python
supports several types of arguments: positional arguments, keyword arguments, default
arguments, and variable-length arguments. This section will cover how to define
functions with these different argument types and how to handle return values.
o Program:
a. Simple Function Example:
# Define a function that adds two numbers
def add_numbers(a, b):
return a + b
Output:
Sum: 8
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice")
Output:
Hello, Alice!
Hello, Guest!
introduce(age=25, name="Bob")
Output:
Modules:
Output:
Random integer between 1 and 10: 7
Random floating-point number between 0 and 1: 0.531457
Experiment 4: Lists and Tuples
Introduction:
Python provides several versatile data structures, and among the most commonly used are lists
and tuples. Lists are mutable, meaning their elements can be changed, added, or removed. They
are perfect for situations where you need a dynamic collection. On the other hand, tuples are
immutable, meaning once created, their contents cannot be changed. They are used in situations
where data integrity is important, and you don’t want accidental modification.
List comprehensions are a concise way to create new lists by iterating over existing lists or
other iterables. They allow for a more readable and shorter syntax compared to traditional for-
loops.
Lists:
Lists are ordered, mutable sequences of elements. You can add, remove, or change items
in a list. Lists are created using square brackets ([]), and elements are separated by
commas.
Common Operations:
o append(): Adds an element to the end of the list.
o remove(): Removes the first occurrence of an element.
o Indexing: Lists can be accessed using an index, where the first element has an
index of 0.
List Comprehension:
o List comprehensions provide a concise way to create new lists by iterating over an
iterable (like a list or range) and applying some transformation to the elements.
o Syntax: [expression for item in iterable] or with conditions [expression for item in iterable if
condition].
Tuples:
Tuples are ordered, immutable sequences of elements. Once created, their values cannot
be changed. Tuples are created using parentheses (()).
Immutability: Tuples cannot be modified after they are created. This makes them useful
for storing data that should not change.
Common Uses: Tuples are often used for data integrity, such as returning multiple
values from functions or using them as keys in dictionaries.
Immutability: The code tries to change the value of a tuple element, but this raises a
TypeError, showing that tuples are immutable.
Tuple Operations: While tuples themselves cannot be changed, you can perform
operations like concatenation to create new tuples with added or altered data.
Experiment 5: Dictionaries and Sets
Introduction:
Python provides several data structures, and among the most powerful are dictionaries and sets.
Dictionaries are collections of key-value pairs. Unlike lists or tuples that are indexed by
a range of numbers, dictionaries are indexed by keys, which can be any immutable type
(such as strings or numbers). This makes dictionaries highly efficient for lookup,
insertion, and deletion operations based on the key.
Dictionaries store data in key-value pairs. Keys must be unique and immutable, while
values can be of any type.
Adding or modifying values is done by assigning a value to a key. If the key exists, the
value is updated; otherwise, a new key-value pair is added.
Accessing values is done using the key as an index. If the key is not found, Python will
raise a KeyError unless you use methods like get().
Deleting key-value pairs is performed using the del keyword, which completely removes
both the key and its associated value.
Dictionaries:
o Dictionaries are unordered collections of key-value pairs. Each key in a dictionary must
be unique and immutable (e.g., strings, numbers, or tuples), but the values can be of any
data type.
o Common Operations:
get(key, default): Returns the value associated with the key, or a default value if
the key is not found.
items(): Returns a view object that displays a list of dictionary's key-value tuple
pairs.
keys(): Returns a view object containing all keys.
values(): Returns a view object containing all values.
1. Dictionary Comprehension:
o Dictionary comprehension provides a concise way to create dictionaries. You can
iterate over an iterable and construct key-value pairs based on some logic.
o Syntax: {key_expression: value_expression for item in iterable if condition}.
Sets are unordered collections of unique elements. They are particularly useful when you
need to eliminate duplicates or perform set operations like union, intersection, and difference.
Since sets do not allow duplicate values, they ensure that each element is unique.
2. Sets:
o Sets are unordered collections of unique elements. Sets are useful when you need to store
distinct items and perform mathematical set operations like union, intersection, and
difference.
o Common Operations:
add(): Adds an element to the set.
remove(): Removes a specific element from the set. Raises a KeyError if the
element is not present.
Set Operations:
Union (union() or |): Combines two sets, keeping all unique elements.
Intersection (intersection() or &): Returns only the elements that are
present in both sets.
Difference (difference() or -): Returns the elements present in the first set
but not in the second.
Experiment 6: Strings and File I/O
Python offers extensive support for both string manipulation and file I/O operations, which are
commonly used in a variety of applications. Understanding how to handle strings is crucial
because text data is widely used, from simple command-line programs to complex web
applications.
File I/O operations allow programs to interact with external files, which can store data
permanently. Python supports working with text files, as well as structured file formats like CSV
(Comma Separated Values) and JSON (JavaScript Object Notation), which are often used for
data storage and transfer.
1. Strings:
o Strings in Python are sequences of characters and are one of the most commonly
used data types.
o Python provides a wide range of built-in methods for working with strings, such
as strip(), split(), join(), upper(), lower(), replace(), and format().
o String slicing allows you to extract substrings by specifying indices.
2. File I/O:
o File input/output (I/O) operations are essential for any program that needs to read
data from or write data to files.
o The open() function is used to open a file, and it takes two arguments: the file
name and the mode (e.g., 'r' for reading, 'w' for writing).
o It is always good practice to use the with statement for file I/O to ensure that files
are properly closed after use.
3. CSV Files:
o CSV is a widely used file format for tabular data. Each line in a CSV file
represents a row, and each value is separated by a comma. The csv module in
Python makes it easy to read from and write to CSV files.
4. JSON Files:
o JSON is a lightweight data format that is easy for humans to read and write, and
easy for machines to parse and generate.
o Python’s json module allows you to serialize (convert a Python object to JSON)
and deserialize (convert JSON back to a Python object).
Experiment 7: Error Handling and Exceptions
Error handling is an essential part of writing robust and reliable software. In Python, errors (or
exceptions) can occur at runtime, and proper handling ensures that the program can gracefully
recover from unexpected conditions. By using exceptions, Python provides a structured way to
handle errors without crashing the program. This mechanism is known as exception handling.
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes
to design and structure software. Python, being a versatile language, supports OOP, allowing
developers to model real-world entities and relationships in code. OOP provides concepts like
inheritance, polymorphism, encapsulation, and abstraction, which make code modular,
reusable, and easier to maintain.
1. Classes and Objects: Creating and using custom-defined types (classes) and their instances
(objects).
2. Inheritance: Establishing relationships between classes by allowing a class to inherit properties
and behavior from another class.
3. Polymorphism: Providing a way to use a single function or method in different contexts.
4. Class and Instance Variables: Understanding the difference between variables that belong to a
class versus those that belong to an instance of the class.
Python is a highly versatile language due to its extensive collection of third-party libraries. These
libraries allow developers to avoid reinventing the wheel by reusing pre-written code, making
development faster and more efficient. NumPy and Pandas are two essential libraries that
simplify working with numerical data and data analysis.
1. Third-Party Libraries:
o Python’s extensive ecosystem of third-party libraries extends the capabilities of the
language, making it suitable for tasks like scientific computing, web development, data
analysis, and more.
o NumPy and Pandas are widely used for numerical computations and data analysis,
respectively.
3. Virtual Environments:
o A virtual environment is an isolated Python environment where you can install
packages without affecting the global Python installation. This is crucial for maintaining
different project dependencies without conflicts.
o Virtual environments ensure that different projects do not interfere with each other’s
package requirements.
Experiment 10: Working with Data
Introduction:
In the modern world, data plays a crucial role in decision-making across various fields like
business, healthcare, engineering, and more. Python has emerged as a powerful tool for data
analysis due to its simplicity and the strength of its libraries such as Pandas, Matplotlib, and
Seaborn. These libraries make data analysis and visualization easier and more efficient.
Pandas is a library designed for data manipulation and analysis. It offers data structures like
DataFrames that are perfect for handling tabular data.
Matplotlib and Seaborn are popular Python libraries used for creating static, animated, and
interactive visualizations. Seaborn is built on top of Matplotlib and provides a high-level
interface for creating attractive and informative statistical graphics.