0% found this document useful (0 votes)
5 views

Python Programming Lab Introduction

This document provides an introduction to Python programming, covering installation, basic syntax, and foundational concepts such as variables, data types, and control structures. It also explores functions, modules, lists, tuples, dictionaries, sets, strings, and file I/O operations, emphasizing Python's simplicity and versatility. Each section includes examples and explanations to help beginners understand how to effectively write and execute Python code.

Uploaded by

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

Python Programming Lab Introduction

This document provides an introduction to Python programming, covering installation, basic syntax, and foundational concepts such as variables, data types, and control structures. It also explores functions, modules, lists, tuples, dictionaries, sets, strings, and file I/O operations, emphasizing Python's simplicity and versatility. Each section includes examples and explanations to help beginners understand how to effectively write and execute Python code.

Uploaded by

23pa1a0352
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Experiment 1: Introduction to Python

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:

# This is a simple Python program to display "Hello, World!"

print("Hello, World!")

Output:

 After running the "Hello, World!" program, the output on the console should be:
Hello, World!
Steps:

 Open your chosen IDE.


 Create a new Python file (e.g., hello.py).
 Type the above code into the editor and save the file.
 Run the file in the IDE to see the output, or use the terminal by typing python hello.py.

Understand and Demonstrate Basic Python Syntax and Semantics:

 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.

Why Use Python?

 Python is an interpreted, high-level language that emphasizes code readability.


 Its syntax allows programmers to express concepts in fewer lines of code compared to languages
like C++ or Java.
 Python has a large standard library and a vast ecosystem of third-party libraries, making it highly
versatile.

Basic Python Structure:

 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.

1. Variables and Data Types:

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

# Call the function and display the result


result = add_numbers(5, 3)
print("Sum:", result)

Output:
Sum: 8

b. Function with Default Arguments:

# Define a function with a default argument

def greet(name="Guest"):
print(f"Hello, {name}!")

# Call the function with and without providing the argument

greet("Alice")

greet() # Uses the default value

Output:

Hello, Alice!

Hello, Guest!

c. Function with Keyword Arguments:

# Define a function using keyword arguments

def introduce(name, age):

print(f"My name is {name} and I am {age} years old.")

# Call the function with keyword arguments

introduce(age=25, name="Bob")

Output:

My name is Bob and I am 25 years old.

Explore and Use Built-in Python Modules:

Modules:

 What is a Module?: A module is a file containing Python definitions and statements.


Modules allow you to reuse code across programs. Built-in modules like math, random, and
datetime offer pre-built functionality for common tasks.
 Importing Modules: Modules can be imported using the import keyword. You can import
specific functions from a module using from module_name import function_name.
 Program:

a. Using the math Module:


import math

# Calculate the square root and power of a number


num = 16
sqrt_num = math.sqrt(num)
power_num = math.pow(num, 2)

print(f"Square root of {num} is {sqrt_num}")


print(f"{num} raised to the power of 2 is {power_num}")
Output:
Square root of 16 is 4.0
16 raised to the power of 2 is 256.0

b. Using the random Module:


import random

# Generate a random number between 1 and 10


random_number = random.randint(1, 10)

# Generate a random floating-point number


random_float = random.uniform(0.0, 1.0)

print(f"Random integer between 1 and 10: {random_number}")


print(f"Random floating-point number between 0 and 1: {random_float}")

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.

Use Dictionary Comprehension:

 Dictionary comprehension is a concise way to create dictionaries, much like list


comprehensions but using key-value pairs.
 The general syntax for dictionary comprehension is {key_expression: value_expression for item in
iterable if condition}.
 In this example, we use dictionary comprehension to generate a dictionary of numbers and
their squares. We can also include conditions, like filtering for even numbers.

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.

The key concepts include:

 try-except blocks to catch and handle exceptions.


 Using else and finally clauses for additional logic after exception handling.
 Handling specific exceptions for more precise error management.
 Creating and raising custom exceptions for specific situations in your program.
 Exception Handling in Python:
o Python provides an error-handling mechanism via exceptions, which are events
that occur during the execution of a program that disrupt the normal flow of the
program's instructions.
o Common built-in exceptions include ZeroDivisionError, TypeError, ValueError, and
IOError.
 Structure of try-except:
o try: Code that may cause an exception is written inside this block.
o except: This block catches exceptions and executes the code to handle the error.
o else: The else block runs only if no exception was raised.
o finally: The finally block runs regardless of whether an exception occurred or not.
It's often used for resource cleanup (e.g., closing files or releasing resources).
 Handling Specific Exceptions:
o Python allows handling multiple specific exceptions by using multiple except
blocks. This allows for targeted error handling depending on the type of error that
occurs.
 Custom Exceptions:
o In addition to built-in exceptions, Python allows you to define your own custom
exceptions by inheriting from the base Exception class.
o Custom exceptions are useful when you want to handle specific conditions or
business logic errors in a more controlled manner.
 Raising Exceptions:
o The raise statement allows you to raise an exception programmatically. You can
raise both built-in and custom exceptions using raise.
Experiment 8: Object-Oriented Programming (OOP)
Introduction:

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.

Key OOP concepts covered in this experiment:

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.

1. Classes and Objects:


o Class: A blueprint for creating objects. Classes define a structure for the data (attributes)
and the behavior (methods) that objects will have.
o Object: An instance of a class. It is created using the class constructor and can access the
attributes and methods defined by the class.
2. Inheritance:
o Inheritance allows one class (child or subclass) to inherit attributes and methods from
another class (parent or superclass). This promotes code reusability.
o In the example above, Dog and Cat inherit from the Animal class. They both have access
to the attributes and methods defined in Animal.
3. Polymorphism:
o Polymorphism allows objects of different classes to be treated as objects of a common
superclass. This allows for methods to be used interchangeably between different object
types, as long as they inherit from the same base class.
o This is seen in the animal_sound function, where both Dog and Cat objects can be passed,
and they produce different outputs based on their overridden make_sound method.
4. Class Variables vs Instance Variables:
o Class variables are variables that are shared across all instances of a class. They are
declared within the class but outside of the class constructor.
o Instance variables are variables that are unique to each object. They are defined within
the constructor (__init__ method) and are accessed using self.
o Modifying a class variable affects all instances, while modifying an instance variable
only affects the specific instance.
Experiment 9: Libraries and Packages
Introduction:

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.

2. Creating Python Packages:


o A Python package is a directory that contains a collection of modules and an __init__.py
file. Packaging your code allows it to be easily shared and reused.
o Packages can be distributed via PyPI (Python Package Index) and installed using pip.

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.

1. Data Manipulation with Pandas:


o Pandas offers powerful tools for handling large datasets in Python. It provides flexible
data structures such as Series (1D) and DataFrames (2D) for manipulating data.
o Common data manipulation tasks include filtering data based on conditions, grouping and
aggregating data, and transforming data (e.g., adding or modifying columns).

2. Data Visualization with Matplotlib and Seaborn:


o Matplotlib is the foundation of many visualization libraries in Python. It is versatile and
supports a wide range of plot types (e.g., line plots, bar charts, histograms).
o Seaborn simplifies the process of creating attractive and informative statistical graphics.
It integrates well with Pandas, making it easy to plot data stored in DataFrames.
o Visualization is a key step in data analysis, allowing patterns and trends to be observed
more easily than through raw data alone.
3. Data Analysis:
o Basic data analysis involves calculating descriptive statistics such as mean, median, and
standard deviation. These statistics provide insight into the distribution and variability of
the dataset.
o Summarizing findings is important in data analysis. After performing operations and
calculations on data, it is essential to interpret the results and communicate the key
insights.

You might also like