0% found this document useful (0 votes)
1 views71 pages

Python Programming With Business

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

Python Programming With Business

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

PYTHON PROGRAMMING IN BUSINESS -THEORY

UNIT-I

Computer Hardware – Software – Introduction about Python - Characteristics of Python -


Python's features - Literals - Variables and Identifiers - Operators - Data types.

UNIT-II

Boolean Expressions - Selection Control – if, if-else, if-elif- else- Iterative Control - While
Statement, do while and for loop - break, continue, pass. Strings: string slices,
immutability, string functions and methods, string module;

UNIT-III

Program Routines- Defining Functions- Calling Value-Returning Functions- Calling Non-


ValueReturning Functions- Parameter Passing - Keyword Arguments in Python - Default
Arguments in PythonVariable Scope. Recursion: Recursive Functions

UNIT-IV

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations
and methods; advanced list processing – list comprehension

UNIT-V

Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages;

TEXT BOOK:

1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd
Edition,

O’Reilly Publishers, 2016

2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and

Programming”, 1st Edition, BCS Learning & Development Limited, 2017

3. Charles Dierbach, “Introduction to Computer Science using Python – A computational


Problemsolving Focus”, Wiley India Edition, 2015.
UNIT-I

Computer Hardware – Software – Introduction about Python - Characteristics of Python -


Python's features - Literals - Variables and Identifiers - Operators - Data types.

SCRIPT MODE(save as file) , INTERACTIVE MODE

Computer hardware includes the physical parts of a computer, such as a case, central
processing unit (CPU), random access memory (RAM), monitor, and mouse which
processes the input according to the set of instructions provided to it by the user and gives
the desired output

Software is a set of programs, which is designed to perform a well-defined function. A


program is a sequence of instructions written to solve a particular problem.

There are two types of software −

 System Software

 Application Software

System Software

The system software is a collection of programs designed to operate, control, and extend
the processing capabilities of the computer itself. System software is generally prepared by
the computer manufacturers. These software products comprise of programs written in
low-level languages, which interact with the hardware at a very basic level. System
software serves as the interface between the hardware and the end users.

Some examples of system software are Operating System, Compilers, Interpreter,


Assemblers, etc.

Application Software

Application software products are designed to satisfy a particular need of a particular


environment. All software applications prepared in the computer lab can come under the
category of Application software.

Application software may consist of a single program, such as Microsoft's notepad for
writing and editing a simple text. It may also consist of a collection of programs, often
called a software package, which work together to accomplish a task, such as a spreadsheet
package.

Examples of Application software are the following −


 Payroll Software

 Student Record Software

 Inventory Management Software

 Income Tax Software

 Railways Reservation Software

 Microsoft Office Suite Software

 Microsoft Word

 Microsoft Excel

 Microsoft PowerPoint

Characteristics of Python

1. For learning it is easy and to use: Python is easy to learn and use, even for
beginners. The syntax is plain and straightforward, almost like writing in English.

2. Object-oriented: Python is an object-oriented programming language that has


highlights such as code reusability and measured quality. It supports highlights
such as abstraction, encapsulation, inheritance and polymorphism.

3. Interpreted: Python is an interpreted language, which implies line by line the code
is executed. This makes the process faster and more efficient as it eliminates the
need for a compilation step, and if some error occurs, it will not wait for the whole
code to compile. It will throw an error at that particular line itself.

4. Cross-platform: Python has the capability to run on multiple platforms, including


Windows, Mac, Linux, and Unix. This makes it highly portable, allowing
developers to write code on one platform and run it on another.

5. Extensive standard library: Python has an extensive standard library that


contains modules for many everyday tasks, e.g. file input/output, regular
expressions and networks. This reduces the code developer’s time and effort.

6. Dynamically typed: Python is dynamically typed, meaning variable types are


determined at runtime. We don't have to tell the data type of the variable explicitly.
This makes the language more flexible and adaptable to changing requirements.
7. High-level language: Python is an interpreted, object-oriented, high-level
programming language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding, make it very
attractive for Rapid Application Development.

8. Free and open source: The Python programming language is free and open
source, which suggests it can be utilized on any working framework for
complimentary. You'll be able download Python and the related libraries and
documentation from the official Python site.

9. Extensive feature: The Python programming language can be extended and is


more versatile than many other programming languages. Its adaptability to various
functionalities makes Python a universal programming language in the software
development industry. Code written in different programming languages can be
executed. Python gains new capabilities and functionality by integrating code from
other programming languages.

10. Database support: Python provides robust support for working with databases
through its standard library and third-party packages such as SQLite3, MySQL
Connector, PostgreSQL, SQLAlchemy, and MongoDB. Python also supports
Object-Relational Mapping (ORM) frameworks such as Django ORM and
SQLAlchemy, which provide an abstraction layer on top of databases, making it
easier to work with data in object-oriented Python code.

11. GUI Programming Support: Python provides several GUI programming


frameworks and libraries, including Tkinter, PyQt, and wxPython where. Tkinter is
a standard GUI toolkit included in Python. PyQt delivers a powerful and flexible
toolkit for creating cross-platform desktop GUI applications, and wxPython
provides a native look and feels for desktop GUI applications on Windows,
macOS, and Linux.

12. Python's simplicity, versatility, and readability make it popular for developers
across many industries and applications

Applications of Python

1. Web development: Django, Flask, and Pyramid are popular web frameworks in
Python, used for building applications ranging from small websites to large
enterprise applications.

2. Data science and analytics: Python is a highly demanded language in data science
and machine learning, with popular libraries like NumPy, Pandas, Matplotlib, and
Scikit-learn for data analysis, visualization, and ML.
3. Scientific computing: Python is widely used in scientific computing, with modules
for numerical calculations, optimization, linear algebra, interpolation, and special
functions. Libraries like SciPy and NumPy provide a powerful way to perform
scientific computations.

4. Automation and scripting: Python is extensively used for automation tasks, such
as scripting, testing, and deployment, providing an efficient way to automate
repetitive tasks and integrate systems and services.

5. Desktop GUI applications: Python provides several GUI toolkits like Tkinter,
PyQt, and wxPython, allowing developers to create desktop applications with a
native look and feel.

