0% found this document useful (0 votes)
3 views9 pages

Python Unit I & II

The document provides an introduction to Python, covering its installation, core concepts like variables, data types, and control structures, as well as user-defined functions and data structures. It also introduces NumPy, highlighting its role in scientific computing, its ndarray object, and its advantages over standard Python sequences, including vectorization and broadcasting. Additionally, it mentions the integration of NumPy with other libraries like SciPy for advanced scientific tools and algorithms.

Uploaded by

jeganbasha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Python Unit I & II

The document provides an introduction to Python, covering its installation, core concepts like variables, data types, and control structures, as well as user-defined functions and data structures. It also introduces NumPy, highlighting its role in scientific computing, its ndarray object, and its advantages over standard Python sequences, including vectorization and broadcasting. Additionally, it mentions the integration of NumPy with other libraries like SciPy for advanced scientific tools and algorithms.

Uploaded by

jeganbasha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit - 1

Python Introduction and Setup

Introduction to Python

Python is a high-level, interpreted, general-purpose programming language. It emphasizes


code readability with its simple syntax, often using English keywords, and a unique reliance on
indentation for defining code blocks. It supports multiple programming paradigms, including
object-oriented, imperative, and functional programming.

Installation of Python

1. Download the appropriate installer from the official Python website ([Link]).

2. Run the installer. Crucially, make sure to check the box that says "Add Python X.X to
PATH" during the installation process (especially on Windows).

3. Verify the installation by opening a command line (Terminal/CMD) and typing python --
version or python3 --version.

Core Concepts

Variables

● Definition: Variables are named storage locations used to hold data.

● Assignment: Variables are created when you assign a value to them using the equals sign
(=).

● Dynamic Typing: Python is dynamically typed, meaning you don't declare the variable
type; the type is inferred at runtime.

Types

Python has several built-in data types:

● Numeric:

0 int: Whole numbers (e.g., 10, -5).

○ float: Numbers with a decimal point (e.g., 3.14, 2.0).

● Boolean:
0 bool: Represents truth values (True or False).

● Sequence Types:

0 str: Text data (covered below).

○ list, tuple: Collections of items (covered later).

● Mapping Type:

0 dict: Key-value pairs (covered later).

● None Type:

0 NoneType: The single value None, often used to signify the absence of a value.

Strings (str)

● Definition: A string is a sequence of characters enclosed in single quotes ('hello'), double


quotes ("world"), or triple quotes ("""multi-line""").

● Immutable: Strings cannot be changed after creation.

● Operations: Support concatenation (+), repetition (*), and various methods (e.g.,

.upper(), .strip(), .split()).

● Indexing/Slicing: Individual characters or substrings can be accessed using square


brackets ([]).

Objects

● Fundamental Principle: Everything in Python is an object.

● Concept: An object is an instance of a class and has both data (attributes) and behavior
(methods).

● Identity, Type, Value: Every object has a unique identity (memory address), a type (class
it belongs to), and a value.

Execution and Logic

Jupyter Notebooks

● Purpose: An interactive computing environment that allows you to create and share
documents containing live code, equations, visualizations, and narrative text.
● Structure: Consists of cells. The two main types are Code cells (for running Python code)
and Markdown cells (for text and formatting).

● Usage: Great for prototyping, data analysis, and documentation.

Control Structures

Used to control the flow of execution in a program:

● Conditional Statements (if, elif, else): Execute a block of code only if a specified
condition is True.

● Loops:

○ for Loop: Used for iterating over a sequence (like a list, tuple, or string).

○ while Loop: Repeats a block of code as long as a specified condition remains True.

Operators

Operators perform operations on variables and values (operands).

● Arithmetic: +, -, *, / (division), // (floor division), % (modulus), ** (exponent).

● Comparison: >, <, == (equal), != (not equal), >= (greater or equal), <= (less or equal).
Result is always a bool (True/False).

● Logical: and, or, not. Used to combine conditional expressions.

● Assignment: =, +=, -=, etc.

User-Defined Functions

● Purpose: Blocks of code designed to perform a specific task. They promote reusability
and code organization.

● Definition: Created using the def keyword, followed by the function name, parentheses (),
and a colon :.

● Arguments/Parameters: Values passed into a function when it's called.

● Return Value: The return keyword is used to send a result back from the function.
Data Structures (Collections)

Data Structures

Containers used to store collections of data.

List

● Definition: An ordered, mutable (changeable) collection of items, enclosed in square


brackets ([]).

● Characteristics: Can store mixed data types. Supports indexing, slicing, and methods
like .append(), .insert(), and .remove().

Tuple

● Definition: An ordered, immutable (unchangeable) collection of items, enclosed in


parentheses (()).

● Characteristics: Typically used for data that shouldn't change, such as coordinates or
fixed records. Faster than lists for iteration.

Dictionary (dict)

● Definition: An unordered collection of data stored as key-value pairs, enclosed in curly


braces ({}).

● Characteristics: Keys must be unique and immutable (like strings or tuples), and are
used to lookup the associated values. Dictionaries are mutable (you can add, change, or
remove pairs).
Unit -II
NumPy
NumPy is the fundamental package for scientific computing in Python. It is a Python library that
provides a multidimensional array object, various derived objects (such as masked arrays and
matrices), and an assortment of routines for fast operations on arrays, including mathematical,
logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear
algebra, basic statistical operations, random simulation and much more.

At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays
of homogeneous data types, with many operations being performed in compiled code for
performance. There are several important differences between NumPy arrays and the standard
Python sequences:

NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically).
Changing the size of an ndarray will create a new array and delete the original.

