Python Unit1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Course: MScDS

Python Programming

Module: 1
Preface

In an age dominated by data, technological advances, and the

ever-evolving realm of digitization, the importance of

understanding programming languages, especially Python, has

never been more pronounced. Python stands as one of the most

versatile, user-friendly, and widely utilised languages, serving

both beginners venturing into the programming world and

experts working on cutting-edge research.

This course aims to serve as a comprehensive guide for readers

keen to delve deep into the Python universe. From basic

fundamentals to intricate data structures, from the elegance of

object-oriented programming to the pragmatism of data science,

this work endeavours to encapsulate every nuance of Python.

While it's tempting to view programming as merely typing lines of

code, the truth is more profound. It's about problem-solving,

creativity, and innovation. It's about building solutions and

shaping the future. The topics covered in this course are not just

to impart knowledge of Python's syntax but to kindle the


analytical thought process, nurturing the programmer's ability to

think, design, and implement solutions to complex problems.

Whether you're an aspiring coder, a seasoned developer looking

to add Python to your repertoire, or someone curious about the

world of programming, this book is crafted for you. Journey with

us as we navigate through the captivating maze of Python, one

chapter at a time.

Learning Objectives:

1. Understand the history, philosophy, and core benefits of

Python, and be proficient in setting up a Python

environment.

2. Acquire the skills to effectively utilise Jupyter Notebook for

Python code development, visualisation, and documentation.

3. Identify and differentiate between the fundamental data

types in Python, demonstrating the ability to perform type

conversions and checking.

4. Apply arithmetic, comparison, logical, and other specialised


operators to manipulate and evaluate Python data types and

expressions.

5. Demonstrate proficiency in creating, accessing, and

manipulating the primary data structures in Python including

lists, tuples, sets, and dictionaries.

6. Implement loops for repetitive tasks and define functions for

modular coding, emphasising the importance of control flow

and reusability in programming.

Structure:

1.1 Basics of Python

1.2 Jupyter Notebook

1.3 Data Types in Python

1.4 Operators

1.5 Data Structures

1.6 Loops

1.7 Functions

1.8 Summary
1.9 Keywords

1.10 Self-Assessment Questions

1.11 Case Study

1.12 Reference

1.1 Basics of Python

Python is a high-level, general-purpose programming language,

renowned for its simplicity and readability. Guido van Rossum, a

Dutch programmer, created Python in the late 1980s. Over the

years, Python has been employed in a variety of domains ranging

from web development and data analysis to artificial intelligence

and scientific computations. Its straightforward syntax, inspired

by the English language, makes it easily comprehensible for

beginners.

● Syntax: Python prioritises code readability. Its syntax allows

developers to express concepts in fewer lines of code than

languages like C++ or Java.

● Libraries: Python has a rich set of libraries that can assist in


various tasks, eliminating the need to write code from

scratch for many common operations.

● Variables: In Python, you don't need to declare variables

explicitly. The assignment of a value to a variable

automatically declares it.

History and Philosophy of Python

Guido van Rossum began working on Python in the late 1980s and

released the first version in 1991. He wanted to create a language

that upheld the principle of code readability. This philosophy is

best expressed in "The Zen of Python," a collection of 19

aphorisms that captures the essence and design principles of the

Python language.

● Python's name doesn't originate from the snake but is rather

a tribute to the British comedy show "Monty Python's Flying

Circus," which Guido was fond of.

● The Zen of Python can be accessed by typing import this in

the Python interpreter. It emphasises simplicity, clarity, and

the importance of readability.


Features and Benefits of Python

Python has several salient features that make it a choice language

for developers worldwide:

● Versatility: Python can be used for web development, data

analysis, artificial intelligence, scientific computations, and

more.

● Portability: Python is cross-platform, which means Python

programs can be run on any operating system without

modification.

● Dynamic Typing: Python variables are not bound to a

specific data type, making it flexible.

● Interpreted Language: Python code is executed line-by-line,

which aids in debugging.

● Open Source: Python is freely available and supported by a

vast community.

Installing Python and Setting Up the Environment

1. Visit the official Python website at python.org.


2. Navigate to the "Downloads" section and choose the version

suitable for your operating system (Windows, macOS, Linux).

3. Follow the installation instructions. Ensure you check the

option "Add Python to PATH" during installation, making it

accessible from the command line.

4. Once installed, you can verify the installation by typing

python --version in the command prompt or terminal.