6. Game development: Python can be used to develop games with libraries like
Pygame, which provides graphics, sound, and input handling tools for game
development.

7. Networking: Python has robust networking libraries, such as sockets and


Requests, which make it easy to create network-based applications, such as web
scrapers and web crawlers(crawling finds websites, and scraping extracts
information).

8. Education: Python's simplicity and ease of use make it a popular choice for
introductory programming courses in academia and online.

9. DevOps: Python is used extensively in the DevOps community for tasks such as
automation, infrastructure management, and deployment. Tools such as Ansible
and SaltStack are written in Python.

10. Finance: Python is widely used for quantitative analysis, algorithmic trading, and
risk management. Banks such as JPMorgan and Goldman Sachs use Python for
financial modeling and analysis.

11. Healthcare: Python is used for medical imaging, data analysis, and research. The
National Institutes of Health (NIH) uses Python for genomic data analysis.

Literals:

Python Literals

Python Literals can be defined as data that is given in a variable or constant.

Python supports the following literals:

1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well as double quotes to create a string.

Ex: "Aman" , '12345'

Types of Strings:

There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.

Example:

text1='hello'

b) Multi-line String - A piece of text that is written in multiple lines is known as


multiple lines string.

There are two ways to create multiline strings:

1) Adding black slash at the end of each line.

Example:

text1='hello\

user'

print(text1)

'hellouser'

2) Using triple quotation marks:-

Example:

str2='''''welcome

to

SSSIT'''

print str2

Output:

welcome
to

SSSIT

Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.

Int(signed Long(long float(floating Complex(complex)


integers) integers) point)

Numbers( can be Integers of Real numbers with In the form of a+bj where a
both positive and unlimited size both integer and forms the real part and b forms
negative) with no followed by fractional part eg: - the imaginary part of the
fractional [Link]: lowercase or 26.2 complex number. eg: 3.14j
100 uppercase L eg:
87032845L
Example - Numeric Literals

x = 0b10100 #Binary Literals

y = 100 #Decimal Literal

z = 0o215 #Octal Literal

u = 0x12d #Hexadecimal Literal

#Float Literal

float_1 = 100.5

float_2 = 1.5e2

#Complex Literal

a = 5+3.14j

print(x, y, z, u)

print(float_1, float_2)
print(a, [Link], [Link])

Output:

20 100 141 301

100.5 150.0

(5+3.14j) 3.14 5.0

Boolean literals:

A Boolean literal can have any of the two values: True or False.

Example - Boolean Literals

x = (1 == True)

y = (2 == 2)

z = (3 == True)

a = True + 10

b = False + 10

print("x is", x)

print("y is", y)

print("z is", z)

print("a:", a)

print("b:", b)

Output:

x is True

y is False

z is False

a: 11

b: 10
Special literals.

Python contains one special literal i.e., None.

The None keyword is used to define a null value, or no value at all.

None is not the same as 0, False, or an empty string. None is a data type

Example - Special Literals

val1=10

val2=None

print(val1)

print(val2)

Output:

10

None

Literal Collections.

Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.

List:

o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within
square brackets([]). We can store different types of data in a List.

Example - List literals

list=['John',678,20.4,'Peter']

list1=[456,'Andrew']

print(list)

print(list + list1)
Output:

['John', 678, 20.4, 'Peter']


['John', 678, 20.4, 'Peter', 456, 'Andrew']

Dictionary:

o Python dictionary stores the data in the key-value pair.


o It is enclosed by curly-braces {} and each pair is separated by the commas(,).

Example

dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}


print(dict)

Output:

{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}

Tuple:

o Python tuple is a collection of different data-type. It is immutable which


means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is separated by the
comma(,).

Example

tup = (10,20,"Dev",[2,3,4])
print(tup)

Output:

(10, 20, 'Dev', [2, 3, 4])

Example: - Set Literals

set = {'apple','grapes','guava','papaya'}
print(set)
Output:

{'guava', 'apple', 'papaya', 'grapes'}

Variables and Identifiers

A variable is the name given to a memory location. A value-holding Python variable is


also known as an identifier.

Since Python is an infer language that is smart enough to determine the type of a variable,
we do not need to specify its type in Python.

Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits.

The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.

Identifier Naming

Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might be
a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the
identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the
language.
o Names of identifiers are case-sensitive; for instance, my name, and
MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python doesn't tie us to pronounce a variable prior to involving it in the application. It


permits us to make a variable at the necessary time.
In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.

The equal (=) operator is utilized to assign worth to a variable.

Python Variable Types


There are two types of variables in Python - Local variable and Global variable.
Let's understand the following variables.

Local Variable
The variables that are declared within the function and have scope within the
function are known as local variables.

Ex:

# Declaring a function

def add():

# Defining local variables. They has scope only within a function

a = 20

b = 30

c=a+b

print("The sum is:", c)

# Calling a function

add()

Output:

The sum is: 50


We get the error that follows if we attempt to use them outside of the function.

add()

# Accessing local variable outside the function

print(a)

Output:

The sum is: 50


print(a)
NameError: name 'a' is not defined

Global Variables
Global variables can be utilized all through the program, and its extension is in the
whole program. Global variables can be used inside or outside the function.

By default, a variable declared outside of the function serves as the global


variable.

Ex:

# Declare a variable and initialize it

x = 101

# Global variable in function

def mainFunction():

# printing a global variable

global x

print(x)

# modifying a global variable

x = 'Welcome To Javatpoint'

print(x)
mainFunction()

print(x)

Output:

101

Welcome To Javatpoint

Welcome To Javatpoint

In the above code, we declare a global variable x and give out a value to it. We
then created a function and used the global keyword to access the declared
variable within the function. We can now alter its value. After that, we gave the
variable x a new string value and then called the function and printed x, which
displayed the new value.

Python Operators

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Arithmetic Operators

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b
= 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a =


(Multiplication) 20, b = 4 => a * b = 80

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is


an exponent operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.

Comparison operator
==,!=,<=,>=,>,<

Assignment Operators
=,+=,-=,*=,%=

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to
a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to
a.

Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The
examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^),
negation (~), Left shift (<<), and Right shift (>>).
example,