The elements in a NumPy array are all required to be of the same data type, and thus will be the
same size in memory. The exception: one can have arrays of (Python, including NumPy) objects,
thereby allowing for arrays of different sized elements.

NumPy arrays facilitate advanced mathematical and other types of operations on large numbers
of data. Typically, such operations are executed more efficiently and with less code than is
possible using Python’s built-in sequences.

A growing plethora of scientific and mathematical Python-based packages are using NumPy
arrays; though these typically support Python-sequence input, they convert such input to NumPy
arrays prior to processing, and they often output NumPy arrays. In other words, in order to
efficiently use much (perhaps even most) of today’s scientific/mathematical Python-based
software, just knowing how to use Python’s built-in sequence types is insufficient – one also
needs to know how to use NumPy arrays.

The points about sequence size and speed are particularly Important in scientific computing. As a
simple example, consider the case of multiplying each element in a 1-D sequence with the
corresponding element in another sequence of the same length. If the data are stored in two
Python lists, a and b, we could iterate over each element:

C = []
For I in range(len(a)):
[Link](a[i]*b[i])
This produces the correct answer, but if a and b each contain millions of numbers, we will pay
the price for the inefficiencies of looping in Python. We could accomplish the same task much
more quickly in C by writing (for clarity we neglect variable declarations and initializations,
memory allocation, etc.)

For (I = 0; I < rows; i++) {


C[i] = a[i]*b[i];
}
This saves all the overhead involved in interpreting the Python code and manipulating Python
objects, but at the expense of the benefits gained from coding in Python. Furthermore, the coding
work required increases with the dimensionality of our data. In the case of a 2-D array, for
example, the C code (abridged as before) expands to

For (I = 0; I < rows; i++) {


For (j = 0; j < columns; j++) {
C[i][j] = a[i][j]*b[i][j];
}
}
NumPy gives us the best of both worlds: element-by-element operations are the “default mode”
when an ndarray is involved, but the element-by-element operation is speedily executed by pre-
compiled C code. In NumPy

C=a*b
Does what the earlier examples do, at near-C speeds, but with the code simplicity we expect
from something based on Python. Indeed, the NumPy idiom is even simpler! This last example
illustrates two of NumPy’s features which are the basis of much of its power: vectorization and
broadcasting.

Why is NumPy fast?


Vectorization describes the absence of any explicit looping, indexing, etc., in the code – these
things are taking place, of course, just “behind the scenes” in optimized, pre-compiled C code.
Vectorized code has many advantages, among which are: Vectorised code is more concise and
easier to read Fewer lines of code generally means fewer bugs
The code more closely resembles standard mathematical notation (making it easier, typically, to
correctly code mathematical constructs)

Vectorization results in more “Pythonic” code. Without vectorization, our code would be littered
with inefficient and difficult to read for loops.
Broadcasting is the term used to describe the implicit element-by-element behavior of
operations; generally speaking, in NumPy all operations, not just arithmetic operations, but
logical, bit-wise, functional, etc., behave in this implicit element-by-element fashion, i.e., they
broadcast. Moreover, in the example above, a and b could be multidimensional arrays of the
same shape, or a scalar and an array, or even two arrays with different shapes, provided that the
smaller array is “expandable” to the shape of the larger in such a way that the resulting broadcast
is unambiguous. For detailed “rules” of broadcasting see Broadcasting.

else uses NumPy?


NumPy fully supports an object-oriented approach, starting, once again, with ndarray. For
example, ndarray is a class, possessing numerous methods and attributes. Many of its methods
are mirrored by functions in the outer-most NumPy namespace, allowing the programmer to
code in whichever paradigm they prefer. This flexibility has allowed the NumPy array dialect
and NumPy ndarray class to become the de-facto language of multi-dimensional data
interchange used in Python.

Aspects of NumPy include:


Multidimensional Arrays: NumPy introduces the ndarray object, a powerful and efficient
way to store and manipulate numerical data in one or more dimensions. Unlike standard Python
lists, NumPy arrays are homogeneous, meaning all elements within an array must be of the same
data type, which contributes to their performance.
High-Performance Operations: NumPy provides a vast collection of high-level mathematical
functions and routines optimized for operating on these arrays. These operations are often
implemented in C or Fortran, leading to significantly faster execution compared to equivalent
operations on standard Python lists, especially for large datasets.
Mathematical and Scientific Computing: NumPy is a cornerstone of the Python scientific
computing ecosystem. It offers extensive functionalities for linear algebra, Fourier transforms,
random number generation, and various other mathematical and statistical operations, making it
essential for fields like data science, machine learning, and engineering.
Broadcasting: NumPy features a powerful mechanism called broadcasting, which allows
operations to be performed on arrays of different shapes, provided they meet certain
compatibility rules. This simplifies code and avoids the need for explicit loops in many cases.
Integration with Other Libraries: NumPy serves as the foundation for many other popular Python
libraries used in scientific computing, such as SciPy, Matplotlib, and Pandas, facilitating
seamless data manipulation and analysis workflows.
NumPy Library

NumPy (Numerical Python) is the fundamental package for scientific computing in Python. It

Provides high-performance, multi-dimensional array objects and tools for working with these
Arrays.

SciPy Library for Statistics

SciPy (Scientific Python) is a library built on NumPy that provides a large collection of

Scientific tools and algorithms, including optimization, linear algebra, integration, interpolation,

Special functions, and statistics.

● [Link] sub package: Provides standard linear algebra operations like determinants,

Matrix inversion, and eigenvalue problems. It is more advanced than [Link] .


Unit -III

You might also like