The Python Interpreter and Interactive Mode

After installation, Python provides two primary modes for

execution:

● Script Mode: You write your Python code in a file (with a .py

extension) and execute the script using the command

python filename.py.

● Interactive Mode (or Shell Mode): This mode is useful for

executing Python statements and seeing their results

immediately. Simply type python in the command prompt or

terminal, and you'll be presented with the Python

interactive prompt (>>>). Here, you can type any Python


command and see its output in real-time.

1.2 Jupyter Notebook

Jupyter Notebook is an open-source interactive computational

environment that allows users to create and share documents

containing live code, equations, visualisations, and narrative text.

Originally developed as part of the IPython project, it has grown

into a robust platform widely adopted for data analysis, scientific

research, and education in numerous disciplines, including Python

programming.

Installing and Launching Jupyter Notebook

To use Jupyter Notebook, one must first install it. Given its

relevance with Python programming, it comes conveniently with

the Anaconda distribution, which is a popular distribution for

Python and R.

Steps for Installation:

1. Install Anaconda: Download the appropriate version of

Anaconda for your OS. This will install both Python and
Jupyter Notebook.

2. Installation Check: After installation, you can check the

installation by typing jupyter notebook in your terminal (for

macOS and Linux) or command prompt (for Windows). This

will launch the Jupyter Notebook in your default browser.

Basics of Notebook Interface

Upon launching Jupyter Notebook, you'll be presented with the

dashboard that displays the notebooks and folders in the current

directory.

Key Features of the Interface:

● Files Tab: This tab shows the list of files and folders in the

current directory.

● Running Tab: This tab displays all currently running

notebooks.

● New Drop-down Button: Used to create a new notebook or

a new folder.

● Notebook Cells: Once inside a notebook, you can input code


or text into cells. There are mainly three types of cells: code

cells, markdown cells, and raw cells. You execute a cell by

pressing Shift + Enter.

Creating and Saving Notebooks

Creating a new notebook is as simple as:

1. Click on the 'New' drop-down button in the dashboard.

2. Select 'Python [default version]'.

3. A new tab will open with an untitled notebook. You can

rename it by clicking on "Untitled" at the top.

To save the notebook:

1. Click on the disk icon or navigate to File > Save and

Checkpoint.

Benefits of Using Jupyter for Python Programming

Using Jupyter Notebook for Python programming offers myriad

benefits:

● Interactivity: One can run individual cells and see outputs

immediately. This interactive nature is especially useful for

data analysis tasks.


● Documentation: The ability to combine narrative text with

code makes Jupyter excellent for documentation. This

ensures that the code is not just executable but also

understandable.

● Visualisation: Integrates seamlessly with various data

visualisation libraries like Matplotlib and Seaborn, allowing

for inline display of plots.

● Extensibility: Jupyter supports various programming

languages beyond Python, such as R and Julia.

● Sharing: Notebooks can be easily shared among peers,

facilitating collaborative work. They can also be exported in

various formats like PDF, HTML, etc.

● Educational Tool: Given its comprehensive nature, it's a

great tool for teaching and learning Python programming,

ensuring students not just write the code but understand it

in a broader context.

1.3 Data Types in Python


In Python, data types are fundamental. They determine the

nature of the data that a variable can store.

1. Common Data Types

● Integers

● Description: Represent whole numbers, both positive

and negative.

● Example: -3, 0, 42

● Floats

● Description: Denote real numbers and are used to

represent decimal points.

● Example: -2.9, 0.0, 3.14

● Strings

● Description: Series of characters. In Python, strings can