if a = 7

b=6

then, binary (a) = 0111

binary (b) = 0110

hence, a & b = 110

a | b = 0111

a ^ b = 0100

~ a = 1000

Let, Binary of x = 0101

Binary of y = 1000

Bitwise OR = 1101

Bitwise XOR = 1101

Operator Description

& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.

^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.

<< (left shift) The number of bits in the right operand is multiplied by the leftward
shift of the value of the left operand.

>> (right The left operand is moved right by the number of bits present in the
shift) right operand.

Logical Operators
And,or,not

Operator Precedence

Operator Description

** Overall other operators employed in the expression, the


exponent operator is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and


the multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to,
greater than, greater then equal to).

<> == != Equality operators.


= %= /= //= -= Assignment operators
+=
*= **=

Data Types

The following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
PYTHON PROGRAMMING THEORY

UNIT-I

Computer Hardware – Software – Introduction about Python - Characteristics of Python -


Python's features - Literals - Variables and Identifiers - Operators - Data types.

UNIT-II

Boolean Expressions - Selection Control – if, if-else, if-elif- else- Iterative Control - While
Statement, do while and for loop - break, continue, pass. Strings: string slices, immutability,
string functions and methods, string module;

UNIT-III

Program Routines- Defining Functions- Calling Value-Returning Functions- Calling Non-


ValueReturning Functions- Parameter Passing - Keyword Arguments in Python - Default
Arguments in PythonVariable Scope. Recursion: Recursive Functions

UNIT-IV

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing – list comprehension

UNIT-V

Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages;

TEXT BOOK:

1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition,

O’Reilly Publishers, 2016

2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and

Programming”, 1st Edition, BCS Learning & Development Limited, 2017

3. Charles Dierbach, “Introduction to Computer Science using Python – A computational


Problemsolving Focus”, Wiley India Edition, 2015.
Unit II

A Boolean expression is an expression that evaluates to produce a result which is a Boolean value. For
example, the operator == tests if two values are equal. It produces a Boolean value.
Ex:
print("Is five equal 5 , to the result of 3 + 2?")
print(5 == (3 + 2))
print("Does five equal six?")
print(5 == 6)
output:

Is five equal 5 to the result of 3 + 2?


True
Does five equal six?
False

Selection Control – if, if-else, if-elif- else

If-Else statements in Python are part of conditional statements, which decide the control of code.

Types of Control Flow in Python


1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder
Python if statement
The if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, python uses indentation to identify a block.
Example of Python if Statement
# python program to illustrate If statement

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if

Python If-Else Statement


The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But if we want to do something else if
the condition is false, we can use the else statement with the if statement to execute a
block of code when the if condition is false.

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Nested-If Statement in Python


A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
Ex:

# python program to illustrate nested If statement


i = 10
if (i == 10):
if (i < 15):
print("i is smaller than 15")
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
Python if-elif-else Ladder
Here, a user can decide among multiple options. The if statements are executed from
the top down.
As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final “else” statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flowchart of Python if-elif-else ladder
Let’s look at the flow of control in if-elif-else ladder:

Example of Python if-elif-else ladder


# Python program to illustrate if-elif-else ladder
#!/usr/bin/python

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Output:
i is 20

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement

# Python program to illustrate short hand if


i = 10
if i < 15: print("i is less than 15")

Output:
i is less than 15

Short Hand if-else statement


This can be used to write the if-else statements in a single line where only one
statement is needed in both the if and else blocks.
Ex:
In the given example, we are printing True if the number is less than 15, or else it will
print False.

# Python program to illustrate short hand if-else


i = 10
print(True) if i < 15 else print(False)

Output:
True
Iterative control statements:

Python While Loop

Until a specified criterion is true, a block of statements will be continuously executed in a Python
while loop.

Syntax:

while expression:
statement(s)
# prints Hello Geek 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Geek")

Output:

Hello Geek
Hello Geek
Hello Geek

Python For loop:

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).

# Iterating over a list


print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Output:

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345
Python Loop Control Statements

Loop control statements change execution from their normal sequence

Python Continue
It returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)

Output:

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Python Break
It brings control out of the loop.
for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)

Output:
Current Letter : g
Python Pass
We use pass statements to write empty loops.
# An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)

Output:
Last Letter : s

Strings:

In Python, a string is a sequence of characters. For example, "hello" is a string


containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

We use single quotes or double quotes to represent a string in Python. For


example,

# create string type variables

name = "Python"
print(name)

message = ‘I love Python.’


print(message)

Output

Python
I love Python.
Access String Characters in Python
We can access the characters in a string in three ways.

 Indexing: One way is to treat strings as a list and use index values. For example,
 greet = 'hello'

 # access 1st index element
 print(greet[1]) # "e"

 Negative Indexing: Similar to a list, Python allows negative indexing for its strings.
For example,
 greet = 'hello'

 # access 4th last element
 print(greet[-4]) # "e"

 Slicing: Access a range of characters in a string by using the slicing operator colon :
For example,
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"

Python Strings are Immutable


In Python, strings are immutable. That means the characters of a string cannot be
changed. For example,

message = 'Hola Amigos'


message[0] = 'H'
print(message)

Output

TypeError: 'str' object does not support item assignment

But, we can assign the variable name to a new string. For example,
message = 'Hola Amigos'

# assign new string to message variable


message = 'Hello Friends'

print(message); # prints "Hello Friends

Python Multiline String