be enclosed in single ('), double ("), or even triple (''' or

""") quotes.

● Example: 'Hello', "Python", '''BCA Course'''

● Booleans

● Description: Express a truth value, which can be either


True or False.

● Usage: Essential in control structures and conditions.

● Example: True, False

2. Type Conversion and Type Checking

● Type Conversion

● Often in programming, there's a need to convert one

data type into another.

● Python provides built-in functions for these

conversions.

● int(): Converts a value to an integer.

Example: int(3.4) results in 3.

● float(): Converts a value to a float.

Example: float(5) results in 5.0.

● str(): Converts a value to a string.

Example: str(10) results in '10'.

● bool(): Converts a value to a boolean. Most

values translate to True, while some (like 0 and

empty structures) translate to False. Example:


bool(0) results in False.

● Type Checking

● Python offers the type() function to ascertain the data

type of a value.

● Example: type(3.14) returns <class 'float'>.

3. The None Data Type

● Description: None is a special data type in Python. It is used

to represent the absence of a value or a default parameter.

● It is the equivalent of "null" in some other languages.

● A function that does not explicitly return a value, by

default returns None.

● Usage:

● Often used to initialise variables.

● To check for None, one should use the is keyword.

Example: if variable is None:

1.4 Operators

Operators are fundamental building blocks in programming


languages like Python. They allow developers to perform

operations on variables and values, manipulate data, and make

decisions based on conditions. Let's delve into the various types of

operators in Python :

1. Arithmetic Operators:

● These operators are used to perform arithmetic

calculations.

● +: Addition — Adds values on either side of the

operator. E.g., a + b.

● -: Subtraction — Subtracts right-hand operand

from left-hand operand. E.g., a - b.

● *: Multiplication — Multiplies values on either

side. E.g., a * b.

● /: Division — Divides left-hand operand by right-

hand operand. E.g., a / b.

● //: Floor Division — Divides and returns the

largest whole number. E.g., 7 // 2 results in 3.

● %: Modulus — Returns the remainder of the


division. E.g., 7 % 2 results in 1.

● **: Exponentiation — Raises the left-hand

operand to the power of the right-hand operand.

E.g., a ** b.

2. Comparison Operators:

● Used for comparing two values.

● ==: Equal to — Checks if two operands are equal.

If so, returns True.

● !=: Not equal to — Checks if two operands are

unequal. If so, returns True.

● <: Less than — Checks if left-hand operand is less

than right-hand operand.

● >: Greater than — Similar to the above, but

checks for greater than.

● <=: Less than or equal to.

● >=: Greater than or equal to.

3. Logical Operators:

● Used to combine conditional statements.


● and: Logical AND — Returns True if both

statements are true.

● or: Logical OR — Returns True if at least one

statement is true.

● not: Logical NOT — Returns True if the statement

is false.

4. Assignment Operators:

● Used to assign values to variables.

● =: Assigns value from right operand to left

operand. E.g., a = b.

● +=: Adds right operand to left operand and

assigns the result to left operand. E.g., a += b is

equivalent to a = a + b.

● -=: Subtracts right from left and assigns. Similar to

above.

● Similarly, other compound assignment operators

like *=, /=, //=, etc., work in a similar manner.

5. Bitwise Operators:
● Used for performing operations on bits.

● &: Bitwise AND.

● |: Bitwise OR.

● ^: Bitwise XOR (Exclusive OR).

● ~: Bitwise NOT.

● <<: Left Shift — Shifts left operands' value by the

number of bits specified by the right operand.

● >>: Right Shift — Operates similarly but shifts to the

right.

6. Membership and Identity Operators:

● They test for membership in a sequence (like strings,

lists, or tuples) and the identity of an object.

● in: Checks if a value is present in a sequence.

● not in: Checks if a value is not present in a

sequence.

● is: Checks if two variables point to the same

memory location.

● is not: Checks if two variables don't point to the


same memory location.

1.5 Data Structures

In Python, data structures allow us to organise and store multiple

pieces of data in a cohesive and structured manner. Let's delve

into the specifics:

a. Lists

● A list is a collection which is ordered and mutable (can be

changed).

● Lists are written with square brackets, [].

fruits = ["apple", "banana", "cherry"]

● Key properties:

● Ordered: The items have a defined order and that

order will not change.

● Mutable: We can change, add, and remove items after

the list has been created.

● Allows duplicates: Lists can have items with the same

value.
b. Tuples

● A tuple is similar to a list in that it can contain multiple items.

However, unlike lists, tuples are immutable.

● Tuples are written with round brackets, ().

colours = ("red", "green", "blue")

● Key properties:

● Ordered: Just like lists, the order of items is preserved.

● Immutable: Once a tuple is created, you cannot

change its contents.

● Allows duplicates.

c. Sets

● A set is an unordered collection of items where every item is

unique (no duplicates).

● Sets are written with curly brackets, {}.

unique_numbers = {1, 2, 3, 4, 4, 5}

● Key properties:

● Unordered: Sets do not record element position.

● No duplicates: Sets cannot have two items with the


same value.

● Mutable: You can add and remove items from the set.

d. Dictionary

● A dictionary is an unordered collection of data in a key:value

pair form.

● Here's how you might define a dictionary:

student = { "name": "Rohan", "age": 20, "course": "BCA" }

● Key properties:

● Unordered: The items do not have a defined order.

● Mutable: You can change, add, and remove items after

the dictionary has been created.

● No duplicate keys: Keys must be unique, though values

can repeat.

1.6 Loops

Control flow is fundamental to programming. It determines the

order in which code is executed, allowing for more sophisticated

behaviours than just executing one instruction after another in


sequence. One of the core components of control flow in

programming is the concept of loops. Loops allow instructions to

be repeated multiple times, either for a fixed number of iterations

or until a certain condition is met.

The for Loop: Iterating over Sequences

The for loop in Python is used to iterate over sequences (like lists,

tuples, strings, or ranges). With this loop, one can execute a set of

statements for each item in a sequence.

● Basic Syntax:

for variable in sequence: # code to execute for each item

● Examples:

● Iterating over a list:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

● Iterating over a string:

for char in "apple": print(char)

The while Loop: Conditional Looping

Unlike the for loop which operates over a sequence, the while

loop keeps executing its body as long as its condition remains true.
● Basic Syntax:

while condition: # code to execute while condition is true

● Example:

count = 0 while count < 5: print(count) count += 1

Remember, it's crucial to ensure that the condition becomes false

at some point; otherwise, the loop might run indefinitely, causing

the program to hang or crash.

Loop Control Statements: break, continue, else

These statements provide added control over the flow of loops:

● break: Used to exit the loop prematurely.

● Example:

for num in range(10): if num == 5: break print(num)

● continue: Skips the rest of the loop's current iteration and

jumps to the next iteration.

● Example:

for num in range(5): if num == 2: continue print(num)

● else: This block of code is executed once the loop is finished

(i.e., after for has finished iterating or when the while


condition becomes false). Note: The else block won’t be

executed if the loop is terminated by a break statement.

● Example:

for num in range(5): print(num) else: print("Loop finished!")

1.7 Functions

Functions in programming are similar to functions in mathematics.

They are a sequence of statements that take certain inputs,

process them, and produce outputs. Functions offer several

advantages:

● Modularity: They allow you to break down a complex

program into smaller, manageable pieces.

● Reusability: Once written, a function can be called multiple

times from different parts of the program, thereby avoiding

redundancy.

● Maintainability: If a bug arises or an update is needed, you

only need to modify the function in one place rather than

multiple locations in your code.


Defining and Calling Functions:

In Python, functions are defined using the def keyword followed

by the function name and parentheses.

def greet(): print("Hello, World!")

To call a function, you use its name followed by parentheses:

greet() # This will output "Hello, World!"

Arguments and Parameters: Positional, Default, Keyword:

Functions can take inputs known as parameters. When we call the

function and provide values, they're termed as arguments.

● Positional Arguments: These are the arguments passed to a

function in the proper position order. The number of

positional arguments needs to match the number of

parameters.

def add(x, y): return x + y add(3, 4) # Here, 3 is the argument for x

and 4 is for y.

● Default Arguments: These allow you to assign a default value

to parameters.

def greet(name="User"): print(f"Hello, {name}!") greet() # This will


output "Hello, User!" greet("Ali") # This will output "Hello, Ali!"

● Keyword Arguments: These allow you to specify arguments

by the parameter name.

add(y=5, x=3) # This will also return 8

Return Values and the return Statement:

Functions can return values using the return statement. When a

function encounters the return statement, it exits the function

and returns the specified value.

def square(n): return n * n result = square(5) # result will hold the

value 25

If no return statement is present, or there's no value with return,

the function will return None.

Scope and Lifetime of Variables:

In Python, variables have two primary scopes:

● Local Scope: Variables defined inside a function have a local

scope and can't be accessed outside that function.

● Global Scope: Variables defined outside any function have a

global scope and can be accessed from within any function,


provided they're not overshadowed by a local variable.

The lifetime of a variable refers to the period for which the

variable exists in memory. Local variables are destroyed once the

function execution is completed, whereas global variables remain

in memory for the duration of the program.

Anonymous Functions: Lambda Expressions:

Python allows the creation of small anonymous functions using

the lambda keyword. They can have multiple inputs but only one

expression.

double = lambda x: x * 2 print(double(5)) # This will output 10

They're useful when you need a short-lived, simple function and

don't want to formally define it using def.

Built-in Functions in Python:

Python provides a set of built-in functions that are always

available. Some of these are:

● print(): Outputs the specified message or value.

● len(): Returns the length of an object.

● type(): Returns the type of an object.


● int(), float(), str(): Convert values to int, float, or string types

respectively.

● list(), tuple(): Convert values to list or tuple.

These are just a few examples; Python has a rich set of built-in

functions that cater to various programming needs.

1.8 Summary

❖ Python is a high-level, interpreted programming language

known for its simplicity and readability, emphasising clear,

human-readable code.

❖ An open-source interactive web application that allows for

the creation and sharing of documents containing live code,

equations, visualisations, and narrative text.

❖ Classification of data items based on the kind of value they

hold, like integers, floats, strings, and booleans, which

dictate the operations possible on them and their storage

method.
❖ Symbols that perform arithmetic, comparison, logical,

assignment, bitwise, membership, or identity operations on

values and variables in Python.

❖ In-built organisational systems in Python, such as lists

(ordered collections), tuples (immutable sequences), sets

(unordered collections of unique items), and dictionaries

(key-value pairs), designed to store, retrieve, and manage

data efficiently.

❖ Structures in Python that allow code to be executed

repeatedly based on a condition or an iterable, with

common types being the for and while loops.

❖ Reusable blocks of code in Python that perform a specific

task, can accept input parameters, and return an output.

1.9Keywords

● def: The def keyword is used to declare or define a function

in Python. It signals the beginning of a function definition,


followed by the function name and parentheses containing

any parameters.

● lambda: The lambda keyword allows the creation of

anonymous functions (i.e., functions that are not bound to a

name). These functions can have any number of arguments

but only one expression.

● in: The in keyword is primarily used to check if a value exists

within a sequence (like a list, tuple, or string). It's also used

in for loops to iterate over a sequence.

● break: The break keyword is used to exit or "break out of"

the loop in which it is placed. Once a break statement is

encountered, the loop terminates and the program

continues with the next line of code outside the loop.

● return: The return keyword is used in functions to send a

result back to the caller. A function that doesn't have a

return statement implicitly returns None.

● dict: The dict keyword is actually a built-in function that


creates dictionaries. Dictionaries in Python are collections of

key-value pairs where each key must be unique.

1.10 Self-Assessment Questions

1. How can you differentiate between a list and a tuple in

Python?

2. What is the primary advantage of using Jupyter Notebook

for Python programming over traditional IDEs?

3. Which of the following operators is used for exponentiation

in Python: ^, **, or %?

4. What is the purpose of the break statement in loops?

5. How can you access the values of a dictionary using its keys?

1.11 Case Study

Title: Automation at 'Metro Retail' using Python

Introduction:

Metro Retail', a medium-sized retail chain, struggled with

managing its vast inventory across multiple stores in the city.


Their inventory system was outdated, and the tracking was largely

manual, which often resulted in errors, overstocking, or stockouts.

The management recognized the urgent need for an efficient

system but had budget constraints for an off-the-shelf solution.

Background:

Enter Maya, a final year BCA student with a flair for Python

programming. As part of her internship at 'Metro Retail', she

proposed developing a custom inventory management system

using Python. Python, being an open-source language, would keep

costs down, and its vast libraries would speed up the

development process.

Maya used the pandas library to handle, analyse, and visualise the

inventory data. She integrated the new system with barcode

scanners using the pyzbar library, allowing real-time tracking of

products. For the GUI, she employed tkinter, making the system

user-friendly even for non-tech staff. One of the features Maya

developed was an automatic alert system that notified store

managers when stock levels of a product went below a set


threshold, using the smtplib library to send email alerts.

Once implemented, the inventory discrepancies dropped by 80%.

'Metro Retail' could now make data-driven decisions regarding

restocking, clearance sales, and procurement. Maya's Python-

based solution not only addressed the immediate pain points but

also equipped the retail chain for future scalability.

Questions:

1. What were the primary challenges faced by 'Metro Retail'

regarding its inventory management?

2. How did the use of Python and its libraries assist in creating

a cost-effective solution for 'Metro Retail'?

3. In what significant ways did the new system improve 'Metro

Retail's' operations post-implementation?

1.12 References

1. "Python Crash Course" by Eric Matthes

2. "Automate the Boring Stuff with Python" by Al Sweigart

3. "Fluent Python" by Luciano Ramalho


4. "Learning Python" by Mark Lutz

5. "Effective Python: 90 Specific Ways to Write Better Python"

by Brett Slatkin

You might also like