We can also create a multiline string in Python. For this, we use triple double
quotes """ or triple single quotes '''. For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)

Output

Never gonna give you up


Never gonna let you down

Python String Operations


Many operations can be performed with strings, which makes it one of the most
used data types in Python.
1. Compare Two Strings

We use the == operator to compare two strings. If two strings are equal, the operator
returns True . Otherwise, it returns False . For example,
str1 = "Hello, world!"
str2 = "I love Swift."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Run Code

Output

False
True

In the above example,

1. str1 and str2 are not equal. Hence, the result is False .

2. str1 and str3 are equal. Hence, the result is True .

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


Run Code

In the above example, we have used the + operator to join two strings: greet and name .

Iterate Through a Python String


We can iterate through a string using a for loop. For example,
greet = 'Hello'
# iterating through greet string
for letter in greet:
print(letter)
Run Code

Output

H
e
l
l
o

Python String Length


In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5
Run Code

String Membership Test


We can test if a substring exists within a string or not, using the keyword in .

MyString1 = "I am from SDNB"

if "SDNB" in MyString1:
print("Yes! it is present in the string")
else:
print("No! it is not present")

Functions and Methods of Python String


Besides those mentioned above, there are various string methods present in Python.
Here are some of those methods:
Methods Description

upper() Converts the string to uppercase

lower() Converts the string to lowercase

replace() Replaces substring inside

find() Returns the index of the first occurrence of substring

rstrip() Removes trailing characters

startswith() Checks if string starts with the specified string

index() Returns index of substring

Escape Sequences in Python


The escape sequence is used to escape some of the characters present inside a string.

Suppose we need to include both a double quote and a single quote inside a string,

example = "He said, "What's there?""

print(example) # throws error


Run Code

Since strings are represented by single or double quotes, the compiler will treat "He

said, " as a string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \ in Python.
# escape double quotes
example = "He said, \"What's there?\""

# escape single quotes


example = 'He said, "What\'s there?"'

print(example)

# Output: He said, "What's there?"


Run Code
Here is a list of all the escape sequences supported by Python.

Escape
Description
Sequence

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell

\b ASCII Backspace

ASCII Formfeed(usedto indicate to


\f a printer that it should start a
new page.)

\n ASCII Linefeed

ASCII Carriage Return


([Link]
\r
between-newline-and-carriage-return-in-
python/)

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH


Python String Module

Python String module contains some constants, utility function, and classes for string manipulation.

It’s a built-in module and we have to import it before using any of its constants and classes.

The string module is a part of Python's standard library and provides several helpful utilities for
working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation)
to useful functions for string formatting and manipulation

String Module Constants


import string

# string module constants


print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
print([Link])
print([Link]) # ' \t\n\r\x0b\x0c'
print([Link])
s = "hello friend!"
print([Link](s))

Output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF

!"#$%&'()*+,-./:;?@[\]^_`{|}~
Hello Friend!
PYTHON PROGRAMMING THEORY

UNIT-III

Functions- Types of Functions in Python- Python Function with Parameters- Python Function Arguments-
Types of Python Function Arguments - Recursive Functions in Python- Scope of the variable

Program routines(Functions)

A function is Python's version of a program routine.


A function is a block of code that performs a specific task, instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Some Benefits of Using Functions

 Increase Code Readability

 Increase Code Reusability

Python Function Declaration

The syntax to declare a function is:

def function_name(parameter)

Types of Functions in Python:

There are mainly two types of functions in Python.

 Built-in library function: These are Standard functions in Python that are available to use.

 User-defined function: We can create our own functions based on our requirements.

User-defined function

We can define a function in Python, using the def keyword.

# A simple Python function

def fun():
print("Welcome to GFG")

Calling a Python Function


After creating a function in Python we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
# A simple Python function
def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()
Output:
Welcome to GFG
Python Function with Parameters :
Parameters: These are the named variables listed in the function definition.
1. Calling function by values :

def add(a:int ,b:int): # 'a' and 'b' are parameters

"""Add two numbers"""

res = a+b

return res

# Driver code

ans = add(5, 6)

print(f"The addition of two numbers {ans}.")

Output:

The addition of two numbers 11.

2. Calling function by parameters:

Defining and calling a function with parameters


def add(num1: int, num2: int):
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Output:
The addition of 5 and 15 results 20.
Python Function Arguments:

These are the actual values passed to the function when it is called

Arguments are the values passed inside the parenthesis of the function. A function can have any number of
arguments separated by a comma.

In this example, we will create a simple function in Python to check whether the number passed as an
argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2) # 2 is argument
evenOdd(3)

Output:
even
odd

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the function call. In Python,
we have the following 4 types of function arguments.

 Default argument

 Keyword arguments (named arguments)

 Positional arguments

 Arbitrary argument

Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the function
call for that argument.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)
Output:
x: 10
y: 50

Keyword Arguments

The idea is to allow the caller to specify the argument name with values so that the caller does not need to
remember the order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')

Output:
Geeks Practice
Geeks Practice

Positional Arguments

We used the Position argument during the function call so that the first argument (or value) is assigned to
name and the second argument (or value) is assigned to age. By changing the position, or if you forget the
order of the positions, the values can be used in the wrong places,

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to
a function using special symbols. There are two special symbols:

1. *args in Python (Non-Keyword Arguments)


2. **kwargs in Python (Keyword Arguments)

Example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:
Hello
Welcome
to
GeeksforGeeks

Example 2: Variable length keyword arguments

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in [Link]():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

Output:
first == Geeks
mid == for
last == Geeks

Recursive Functions in Python


Recursion in Python refers to when a function calls itself.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output
24

Note: the end statement for this function is when n is equal to 0

Return Statement in Python Function

The function return statement is used to exit from a function and go back to the function caller and return
the specified value or data item to the caller. The syntax for the return statement is:

return [expression_list]

The return statement can consist of a variable, an expression, or a constant which is returned at the end of
the function execution. If none of the above is present with the return statement a None object is returned.

Ex:

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output:
4
16

Pass by Reference and Pass by Value

def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]

Scope of the variable:

A variable is only available from inside the region it is created. This is called scope.

Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that
function.

ExampleGet your own Python Server


A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Output:

300

Function Inside Function


As explained in the example above, the variable x is not available outside the function, but it is available for any
function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

# without this above line the function myinnerfunc() will not be #invoked ,output will not get print.

myfunc()

Output:

300

Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope.

Global variables are available from within any scope, global and local.

Example
A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Output:

300

300

Naming Variables

If you operate with the same variable name inside and outside of a function, Python will treat them as two
separate variables, one available in the global scope (outside the function) and one available in the local
scope (inside the function):

Example

The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)

output:

200

300
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.

The global keyword makes the variable global.

Example

A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Output:

300

To change the value of a global variable inside a function, refer to the variable by using
the global keyword:

x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

Output:

200
Python – Unit IV

1. List Values in Python


🔹 Definition

 A list is an ordered collection of values.


 Each element in the list is identified by a numeric index, starting from 0.
 The values inside a list are called elements or items.
 Unlike strings (which are sequences of characters), a list can contain different
data types like integers, floats, strings, and even other lists.

Example:

numbers = [10, 20, 30, 40] # List of integers


animals = ['dog', 'cat', 'cow'] # List of strings
mixed = ['apple', 3.14, 7, [1, 2, 3]] # List with different types
(nested)

🔹 Creating a List

 Lists are created by enclosing elements inside square brackets [ ] separated by


commas.
 Examples:

list1 = [10, 20, 30] # integers


list2 = ['red', 'green', 'blue'] # strings
list3 = [10, 'apple', 3.14] # mixed types
list4 = [] # empty list

✔️ Empty list: [] is useful when you want to create a list and add elements later.

🔹 Accessing Values in a List

 Elements are accessed using index positions.


 Indexing starts from 0.
 Negative indices count from the end of the list (-1 is the last element).

Example:

fruits = ['Apple', 'Banana', 'Orange']


print(fruits[0]) # Output: Apple
print(fruits[2]) # Output: Orange
print(fruits[-1]) # Output: Orange (last element)

🔹 Deleting Elements from a List

 Use the del statement to remove elements by index.


 Entire list can also be deleted.

Example:

a = ['one', 'two', 'three']


del a[1] # deletes element at index 1
print(a) # Output: ['one', 'three']

del a # deletes the whole list

🔹 Updating List Elements

 Lists are mutable, meaning values can be changed.


 We can update a single element or multiple elements using indexing or slicing.

Example 1 – Updating Single Element:

t = ['a', 'b', 'c', 'd']


t[0] = 'x'
print(t) # Output: ['x', 'b', 'c', 'd']

Example 2 – Updating Multiple Elements with Slice:

t = ['a', 'b', 'c', 'd', 'e', 'f']


t[1:3] = ['x', 'y']
print(t) # Output: ['a', 'x', 'y', 'd', 'e', 'f']

🔹 Key Points to Remember

 Lists allow heterogeneous data types.


 Lists are mutable (can be changed).
 Lists support indexing, slicing, and looping.
 Lists can be nested (a list inside another list).
 An empty list is valid and often used.
2. Basic List Operations & Slices
🔹 List Operations

Python provides several built-in operations on lists.

1. Concatenation (+)
o Joins two or more lists into a single list.
2. a = [1, 2, 3]
3. b = [4, 5]
4. c = a + b
5. print(c) # Output: [1, 2, 3, 4, 5]
6. Repetition (*)
o Repeats the list a given number of times.
7. x = [1] * 4
8. print(x) # Output: [1, 1, 1, 1]
9.
10. y = [1, 2, 3] * 3
11. print(y) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
12. Membership (in)
o Checks if an element is present in the list.
13. nums = [10, 20, 30]
14. print(20 in nums) # True
15. print(50 in nums) # False
16. Length (len)
o Returns the total number of elements in the list.
17. fruits = ['apple', 'banana', 'orange']
18. print(len(fruits)) # Output: 3

🔹 List Slices

 A slice is a subsequence (part of a list) obtained by using the colon : operator


inside brackets.
 Syntax:
 list[start : stop : step]
o start → starting index (default = 0)
o stop → ending index (excluded)
o step → jump (default = 1)

Examples:
t = ['a', 'b', 'c', 'd', 'e']

print(t[1:3]) # ['b', 'c'] (from index 1 to 2)


print(t[:4]) # ['a', 'b', 'c', 'd'] (from start to index 3)
print(t[3:]) # ['d', 'e'] (from index 3 to end)
print(t[:]) # ['a', 'b', 'c', 'd', 'e'] (full copy)

Negative Index Slices:


t = ['a', 'b', 'c', 'd', 'e']
print(t[-3:]) # ['c', 'd', 'e'] (last 3 elements)
print(t[:-2]) # ['a', 'b', 'c'] (all except last 2)

🔹 Updating with Slices

Because lists are mutable, slices can also be used to update multiple elements at once.

t = ['a', 'b', 'c', 'd', 'e', 'f']


t[1:3] = ['x', 'y']
print(t) # Output: ['a', 'x', 'y', 'd', 'e', 'f']

✅Key Points to Remember

 + joins lists, * repeats lists.


 in checks for membership.
 len() gives number of items.
 Slicing extracts parts of a list.
 Slices do not affect the original list unless used in assignment.

3. Python List Methods

Python provides many built-in methods to manipulate lists.


Here are the most important ones for your exam:

🔹 1. append(x)

 Adds a new element at the end of the list.


 Syntax: [Link](element)

fruits = ['apple', 'banana']


[Link]('orange')
print(fruits)
# Output: ['apple', 'banana', 'orange']

🔹 2. remove(x)

 Removes the first occurrence of the value x.


 If element not found → ValueError.
nums = [1, 2, 3, 2, 4]
[Link](2)
print(nums)
# Output: [1, 3, 2, 4]

🔹 3. count(x)

 Counts how many times an element occurs in the list.

letters = ['a', 'b', 'a', 'c', 'a']


print([Link]('a'))
# Output: 3

🔹 4. insert(i, x)

 Inserts element x at position/index i.


 Elements shift to the right.

nums = [10, 20, 30]


[Link](1, 15)
print(nums)
# Output: [10, 15, 20, 30]

🔹 5. pop(i)

 Removes and returns the element at index i.


 If i not given → removes last element.

x = [100, 200, 300]


print([Link](1)) # removes element at index 1 → 200
print(x) # Output: [100, 300]

🔹 6. sort()

 Sorts the list in ascending order by default.


 Can sort numbers, strings, etc.

nums = [54, 12, 85, 65]


[Link]()
print(nums)
# Output: [12, 54, 65, 85]

(Optional: [Link](reverse=True) → descending order)


🔹 7. reverse()

 Reverses the order of elements in place.

x = [1, 2, 3, 4]
[Link]()
print(x)
# Output: [4, 3, 2, 1]

🔹 8. clear()

 Removes all elements from the list (makes it empty).

x = [10, 20, 30]


[Link]()
print(x)
# Output: []

🔹 9. index(x)

 Returns the index position of the first occurrence of element x.

names = ['ram', 'sam', 'tom']


print([Link]('sam'))
# Output: 1

🔹 10. extend(list2)

 Adds all elements of another list to the end of the current list.

a = [1, 2, 3]
b = [4, 5]
[Link](b)
print(a)
# Output: [1, 2, 3, 4, 5]

✅Key Points to Remember

 append() → add single element.


 extend() → add multiple elements (another list).
 insert() → add at specific index.
 remove() → delete by value, pop() → delete by index.
 sort() and reverse() modify the list permanently.
 clear() makes list empty.
 count() and index() help in searching values.
4. List Loop & Mutability

🔹 List Looping

 A loop is used to process each element in a list, one by one.


 for loop is commonly used with lists.
 Loop will run once for every item in the list.

Example 1:

colours = ["red", "green", "blue"]


for c in colours:
print(c)

Output:

red
green
blue

Example 2:

months = ["Jan", "Feb", "Mar"]


for m in months:
print(m)

Output:

Jan
Feb
Mar

✅Loops make it easy to traverse and process list elements.

🔹 List Mutability

 Mutability = ability of a data structure to be changed after creation.


 Strings are immutable (cannot be modified), but lists are mutable.
 We can change, add, or delete elements from a list without creating a new one.

Example 1 – Updating Value by Index:


nums = [10, 20]
nums[1] = 50
print(nums)

Output:

[10, 50]

Example 2 – Updating Using Negative Index:

fruits = ["apple", "grapes", "orange"]


fruits[-1] = "mango" # changes last element
print(fruits)

Output:

['apple', 'grapes', 'mango']

Example 3 – Multiple Updates Using Slice:

t = ['a', 'b', 'c', 'd', 'e']


t[1:3] = ['x', 'y']
print(t)

Output:

['a', 'x', 'y', 'd', 'e']

✅ Key Points to Remember

 Looping: for loop is used to access each list element.


 Mutable: Lists can be modified directly.
 You can update elements using index or slice.
 Negative indices allow access from the end of list.

5. List Aliasing, Cloning & Parameters

🔹 Aliasing

 Aliasing happens when two or more variables refer to the same list.
 Changing one will automatically affect the other.
 This is because both variables point to the same memory location.
Example:

A = [1, 2, 3]
B = A # aliasing
B[0] = 9
print(A) # Output: [9, 2, 3]
print(B) # Output: [9, 2, 3]

✔️ Here, A and B are different names for the same object.

🔹 Cloning

 To avoid aliasing, we can create a copy of a list.


 The most common way → use slicing ([:]).
 Now, modifying one will not affect the other.

Example:

A = [1, 2, 3]
B = A[:] # cloning
B[0] = 5
print(A) # Output: [1, 2, 3]
print(B) # Output: [5, 2, 3]

✔️ A remains unchanged because B is a new list.

🔹 List as Function Parameter

 When a list is passed to a function, it is passed by reference.


 This means the function can modify the original list.

Example:

def delete_head(t):
del t[0] # removes first element

letters = ['a', 'b', 'c']


delete_head(letters)
print(letters)

Output:

['b', 'c']
✔️ The original list letters is changed because the parameter t refers to the same list.

✅ Key Points to Remember

 Aliasing: B = A → both refer to same list (dangerous if one is modified).


 Cloning: B = A[:] → creates a new independent copy.
 Function Parameters: Lists are passed by reference, so functions can change the
original list.

6. Tuples in Python

🔹 Definition

 A tuple is a sequence of values, similar to a list.


 The main difference: Tuples are immutable → once created, elements cannot be
changed.
 Tuples are useful for storing fixed collections of items.

🔹 Creating Tuples

1. Normal tuple:

t = ('a', 'b', 'c')


print(t) # Output: ('a', 'b', 'c')

2. Single element tuple:


o Must include a comma; otherwise, Python treats it as a string/number in
brackets.

t1 = ('a',)
print(type(t1)) # Output: <class 'tuple'>

t2 = ('a')
print(type(t2)) # Output: <class 'str'>

3. Using tuple() function:

t = tuple('lupins')
print(t)
# Output: ('l', 'u', 'p', 'i', 'n', 's')
🔹 Accessing Elements

 Tuples support indexing and slicing, same as lists.

t = ('a', 'b', 'c', 'd', 'e')


print(t[0]) # Output: 'a'
print(t[1:3]) # Output: ('b', 'c')

🔹 Immutability

 Tuples cannot be modified.

t = ('a', 'b', 'c')


t[0] = 'A' # ❌ Error: TypeError (tuples are immutable)

✔️ Instead, you can create a new tuple:

t = ('a', 'b', 'c')


t = ('A',) + t[1:]
print(t)
# Output: ('A', 'b', 'c')

🔹 Tuple Assignment

 Tuples allow assigning multiple values at once.

x, y = (10, 20)
print(x) # 10
print(y) # 20

 Useful for swapping values without a temporary variable:

a, b = 5, 7
a, b = b, a
print(a, b) # Output: 7 5

🔹 Tuples as Return Values

 Functions can return multiple values by returning them inside a tuple.

Example 1 – Using divmod:

result = divmod(7, 3)
print(result) # Output: (2, 1)
quot, rem = divmod(7, 3)
print(quot) # Output: 2
print(rem) # Output: 1

Example 2 – Custom Function:

def min_max(t):
return min(t), max(t)

nums = [5, 10, 2]


print(min_max(nums))
# Output: (2, 10)

✅ Key Points to Remember

 Tuple = immutable list (cannot change after creation).


 Created using parentheses ( ) or tuple() function.
 Single element tuple needs a comma: ('a',).
 Supports indexing, slicing, assignment unpacking.
 Useful for returning multiple values from a function.

7. Dictionary in Python

🔹 Definition

 A dictionary is an unordered collection of items in key:value pairs.


 Keys must be unique and of an immutable type (string, number, tuple).
 Values can be of any data type and may repeat.
 Dictionaries are written inside curly braces { }.

🔹 Creating a Dictionary
dict1 = {1: "Fruit", 2: "Veg"}
print(dict1)
# Output: {1: 'Fruit', 2: 'Veg'}

dict2 = {"Name": "Zara", "Age": 20, "Subjects": ["Math", "Physics"]}


print(dict2)
# Output: {'Name': 'Zara', 'Age': 20, 'Subjects': ['Math', 'Physics']}

✅Empty dictionary:
empty_dict = {}

🔹 Accessing Values

 Use the key to get the value.

dict1 = {1: "Fruit", 2: "Veg"}


print(dict1[1]) # Output: Fruit
print(dict1[2]) # Output: Veg

🔹 Updating Dictionary

 You can update existing keys or add new ones.

student = {"Name": "Nivetha", "Rank": 5}


student["Rank"] = 3 # update existing key
student["Average"] = 78.9 # add new key
print(student)
# Output: {'Name': 'Nivetha', 'Rank': 3, 'Average': 78.9}

🔹 Deleting Elements

 Remove a specific key:value pair using del.


 Remove the entire dictionary also with del.

d = {"Name": "Zara", "Age": 7, "Class": "First"}


del d["Age"] # deletes key 'Age'
print(d)
# Output: {'Name': 'Zara', 'Class': 'First'}

del d # deletes entire dictionary


🔹 Common Dictionary Methods
✅ Key Points to Remember

 Dictionary = unordered key:value pairs.


 Keys must be unique & immutable.
 Supports fast lookups using keys.
 Important methods: clear(), copy(), items(), keys(), values(),
update(), fromkeys(), get(), len() .

8. List Comprehension / Advanced List Processing

🔹 Definition

 A list comprehension is a compact way to create new lists from existing


iterables (list, tuple, string, etc.).
 It combines loop + optional condition + expression into a single line.
 Provides a more readable and faster alternative to using loops.

🔹 Syntax
[expression for variable in iterable if condition]

 expression → operation to perform or value to store.


 variable → element from the iterable.
 iterable → sequence (list, string, tuple, etc.).
 if condition (optional) → filter elements.

🔹 Examples

Example 1 – Basic Transformation

nums = [11, 22, 33]


result = [x*2 for x in nums]
print(result)

Output:

[22, 44, 66]

Example 2 – String Conversion


names = ['alice', 'bob']
upper_names = [[Link]() for name in names]
print(upper_names)

Output:

['ALICE', 'BOB']

Example 3 – With Condition

nums = [10, 15, 20, 25, 30]


even_nums = [x for x in nums if x % 2 == 0]
print(even_nums)

Output:

[10, 20, 30]

Example 4 – Nested Loops

result = [x*y for x in [2, 4] for y in [1, 2, 3]]


print(result)

Output:

[2, 4, 6, 4, 8, 12]

Example 5 – Creating a List from Range

squares = [i*i for i in range(1, 6)]


print(squares)

Output:

[1, 4, 9, 16, 25]

✅ Key Points

 Short, elegant, and faster than traditional loops.


 Can include conditions for filtering.
 Supports nested loops.
 Useful for data transformation and quick list creation.
1. Files in Python
Files are used to store data permanently on a computer’s storage device. Unlike variables
(which store data temporarily in memory), files allow information to persist even after the
program ends. Python provides built-in functions and methods for creating, reading,
writing, and managing files.

Types of Files
1. Text Files

 Store data in human-readable form (characters, words, numbers, symbols).


 Encoding: ASCII or Unicode.
 Examples: .txt, .py, .csv, .html.
 Each line in a text file is terminated by a newline (\n).

Example (Text File Creation):

# Writing to a text file


f = open("[Link]", "w")
[Link]("Hello, this is a text file.\n")
[Link]("Python makes file handling easy.")
[Link]()

# Reading from a text file


f = open("[Link]", "r")
print([Link]())
[Link]()

2. Binary Files

 Store data in binary format (0s and 1s).


 Not directly readable by humans.
 Examples: .jpg, .png, .exe, .mp3, .dat.
 Suitable for images, audio, video, and executable programs.

Example (Binary File Copy):

# Copying an image file


with open("[Link]", "rb") as f1: # rb = read binary
data = [Link]()

with open("copy_image.jpg", "wb") as f2: # wb = write binary


[Link](data)
2. Opening and Closing Files
To work with files in Python, the built-in open() function is used. This function returns a
file object, which provides methods for reading, writing, and manipulating the file.

Syntax
f = open("[Link]", mode)

 [Link] → name of the file (with path if required).


 mode → specifies the purpose of opening the file (read, write, append, etc.).

Common File Modes


Mode Meaning Example
"r" Read (default). File must exist. open("[Link]", "r")
"w" Write. Creates a new file or overwrites existing. open("[Link]", "w")
"a" Append. Adds new data at the end of file. open("[Link]", "a")
"b" Binary mode (used with r, w, or a). open("[Link]", "rb")
"r+" Read and write. File must exist. open("[Link]", "r+")

Examples
1. Opening in Read Mode
f = open("[Link]", "r")
print([Link]()) # Reads the content
[Link]()

2. Opening in Write Mode


f = open("[Link]", "w")
[Link]("This is a new file content.") # Overwrites file
[Link]()

3. Opening in Append Mode


f = open("[Link]", "a")
[Link]("\nThis line is appended.")
[Link]()

4. Opening in Binary Mode


with open("[Link]", "rb") as f:
data = [Link](20) # Read first 20 bytes
print(data)

Closing a File
When file operations are completed, always close the file to free system resources.

f = open("[Link]", "r")
print([Link]())
[Link]()

Best Practice: Using with open()

Instead of manually closing, Python provides a context manager (with) which automatically
closes the file.

with open("[Link]", "r") as f:


data = [Link]()
print(data) # File automatically closes here

✅ This ensures files are properly closed, even if an error occurs.

3. Reading and Writing Files


After opening a file with the appropriate mode, Python provides several methods to read and
write data.

Reading from Files


Python provides multiple ways to read data:

1. [Link]()

 Reads the entire content of the file as a single string.


 Optional argument specifies the number of characters to read.

f = open("[Link]", "r")
print([Link]()) # Reads the whole file
[Link]()

f = open("[Link]", "r")
print([Link](10)) # Reads first 10 characters
[Link]()
2. [Link]()

 Reads one line at a time (ending at \n).

f = open("[Link]", "r")
print([Link]()) # Reads first line
print([Link]()) # Reads second line
[Link]()

3. [Link]()

 Reads all lines into a list, where each element is one line.

f = open("[Link]", "r")
lines = [Link]()
print(lines) # ['Line 1\n', 'Line 2\n', 'Line 3\n']
[Link]()

Writing to Files
To write content into a file, use "w" or "a" modes.

1. Write Mode ("w")

 Creates a new file or overwrites an existing one.

f = open("[Link]", "w")
[Link]("Hello World\n")
[Link]("Python makes file handling easy.")
[Link]()

Result in [Link]:

Hello World
Python makes file handling easy.

2. Append Mode ("a")

 Adds content to the end of the file without deleting existing data.

f = open("[Link]", "a")
[Link]("\nThis line is appended.")
[Link]()

Result in [Link] (previous content retained):

Hello World
Python makes file handling easy.
This line is appended.

Best Practice: Using with open()

with open("[Link]", "r") as f:


for line in f:
print([Link]()) # Reads line by line

4. Format Operator
In Python, the format operator (%) is used for string formatting, i.e., inserting values into a
string at specific places.

Basic Syntax
"string with placeholders" % (values)

 Placeholders are represented by % followed by a type code.


 The values inside the tuple are substituted into the string.

Common Format Codes


Code Meaning Example
%s String "Hello %s" % "World" → "Hello World"
%d Integer "Age: %d" % 21 → "Age: 21"
%f Floating-point number "Pi = %.2f" % 3.14159 → "Pi = 3.14"

Examples
name = "Alice"
age = 21
pi = 3.14159

print("My name is %s and I am %d years old." % (name, age))


print("Pi value up to 2 decimals: %.2f" % pi)

Output:
My name is Alice and I am 21 years old.
Pi value up to 2 decimals: 3.14

Modern Alternatives
Python provides better, more flexible ways:

1. [Link]() method
print("My name is {} and I am {} years old.".format(name, age))
print("Pi value: {:.3f}".format(pi))

2. f-strings (Python 3.6+)


print(f"My name is {name} and I am {age} years old")
print(f"Pi value up to 4 decimals: {pi:.4f}")

5. Command Line Arguments


When a Python script is executed from the command line, arguments can be passed to it.
Python provides the sys module to work with command line arguments.

Accessing Arguments
import sys

print("Total arguments:", len([Link]))


print("Arguments list:", [Link])

Explanation
 [Link] → List of command-line arguments.
 [Link][0] → The name of the Python script.
 [Link][1], [Link][2], … → Arguments passed to the script.

Example
Suppose we have a file [Link]:

import sys

print("Program name:", [Link][0])


print("First argument:", [Link][1])
print("Second argument:", [Link][2])

Run in terminal:

python [Link] hello world

Output:

Program name: [Link]


First argument: hello
Second argument: world

6. Errors and Exceptions


Errors are problems that occur in a program and stop its normal execution.
In Python, errors are mainly divided into three categories:

1. Syntax Errors
 Occur when the Python code does not follow the correct syntax rules.
 Detected before execution (during compilation).

Example:

print("Hello" # Missing closing parenthesis

Error:

SyntaxError: unexpected EOF while parsing

2. Logical Errors
 Code runs without error but produces incorrect results due to wrong logic.
 Difficult to detect since program executes normally.

Example:

# Program to calculate average


marks = [90, 80, 70]
print("Average =", sum(marks)/2) # Wrong logic (should divide by 3)

Output:
Average = 120.0 # Incorrect result

3. Runtime Errors (Exceptions)


 Errors that occur during program execution.
 These stop the program unless handled.

Examples:

print(10/0) # ZeroDivisionError
int("abc") # ValueError
mylist = [1, 2, 3]
print(mylist[5]) # IndexError

 Syntax Errors → at compile time.


 Logical Errors → wrong output.
 Runtime Errors → exceptions during execution.

7. Handling Exceptions
Python provides a mechanism to handle runtime errors using try–except blocks.

Basic Syntax
try:
# Code that may cause an error
except ErrorType:
# Code to handle the error

Example 1: Multiple Exception Handling


try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input (enter numbers only)")

Example 2: Using finally


 The finally block is always executed, whether an exception occurs or not.
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")
finally:
print("This block always runs.")

Example 3: Raising Exceptions


 The raise keyword is used to manually trigger an exception.

x = -10
if x < 0:
raise ValueError("Negative numbers not allowed")

Output:

ValueError: Negative numbers not allowed

 Use try–except to handle runtime errors.


 Use finally for cleanup code (closing files, releasing resources).
 Use raise to create custom exceptions.

8. Modules
A module in Python is simply a file with the .py extension that contains functions,
variables, or classes.
Modules help in code reusability, organization, and modular programming.

Creating a Module
Example: [Link]

# [Link]
def greet(name):
return f"Hello {name}"

pi = 3.14159

Using a Module
In another program:

import mymodule

print([Link]("Alice"))
print("Value of pi:", [Link])

Other Import Methods


1. Import specific function/variable

from mymodule import greet


print(greet("Bob"))

2. Alias a module

import mymodule as m
print([Link]("Charlie"))

3. Import all (not recommended)

from mymodule import *


print(greet("David"))

 Every .py file is a module.


 Modules improve reusability and maintainability.
 Built-in modules include math, os, random, sys.

9. Packages
A package is a collection of related modules stored in a directory.
The directory must contain a special file: __init__.py (can be empty, but indicates that the
folder is a package).

Package Example
Folder structure:

mypackage/
__init__.py
[Link]
[Link]

[Link]
def add(a, b):
return a + b

[Link]
def subtract(a, b):
return a - b

Using the Package


from mypackage import module1, module2

print([Link](5, 3)) # Output: 8


print([Link](10, 4)) # Output: 6

 Module = single .py file.


 Package = folder with multiple modules + __init__.py.
 Used for better project structure (e.g., numpy, pandas are packages).

You might also like