0% found this document useful (0 votes)
10 views128 pages

Python Programming Basics Guide

The document provides a comprehensive overview of Python programming, covering its history, features, and basic concepts such as data types, control statements, functions, and file handling. It highlights Python's versatility for various applications including web development, data analysis, and machine learning. Additionally, it explains key programming constructs like variables, literals, and built-in functions, making it suitable for beginners and experienced programmers alike.

Uploaded by

ishwarya8085
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)
10 views128 pages

Python Programming Basics Guide

The document provides a comprehensive overview of Python programming, covering its history, features, and basic concepts such as data types, control statements, functions, and file handling. It highlights Python's versatility for various applications including web development, data analysis, and machine learning. Additionally, it explains key programming constructs like variables, literals, and built-in functions, making it suitable for beginners and experienced programmers alike.

Uploaded by

ishwarya8085
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 – SCSPC31

UNIT - 1
Basics of Python Programming: History of Python-Features of Python-Literal-
Constants-Variables – Identifiers–Keywords-Built-in Data Types-Output
Statements – Input Statements-Comments – Indentation- Operators-Expressions-
Type conversions. Python Arrays: Defining and Processing Arrays – Array
methods
UNIT - 2
Control Statements: Selection/Conditional Branching statements: if, if-else, nested
if and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in
loop and nested loops. Jump Statements: break, continue and pass statements.
UNIT - 3
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword
Arguments, Default Arguments and Variable Length Arguments- Recursion.
Python Strings: String operations- Immutable Strings – Built-in String Methods
and Functions – String [Link]: import statement- The Python
module – dir() function – Modules and Namespace – Defining our own modules.
UNIT - 4
Lists: Creating a list -Access values in List-Updating values in Lists - Nested lists -
Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and
Deleting Elements in a tuple – Nested tuples– Difference between lists and tuples.
Dictionaries: Creating, Accessing, Updating and Deleting Elements in a Dictionary
– Dictionary Functions and Methods - Difference between Lists and Dictionaries.
UNIT - 5
Python File Handling: Types of files in Python – Opening and Closing files-
Reading and Writing files: write() and writelines() methods- append() method –
read() and readlines() methods – with keyword – Splitting words – File methods –
File Positions- Renaming and deleting files.
BASICS OF PYTHON :

Python is a versatile, high-level programming language known for


its readability and simplicity.

What is Python?
Python is a high-level, general-purpose
programming language that is:

• Easy to read and write

• Beginner-friendly

• Widely used in many fields

Created by: Guido van Rossum

Released in: 1991

Current Version: Python 3.x (as of now)

What Makes Python Special?


Feature Benefit
Simple, English-like Easy to read/write, ideal for beginners and
Syntax teams
Interpreted Language Run code instantly line-by-line—no compile
step
Dynamically Typed Variables don’t require type declarations—
flexible and fast
Cross-Platform Works seamlessly on Windows, macOS,
(Portable) Linux
Extensible & Easily integrate with C/C++ for performance
Embeddable or embed in other apps
Multi-Paradigm Use procedural, OOP, functional styles, even
Support meta-programming
Massive Standard Pre-packaged modules for web, file I/O,
Library testing, etc.
Great for Data Libraries like NumPy, Pandas, TensorFlow,
Science & AI Matplotlib drive innovation

What Can You Do with Python?

🌐 Web Development
📊 Data Analysis & Visualization
🤖 Machine Learning & AI
🕹 Game Development
🖥 Desktop Applications
🤖 Automation (like bots or scripts)
📱 Internet of Things (IoT)

🔹 Example Code:
Print(“Welcome to Python”)
o/p: Welcome to Python

HISTORY OF PYTHON:
• Python’s history begins in the late 1980s with ‘Guido van
Rossum’, a Dutch programmer, who started developing it as a
hobby project during the Christmas holidays.
• The language was officially released in 1991, with the name
"Python” inspired by the British comedy group ‘Monty
Python’s Flying Circus’.
• Over the years, Python has evolved through several versions,
including 1.0 (1994), 2.0 (2000), and 3.0 (2008).
• 1980s: Guido van Rossum begins developing Python at CWI
(Centrum Wiskunde & Informatica) a research institute in
mathematics and computer science in the Netherlands, aiming to
create a successor to the ABC programming language.
• 1991: Python 0.9 is released, marking the first official public
release.
• 1994: Python 1.0 is released, introducing features like exception
handling and lambda expressions.
• 2000: Python 2.0 is released, adding list comprehensions and
other key features.

• 2008: Python 3.0 is released, which introduced significant


changes and was not backwards compatible with earlier
versions.
• 2010s: Python''s popularity and community grow rapidly, driven
by advancements in fields like data science and machine
learning.
• 2018: Guido van Rossum steps down as the Benevolent Dictator
For Life (BDFL).
• 2020: Python 2 reaches end-of-life. Python continues to
evolve, with new versions and features being introduced.

Guido Van Rossum

FEATURES OF PYTHON:

1. Easy to Learn and Read: Python's syntax is designed to be


simple and intuitive, making it beginner-friendly and easy to
understand.

2. Interpreted Language: Python code is executed line by line,


making it easier to debug and test.

3. Open Source and Free: Python is freely available for use,


modification, and distribution.

4. Large Standard Library: Python includes a vast collection of


pre-built modules and libraries for various tasks, reducing the
need for third-party packages.

5. High-Level Language: Python abstracts away low-level details,


allowing developers to focus on algorithms and functionality.
6. Object-Oriented Programming (OOP) Language: Python
supports OOP principles, allowing for the creation of modular and
reusable code.

7. Platform Independent: Python code can run on different


operating systems like Windows, macOS, and Linux without
modification.

8. Graphical User Interface (GUI) Support: Python offers


libraries like Tkinter, wxPython, and PyQt for creating graphical
user interfaces.

9. Multi-Paradigm: Python supports multiple programming


paradigms, including object-oriented, functional, and procedural
programming.

10. Versatile and Flexible: Python is a general-purpose language


suitable for a wide range of applications, including web
development, data analysis, machine learning, and more.

LITERALS:

➢ In Python, a literal represents a fixed value in the source code.


➢ A literal is a sequence of one or more characters that stands for
itself.
➢ Literals are used to assign values to variables.

There are several types of literals in Python:

1. String literals: Represent text enclosed in single, double, or


triple quotes.
2. Numeric literals: Represent numbers, and can be integers,
floating-point numbers, or complex numbers.
3. Boolean literals: Represent truth values, either True or False.
4. None literal: Represents the absence of a value, denoted by
None.
5. Collection literals: Represent collections of data, such as lists,
tuples, dictionaries, and sets.

EXAMPLE

string_literal = "Hello, world!"integer_literal = 10

float_literal = 3.14

boolean_literal = True

none_literal = None

list_literal = [1, 2, 3]

tuple_literal = (4, 5, 6)

dictionary_literal = {"name": "Alice", "age": 30}

set_literal = {7, 8, 9}

# Using literals in expressions

result = integer_literal + 5

#10+5

#OUTPUT: 15

message = string_literal + " Welcome!"

#OUTPUT: "Hello, world! Welcome!"


# Assigning literals to variables

name = "Bob"

pi = 3.14159

VARIABLES:

➢ A variable holds a value. A value is assigned to a variable.

➢ A variable is a name given to the memory location to store


values, so that there is no need to remember the address of the
location.

➢ The assignment statement ( = ) assigns a value to a variable.

Rules for naming variables:

1) They can contain both letters and numbers but they cannot begin
with a number.

2) No blank spaces are allowed between variable names.

3) A variable name cannot be any one of the keywords or special


characters.

4) Variable names are case-sensitive.

5) Variable names can be uppercase letters or lowercase letters.

6) The underscore character ( _ ) can appear in a name. It is often


used in names with multiple words

7) Variable names can be at any length.


SYNTAX:

Variable_name = value

Explanation: The value on the right side is then associated with the
variable name on the left side.

EXAMPLE:

# Valid variable names

age = 30

user_name = "Alice"

_count = 10

total_score = 150

# Invalid variable names (will cause errors)

1st_name = "Bob" # SyntaxError: invalid syntax

user-id = 12345 # SyntaxError: invalid syntax

for = "loop" # SyntaxError: invalid syntax

IDENTIFIERS:

➢ In Python, an identifier is a name given to entities like


variables, functions, classes.
➢ It allows you to access and manipulate these entities within
your code.
EXAMPLE:

Age = 30 # ‘age’ is a variable identifier

def calculate_area(length, width): # ‘calculate_area’ is a function


identifier

class dog: # ‘Dog’ is a class identifier.

CONSTANTS:

➢ Constants are variables whose values are not intended to be


changed during the program’s execution.
➢ Although Python doesn’t have a built-in mechanism to enforce
immutability for constants, it relies on naming conventions to
indicate that a variable should be treated as a constant.
➢ By convention, constants in Python are named using uppercase
letters, with words separated by underscores.

EXAMPLE:

# Define constants

PI = 3.14159

GRAVITY = 9.8

# Use constants

radius = 5

circumference = 2 * PI * radius
printf(“The circumference of the circle is: {circumference}")

KEYWORDS:

➢ Keywords are reserved words they have predefined meanings


in python.
➢ They cannot be used as ordinary identifiers.
➢ Python is case sensitive so keyword must be spelled exactly as
they are written.
➢ Python 3 has 33 keywords.

➢ import keyword
print(keyword. kwlist)

Keywords Description
False Represents the boolean value
false.
True Represents the boolean value true.
None Represents a null value or no
value at all.
as Used to create an alias while
importing a module.
assert Used for debugging by testing a
condition. If the condition is
False, it raises an exception.
async Used to define asynchronous
functions
await Used to wait for the result of an
asynchronous call
break Terminates the loop prematurely.
class Used to define a class.
continue Skips the rest of the code inside a
loop for the current iteration and
proceeds to the next iteration.
def Used to define a function.
del Deletes objects like variables,
lists, or dictionary elements.
elif Used for conditional branching
(else if). else specifies a block of
code to execute if the condition in
if or elif is false.
except Used to catch exceptions in a try
block.
finally A block of code that will be
executed regardless of an
exception occurring or not.
for Used for looping over an iterable.
from Specifies the module to import
specific parts from.
global Declares a variable as global,
allowing it to be modified outside
the current scope.
if Used for conditional branching.
in Check if an element is present in
a sequence.
is Tests for object identity.
not Logical operator to invert the
truth value of an expression.
or Logical operator to combine
conditional statements.
pass A null operation, is used as a
placeholder.
raise Used to raise an exception.
return Exits a function and optionally
passes back a value.
try Starts a block of code to test for
exceptions.
while Used to create loops that continue
while a condition is true.
with Used to simplify exception
handling and resource
management.
yield Pauses the function execution and
returns a value, allowing it to be
resumed later.

BUILT-IN DATATYPES:
DATATYPES:
➢ In Python, a data type defines the type of value a variable can
hold.
➢ It tells the interpreter what kind of data is being stored like
numbers, text, or more complex structures.
➢ Data types help in allocating memory and performing
operations on variables.
TYPES OF DATATYPES:
Python has two main categories of data types:

1. Built-in Data Types


2. User-defined Data Types
[Link]-in datatypes:
Python has several built-in data types, grouped into the following
categories:
i. Numeric Types:
int: Represents integers of any size.
float: Represents floating-point numbers.
complex: Represents complex numbers.
Example:
a = 10 # int
b = 3.5 # float
c = 2 + 3j # complex

ii. Sequence types:


str: Represents immutable sequences of characters (strings).
list: Represents mutable sequences of items.
tuple: Represents immutable sequences of items.
range: Generates a sequence of numbers within a specified range.
Example:
My_list = [1, 2, 3]
My_tuple = (4, 5, 6)
My_range = range(1, 5) # 1 to 4

iii. Mapping Types:


dict: Represents a collection of key-value pairs.
Example:
student = {"name": "Jesima", "age": 22}

[Link] types:
set: Represents an unordered collection of unique elements.

Example:
my_set = {1, 2, 3}

v. Boolean types:
bool: Represents True or False
Example:
is_active = True

vi. Binary Types


bytes: Represents immutable sequences of bytes.
bytearray: Represents mutable sequences of bytes.
Example:
b = bytes(5) # b'\x00\x00\x00\x00\x00'
ba = bytearray(5) # mutable version

OUTPUT STATEMENT:
Output statements in Python are primarily handled by the print()
function, which displays data to the console.

i. Basic Usage
The simplest form of output is printing a string literal:
EXAMPLE:
print("Hello, world!")
# Output:
Hello, world!

The print() function can also output the value of variables:


EXAMPLE:
name = "Alice"
age = 30
print("Name:", name)
print("Age:", age)
# Output:
Name: Alice
Age: 30

ii) Multiple Arguments


The print() function can take multiple arguments, which it will output
separated by spaces by default:
EXAMPLE:
x=5
y = 10
print("The value of x is", x, "and the value of y is", y)
# Output:
The value of x is 5 and the value of y is 10
iii) Custom Separator and End Characters
The print() function allows customization of the separator between
items
and the end character using the sep and end parameters:
EXAMPLE:
print("apple", "banana", "cherry", sep=", ")
# Output:
apple, banana, cherry

print("first line", end=" ")


print("second line")
# Output:
first line second line

iv) Formatted output


✓ Python offers several ways to format output, including f-strings
(formatted string literals), the .format() method, and the older
% operator.
✓ F-strings are generally preferred for their readability and
efficiency:
EXAMPLE:
name = "Bob"
score = 85
print(f"The score of {name} is {score}")
# Output:
The score of Bob is 85

print("The score of {} is {}".format(name, score))


# Output:
The score of Bob is 85

INPUT STATEMENTS:
✓ Input statements in Python allow programs to receive data from
users during runtime.
✓ The input() function is used for this purpose.

i) Basic Input
The input() function takes an optional string argument, which serves
as a prompt to the user.
EXAMPLE:
name = input("Enter your name: ")
print("Hello, " + name + "!")
#OUTPUT
Enter your name: kaviya
Hello, kaviya!

ii) Handling Multiple Inputs


You can take multiple inputs in a single line using the split() method.
EXAMPLE:
x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)
#OUTPUT
Enter two numbers separated by space: 12 76
Sum: 88

iii) Error Handling


It is good practice to handle potential errors when taking input,
especially when converting to numbers.
EXAMPLE:
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Invalid input. Please enter a valid integer.")
#OUTPUT-1
Enter a number: 45
You entered: 45
#OUTPUT-2
Enter a number: 56.98
Invalid input. Please enter a valid integer.

COMMENTS OR DOCSTRING OR DOCUMENTATION


SECTION :
✓ Comments in Python are explanatory notes added to the code to
make it more readable and understandable.
✓ They are ignored by the Python interpreter during execution.

i) Single-line comments
Begin with a hash symbol (#). Everything after the # on that line is
considered a comment.
EXAMPLE:
# This is a single-line comment

ii) Multi-line comments


• Using triple-quoted strings: Although technically a string literal, a
multi-line string that is not assigned to a variable can be used as a
multi-line comment.
EXAMPLE:
"""
This is a multi-line comment
using a triple-quoted string.
"""
print("Hello, world!")

INDENTATIONS:
✓ Indentation in Python is the whitespace at the beginning of a
code line.
✓ It's crucial because it signifies code block structure.
✓ Unlike languages using curly braces, Python uses indentation to
group statements.
✓ Consistent indentation ensures the code runs as expected.

EXAMPLE:
# Correct indentation
if 5 > 2:
print("Five is greater than two!")
print("This is also inside the if block.")

# Incorrect indentation (will cause an IndentationError)


# if 5 > 2:
# print("Five is greater than two!") #IndentationError: expected an
indented block
Rules for Indentation
• Python uses four spaces as default indentation, but the number can
vary as long as it's consistent within a block.
• The first line of code should not be indented.
• Indentation is mandatory for defining code blocks.
• The number of spaces must be uniform within a block.
• Mixing tabs and spaces can cause errors, so it's best to stick to one or
the other.

Importance of Indentation

✓ Indentation in Python isn't just for readability, it's a syntax


requirement.
✓ Correct indentation is essential for the interpreter to understand
the code's structure and execute it properly.
✓ Inconsistent or incorrect indentation will result
in IndentationError, preventing the code from running.

OPERATORS:

✓ An operator in Python is a special symbol or keyword


that is used to perform operations on values (or variables).
✓ Operators allow us to manipulate values, combine them, or
compare them to achieve specific results.
✓ They are used to carry out various operations such as
arithmetic calculations, logical comparisons, and bitwise
operations.
✓ Operators are central to programming, enabling the
manipulation of data and control of program flow.
✓ Operators are usually classified into the following
categories:

Arithmetic Operators

✓ Arithmetic operators perform basic mathematical operations.


✓ These operators are used to carry out calculations such as
addition, subtraction, multiplication, etc.

EXAMPLE:

a = 10

b=5

# Addition

result = a + b # result = 15

# Subtraction

result = a - b # result = 5

# Multiplication

result = a * b # result = 50

# Division

result = a / b # result = 2.0 (float division)

# Floor Division

result = a // b # result = 2 (integer division)

# Modulus

result = a % b # result = 0 (remainder of division)


# Exponentiation

result = a ** b # result = 100000 (10 raised to the power of 5)

Comparison (Relational) Operators:

✓ These operators are used to compare values.


✓ The result of a comparison is always a boolean value (True or
False).

EXAMPLE:

x=5

y=3

# Equal to

print(x == y) # False

# Not equal to

print(x != y) # True

# Greater than

print(x > y) # True

# Less than

print(x < y) # False

# Greater than or equal to

print(x >= y) # True

# Less than or equal to

print(x <= y) # False


Assignment Operators:

✓ Assignment operators are used to assign values to variables.


✓ They allow you to assign the result of an operation to a variable.

EXAMPLE:

# Assign value 10 to x

x = 10

# Equivalent to x = x + 5 (x becomes 15)

x += 5

# Equivalent to x = x - 3 (x becomes 12)

x -= 3

# Equivalent to x = x * 2 (x becomes 24)

x *= 2

# Equivalent to x = x / 4 (x becomes 6.0)

x /= 4

# Equivalent to x = x % 3 (x becomes 0)

x %= 3
Logical Operators

✓ Logical operators are used to combine conditional statements or


expressions.
✓ These operators are commonly used in if statements to control
the flow based on multiple conditions.

EXAMPLE:

x=5

y = 10

# AND

print(x > 0 and y < 15) # True (both conditions are True)

# OR

print(x < 0 or y > 5) # True (at least one condition is True)

# NOT

print(not(x > 0)) # False (negates the condition)

Bitwise Operators:

✓ Bitwise operators perform bit-level operations on integer types.


✓ They are used to manipulate individual bits of a number.
EXAMPLE:

a = 5 # 5 in binary: 101

b = 3 # 3 in binary: 011

# AND

print(a & b))

# 1 (binary 001)

# OR

print(a | b)

# 7 (binary 111)

# XOR

print(a ^ b) # 6 (binary 110)

# 7 (binary 111)

# NOT

print(~a)

# -6 (binary 010 -> flipping the bits)

# Left Shift

print(a << 1)

# 10 (binary 1010)
# Right Shift

print(a >> 1)

# 2 (binary 010)

Membership Operators:

Membership operators are used to test if a value is present in a


sequence (like a string, list, tuple, etc.).

EXAMPLE:

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

# In

print('banana' in fruits) # True

# Not In

print('orange' not in fruits) # True

Identity Operators:

✓ Identity operators compare the memory locations of two objects.


✓ They are used to check if two variables point to the same object
in memory.
EXAMPLE:

a = [1, 2, 3]

b=a

c = [1, 2, 3]

# is

print(a is b) # True (b points to the same object as a)

# is not

print(a is not c) # True (c is a different object, even though the values


are the same)

Ternary (Conditional) Operator:

Python also supports a shorthand version of if-else called the ternary


operator.

Syntax:

x = 10 if condition else 5

• If condition is True, x will be assigned 10.


• If condition is False, x will be assigned 5.
Example:

x = 10

result = “Even” if x % 2 == 0 else "Odd"

print(result)

# Output: Even

EXPRESSIONS:

✓ An expression in Python is a combination of values, variables,


operators, and function calls that the interpreter can evaluate to
produce a result.
✓ It represents a computation or a calculation.
✓ Expressions are fundamental building blocks of Python code,
used to perform operations, manipulate data, and make
decisions.
DIFFERENCE BETWEEN OPERATORS AND EXPRESSIONS:

Category Expressions Operators

Definition An expression is a An operator is a symbol or


combination of keyword used to perform
values, variables, operations on variables or
and operators that values.
can be evaluated to
produce a result.

Purpose To calculate or To perform specific


evaluate a value. operations (e.g.,
arithmetic, logical, etc.).

Example x+y + (addition operator)


(expression
with an
addition
operator)

Complexity Can contain Individual symbols or


multiple operators keywords that perform a
and variables, . specific operation.
forming a complete
statement.

Output Produces a Used to manipulate or


value/result when combine values.
evaluated.
TYPE CONVERSIONS:

✓ Type conversion, also known as type casting, is the process of


changing a value from one data type to another.
✓ In Python, this can occur implicitly or explicitly.

Implicit Type Conversion:


✓ Python automatically converts one data type to another without
any explicit instruction from the programmer.
✓ This usually happens when performing operations between
different data types.

EXAMPLE:

num_int = 123

num_float = 1.23

num_new = num_int + num_float

print("Data type of num_int:",type(num_int))

print("Data type of num_float:",type(num_float))

print("Value of num_new:",num_new)

print("Data type of num_new:",type(num_new))

OUTPUT:

Data type of num_int: <class 'int'>

Data type of num_float: <class 'float'>

Value of num_new: 124.23

Data type of num_new: <class 'float'>


Explicit Type Conversion:
✓ Programmers use built-in functions to explicitly convert values
from one data type to another.
✓ Common functions used for explicit type conversion include:
• int(): Converts a value to an integer.
• float(): Converts a value to a floating-point number.
• str(): Converts a value to a string.
• bool(): Converts a value to a Boolean

EXAMPLE:
num_str = "12"
num_int = 34
num_sum = int(num_str) + num_int
print("The sum of num_str and num_int is:", num_sum)
print("Data type of num_sum:", type(num_sum))

string_int = "10"
string_float = "10.5"
num_int = int(string_int)
num_float = float(string_float)
print("Data type of num_int:", type(num_int))
print("Data type of num_float:", type(num_float))

OUTPUT:
The sum of num_str and num_int is: 46
Data type of num_sum: <class 'int'>
Data type of num_int: <class 'int'>
Data type of num_float: <class 'float'>

PYTHON ARRAYS
DEFINING AND PROCESSING ARRAYS

ARRAYS IN PYTHON:

✓ In Python, an array is a data structure that stores a collection of


elements of the same data type.
✓ Python lists can hold elements of different types, arrays are
designed for homogeneity, making them more memory-efficient
for numerical operations.

Defining Arrays:
✓ To use arrays in Python, you first need to import
the array module.
✓ Arrays are defined using the array() constructor, which takes
two arguments: the type code and a list or iterable of initial
values.

EXAMPLE:

import array as arr

# Defining a list (array) with integers

arr = [1, 2, 3, 4, 5]

# Defining a list with mixed types

arr_mixed = [1, 'two', 3.0]

Accessing Array Elements:

You can access elements in a list using indices, where indexing starts
from 0.

EXAMPLE:
arr = [10, 20, 30, 40, 50]

# Accessing the first element

print(arr[0]) # Output: 10

# Accessing the last element using negative indexing

print(arr[-1]) # Output: 50

Processing the array:

You can process lists using various built-in methods:

• Append: Add an element to the end of the array.


• Insert: Insert an element at a specific index.
• Remove: Remove an element by value.
• Pop: Remove an element at a specific index and return it.
• Slice: Extract a portion of the array.

EXAMPLE:

arr = [10, 20, 30, 40, 50]

# Append a new element

[Link](60)

print(arr) # Output: [10, 20, 30, 40, 50, 60]

# Insert an element at index 2

[Link](2, 25)

print(arr) # Output: [10, 20, 25, 30, 40, 50, 60]


# Remove an element by value

[Link](40)

print(arr) # Output: [10, 20, 25, 30, 50, 60]

# Pop an element at index 1

popped_value = [Link](1)

print(popped_value) # Output: 20

print(arr) # Output: [10, 25, 30, 50, 60]

# Slice the array (extract elements from index 1 to 3)

sliced_arr = arr[1:4]

print(sliced_arr) # Output: [25, 30, 50]

ARRAY METHODS

1. Basic List Methods


o append()

• Purpose: Adds a single element to the end of the list.


• Syntax: [Link](element)
• Example:

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

o extend()

• Purpose: Adds multiple elements (from an iterable) to the end


of the list.
• Syntax: [Link](iterable)
• Example:

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

o insert()

• Purpose: Inserts an element at a specific position in the list.


• Syntax: [Link](index, element)
• Example:

arr = [1, 2, 4]
[Link](2, 3) # Insert 3 at index 2
print(arr)
# Output: [1, 2, 3, 4]

o remove()

• Purpose: Removes the first occurrence of a specified element


from the list. If the element is not found, a ValueError is raised.
• Syntax: [Link](element)
• Example:
arr = [1, 2, 3, 4, 2]
[Link](2) # Removes the first occurrence of 2
print(arr)
# Output: [1, 3, 4, 2]
o pop()

• Purpose: Removes and returns the element at the specified


index. If no index is specified, it removes and returns the last
item in the list.
• Syntax: [Link]([index])
• Example:

arr = [1, 2, 3, 4]
popped_value = [Link](1) # Removes and returns the element
at index 1
print(popped_value) # Output: 2
print(arr)
# Output: [1, 3, 4]

o clear()

• Purpose: Removes all elements from the list, leaving it empty.


• Syntax: [Link]()
• Example:

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

2. Querying List Elements

o index()

• Purpose: Returns the index of the first occurrence of the


specified element. If the element is not found, a ValueError is
raised.
• Syntax: [Link](element)

• Example:

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

o count()

• Purpose: Returns the number of occurrences of the specified


element in the list.
• Syntax: [Link](element)
• Example:

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

o copy()

• Purpose: Creates and returns a shallow copy of the list.


Changes to the new list won't affect the original list.
• Syntax: [Link]()
• Example:

arr = [1, 2, 3]
arr_copy = [Link]()
print(arr_copy)
# Output: [1, 2, 3]
3. Sorting and Reversing

o sort()

• Purpose: Sorts the list in ascending order by default. You can


also specify a custom sorting order using the reverse parameter
or a key function.
• Syntax: [Link](key=None, reverse=False)
• Example:

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

# Sorting in reverse order


[Link](reverse=True)
print(arr)
# Output: [5, 4, 3, 2, 1]

o sorted()

• Purpose: Returns a new sorted list, without modifying the


original list.
• Syntax: sorted(iterable, key=None, reverse=False)
• Example:

arr = [3, 1, 4, 5, 2]
sorted_arr = sorted(arr)
print(sorted_arr)
# Output: [1, 2, 3, 4, 5]
print(arr)
# Original list remains unchanged: [3, 1, 4, 5, 2]
o reverse()

• Purpose: Reverses the elements of the list in place.


• Syntax: [Link]()
• Example:

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

o reversed()

• Purpose: Returns a reversed iterator (does not modify the


original list).
• Syntax: reversed(iterable)
• Example:

arr = [1, 2, 3, 4, 5]
reversed_arr = list(reversed(arr)) # Convert iterator to list
print(reversed_arr)
# Output: [5, 4, 3, 2, 1]

4. Other Useful Methods

o join()

• Purpose: Joins elements of an iterable (such as a list) into a


string, using a specified separator.
• Syntax: 'separator'.join(iterable)
• Example:

arr = ['apple', 'banana', 'cherry']


joined_str = ', '.join(arr)
print(joined_str)
# Output: "apple, banana, cherry"
o list()

• Purpose: Converts an iterable (e.g., string, tuple, or range) into


a list.
• Syntax: list(iterable)
• Example:

string = "hello"
list_from_string = list(string)
print(list_from_string)
# Output: ['h', 'e', 'l', 'l', 'o']

o max() and min()

• Purpose: These functions return the largest and smallest


element of the list, respectively.
• Syntax: max(list) or min(list)
• Example:

arr = [10, 20, 30, 40, 50]


print(max(arr))
# Output: 50
print(min(arr))
# Output: 10

o sum()

• Purpose: Returns the sum of all elements in the list (for


numerical elements).
• Syntax: sum(list)
• Example:

arr = [1, 2, 3, 4, 5]
print(sum(arr))
# Output: 15
5. List Slicing and Indexing

Python lists also support slicing and indexing for extracting parts of
lists or accessing specific elements.

Slicing

✓ Slicing allows you to extract a portion of a list.


✓ The syntax is list[start:end:step].

• start: Index to start from (inclusive).


• end: Index to stop at (exclusive).
• step: The step size.

Example:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
slice_arr = arr[Link]
print(slice_arr)
# Output: [3, 5, 7]

Indexing

Lists also support indexing using arr[index] to access individual


elements.

Example:

arr = [1, 2, 3, 4, 5]
print(arr[0])
# Output: 1
print(arr[-1])
# Output: 5 (last element)
PART A

1. Is python case sensitive when dealing with identifiers?


(a) no
(b) yes
(c) machine dependent
(d) none of the mentioned
Answer : (b) yes

2. Which of the following is the correct extension of the python file?


(a) .python
(b) .pl
(c) .py
(d) .p
Answer: (c) .py
3. A variable can be removed using _____________keyword
(a) remove
(b) clear
(c) del
(d) delete
Answer: (c) del

4. Which one of the following is a escape sequence in python?


(a) \\
(b) \
(c) \”
(d) All the above
Answer: (d) All the above

5. Which part of if statement should be indented?


(a) The first statement
(b) Statements within if block
(c) All the statements
(d) None
Answer: (b) Statements within if block

6. Which of the following character is used to give single-line


comments in python?
(a) //
(b) #
(c) !
(d) /*
Answer: (b) #

PART B

1. Write a note on features of python.


2. Discuss input statements in python with example.
3. How to write and execute a python program.
4. Write a note on Bitwise operators in python.
5. Discuss input statements in python with example.
6. Write a note on history of python.

PART C

1. Write about (i) Output Statement (ii)Data Types


2. How to define array in python? How it process?
3. Explain in detail about various operators in python with example.
4. Explain in detail about different data types in python with example.
5. Explain about operators in python.
Python Control Statements
In any programming language a program may execute
sequentially, selectively or iteratively. Every programming
language provides constructs to support Sequence,
Selection and Iteration. In Python all these construct can
broadly categorized in 2 categories.
A. Conditional Control Construct
(Selection, Iteration)
B. Un- Conditional Control Construct
(pass, break, continue, exit(), quit())

Python have following types of control statements


Conditional Control
1. Selection (branching) Statement
[Link]( looping) Statement

Un- Conditional Control


[Link](break / continue/pass)Statement

Conditional Statement
• Conditional statements are used to execute
specific blocks of code based on whether
certain conditions evaluate to True or False .
• They are fundamental for controlling the flow
of a Python program and implementing logic.

Python Selection Statements

Python have following types of selection statements

1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
Python If statements
The if statement allows you to execute a block of code only if a
specified condition is True .
Syntax:

if condition:
# block of code

Syntax Explanation:
• The condition can be any expression that evaluates to a boolean value
( True or False ).
• If the condition is True , the indented block of code following the if
statement is executed.
• If the condition is False , the block of code is skipped.
Flowchart
Flow Chart: it is a graphical
representation of steps an
algorithm to solve a problem.
Example:
x = 10
if x > 5:
print("x is greater than 5")

Explanation:
• Here, x > 5 is the condition being evaluated.
• Since x is 10 , which is indeed greater than 5 , the print statement "x is
greater than 5" is executed.

2. if - else statements
This construct of python program consist of one if condition with two
blocks. When condition becomes true then executes the block given below
it. If condition evaluates result as false, it will executes the block given
below else.

Syntax:
if condition:
# block of code
else:
# block of code
Syntax Explanation:
• After an if statement, you can optionally add an else statement.
• The else block is executed only if the preceding if condition evaluates to
False .
• You cannot have an else statement without an if statement.
• Flowchart

Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

Explanation:
Here, x > 5 evaluates to False because x is 3 .
Therefore, the else block "x is not greater than 5" is executed
Example-1:
Age=int(input(“Enter Age: “))

if ( age>=18):
print(“You are eligible for vote”)
else:
print(“You are not eligible for vote”)

Example-2:
N=int(input(“Enter Number: “))
if(n%2==0):
print(N,“ is Even Number”)
else:
print(N,“ is Odd Number”)
Python Ladder if else statements (if-elif-else)
This construct of python program consist of more than one if condition.
When first condition evaluates result as true then executes the block given
below it. If condition evaluates result as false, it transfer the control at else
part to test another condition. So, it is multi-decision making construct.

Syntax:
if ( condition-1):
# block of code
…………………..
elif (condition-2):
# block of code
…………………..
elif (condition-3):
# block of code
…………………..
else:
…………………..
…………………..

Syntax Explanation:
• You can have multiple elif statements to check additional conditions.
• The elif statements are evaluated sequentially from top to bottom.
• Once a condition evaluates to True , the corresponding block of code is
executed, and subsequent conditions are not checked.
Flowchart:

Example:
x=7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")

Explanation:
Here, x > 10 is False , so it moves to the next elif condition.
x > 5 is True , so "x is greater than 5 but less than or equal to 10" is printed.
Nested if statements
It is the construct where one if condition take part inside of other if
condition. This construct consist of more than one if condition. Block
executes when condition becomes false and next condition evaluates
when first condition became true.
So, it is also multi-decision making construct.

Syntax:
if ( condition-1):
if (condition-2):
……………
……………
else:
……………
……………
else:
…………………..
…………………..
FlowChart

Example:
x = 15
if x > 10:
print("x is greater than 10")
if x > 20:
print("x is also greater than 20")
else:
print("x is not greater than 20")

Explanation:
• In this example, the outer if statement checks if x > 10 .
• If x is indeed greater than 10 , it enters the inner if statement to check
if x >20 .
• Depending on the value of x , different blocks of code are executed
sequentially.
Example:
num=int(input(“Enter Number: “))
if ( num<=0):
if ( num<0):
Print(“You entered Negative number”)
else:
Print(“You entered Zero ”)
else:
Print(“You entered Positive number”)

Output:
Enter Number:4
You entered Positive number
Program:

find largest number out of given three numbers

x=int(input("Enter First Number: "))


y=int(input("Enter Second Number: "))
z=int(input("Enter Third Number: "))
if(x>y and x>z):
largest=x
elif(y>x and
y>z):
largest=y
elif(z>x and
z>y):
largest=z
print("Larest Value in %d, %d and %d is: %d"%(x,y,z,largest)
Iteration Statements
The iteration (Looping) constructs mean to execute the block of
statements again and again depending upon the result of condition. This
repetition of statements continues till condition meets True result. As soon
as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable

while loop
The while loop is conditional construct that executes a block of statements
again and again till given condition remains true. Whenever condition
meets result false then loop will terminate.
Syntax:
Initialization of control variable
while (condition):
…………………..
Updation in control variable
..…………………
Flowchart

Example: print 1 to 10
numbers num=1

# initialization
while(num<=10): # condition testing
print(num, end=” “) #Body of loop
num + = 1 # Increment

Example: Sum of 1 to 10 numbers.


num=1
sum=0
while(num<=10):
sum + = num
num + = 1
print(“The Sum of 1- 10 numbers: “,sum)
Python range( ) Function
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.
The common format of range() is as given below:

range ( start value, stop value, step value )

Where all 3 parameters are of integer type


Start and Step Parameters are
Start value is Lower Limit
Stop value is Upper Limit optional default value will be as
Step value is Increment / Decrement Start=0 and Step=1

Example

range(5) => sequence of 0,1,2,3,4


range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank list (default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0

Example:
L=list(range(1,20,2)
Print(L) Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
For loop
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a string etc.) With for loop we can execute a set of
statements, and for loop can also execute once for each element
in a list, tuple, set etc.
Example: print 1-10 numbers Example: print 10-1
numbers for num in range(1,11,1): for num in range(10,0,-1):
print(num, end=” “) print(num, end=” “)

Output: 1 2 3 4 5 6 7 8 9 10 Output: 10 9 8 7 6 5 4 3 2 1

Print each element in a fruit list:


1 .fruits = ["mango", "apple", "grapes", "cherry"]
for x in fruits:
print(x)

output:
mango Membership Operators:
apple
grapes The “in” and “not in” are membership
cherry operators. These operators check either
[Link] x in "TIGER": given value is available in sequence or
print(x)
not. The “in” operator returns Boolean
output: True result if value exist in sequence
T otherwise returns Boolean False.
I
G The “not in” operator also returns
E
R
Boolean True / False result but it works
opposite to “in” operator.
else in for Loop
The else keyword in for loop specifies a block of code to be executed when the
loop is finished:

for x in range(4):
print(x, end=” “)
else:
print("\nFinally finished!")
output: 0 1 2 3
Finally finished!

Nested Loops
A nested loop is a loop inside another loop.

city = ["Jaipur", "Delhi", "Mumbai"]


fruits = ["apple", "mango",
"cherry"] for x in city:
for y in fruits:
print(x, “:”,y)
output:
Jaipur:apple
Jaipur : mango
Jaipur : cherry
Delhi : apple
Delhi : mango
Delhi : cherry
Mumbai : apple
Mumbai :mango
Mumbai :cherry
Un- Conditional Control Construct
(pass, break, continue, exit(), quit())
pass Statement (Empty Statement)
The pass statement do nothing, but it used to complete the syntax
of programming concept. Pass is useful in the situation where user
does not requires any action but syntax requires a statement. The
Python compiler encounters pass statement then it do nothing but
transfer the control in flow of execution.

a=int(input("Enter first Number: "))


b=int(input("Enter Second Number: "))
if(b==0):
pass
else:
print("a/b=",a/b)

for x in [0, 1, 2]:


pass
Jumping Statements
break Statement
The jump- break statement enables to skip over a part of code that used
in loop even if the loop condition remains true. It terminates to that loop
in which it lies. The execution continues from the statement which find
out of loop terminated by break.

Exit the loop when xis "banana":

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


for x in fruits:
if x=="banana":
break
print(x)
output: apple
Continue Statement
Continue statement is also a jump statement. With the help of
continue statement, some of statements in loop, skipped over and
starts the next iteration. It forcefully stop the current iteration and
transfer the flow of control at the loop controlling condition.
Example:
i=0
while i <=10:
i+=1
if (i%2==1):
continue
print(I, end=” “)
output: 2 4 6 8 10

Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
output:
apple
cherry
UNIT-3
FUNCTIONS AND MODULES
FUNCTIONS:
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that 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
Need for Functions
• Once defined, Python functions can be called multiple times and from any location in a
program.
• Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.
• The ability to return as many outputs as we want using a variety of arguments is one of
Python's most significant achievements.
However, Python programs have always incurred overhead when calling functions

There are three types of functions in Python:


I. Built-in functions The Python interpreter has a number of functions built into it that are
always available. They are listed here in alphabetical order.

II. User-Defined Functions (UDFs):


Following are the rules to define a User Define Function in Python.
• Function begin with the keyword def followed by the function name and parentheses ( ) .
• Any list of parameter(s) or argument(s) should be placed within these parentheses.
• The first statement within a function is the documentation string of the function or docstring
is an optional statement
• The function block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
Syntax
def functionName( list of parameters ):
"_docstring"
function_block
return [expression]

I. Example for Creating a Function without parameter


In Python a function is defined using the def keyword:
>>> def MyMsg1():
print("Learning to create function")

Calling a Function To call a function, use the function name followed by parenthesis:
>>> MyMsg1()
OUTPUT:
Learning to create function

II. Example for Creating a Function parameter


The following function takes a string as parameter and prints it on screen.
def MyMsg2( name ):
"This prints a passed string into this function"
print (name ,’ is learning to define Python Function’)
return

Calling a Function To call a function, use the function name followed by parenthesis:
>>> MyMsg2(‘john’)
OUTPUT:
John is learning to define Python Function
2. Parameter (argument) Passing

III. Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword

x= lambda a,b:a*b
print(x(5, 6)
OUTPUT:
30
FUNCTION DEFINITION
Syntax of function is:

• The start of a capability header is shown by a catchphrase called def.


• function name is the function's name, which we can use to distinguish it from other
functions. We will utilize this name to call the capability later in the program. Name
functions in Python must adhere to the same guidelines as naming variables.
• Using parameters, we provide the defined function with arguments. Notwithstanding,
they are discretionary.
• A colon (:) marks the function header's end.
• We can utilize a documentation string called docstring in the short structure to make
sense of the reason for the capability.
• Several valid Python statements make up the function's body. The entire code block's
indentation depth-typically four spaces-must be the same.
• A return expression can get a value from a defined function.
Example:
def greet():
print('Hello World!')
FUNCTION CALL
Calling a Function To define a function, use the def keyword to give it a name, specify the
arguments it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from anywhere in the
program. An illustration of how to use the a_function can be found below.
EXAMPLE:
def a_function( string ):
"This prints the value of length of string"
return len(string)
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
OUTPUT:
Length of the string Functions is: 9
Length of the string Python is: 6
Function Parameters:
Function arguments are the values or variables passed into a function when it is called. The
behavior of a function often depends on the arguments passed to it.
While defining a function, you specify a list of variables (known as formal parameters) within
the parentheses. These parameters act as placeholders for the data that will be passed to the function
when it is called. When the function is called, value to each of the formal arguments must be provided.
Those are called actual arguments
EXAMPLE
def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return
greetings("Samay")
greetings("Pratima")
greetings("Steven")
OUTPUT
Hello Samay
Hello Pratima
Hello Steven
Local Global Variables:
Python Global variables are those which are not defined inside any function and have a global
scope whereas Python local variables are those which are defined inside a function and their scope is
limited to that function only.
Local variables in Python are those which are initialized inside a function and belong only to
that particular function. It cannot be accessed anywhere outside the function.
def f():
# local variable def f():
s = "I love Geeksforgeeks" # local variable
print(s) s = "I love Geeksforgeeks"
# Driver code print("Inside Function:", s)
f() # Driver code
f()
OUTPUT: I love Geeksforgeeks print(s)

OUTPUT: NameError: name 's' is not defined

Global Variables are those which are defined outside any function and which are accessible
throughout the program, i.e., inside and outside of every function. Let’s see how to create a Python
global variable.
EXAMPLE:
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
OUTPUT
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
THE return STATEMENT
When a defined function is called, a return statement is written to exit the function and return
the calculated value.
Syntax:
return < expression to be returned as output >
The return statement can be an argument, a statement, or a value, and it is provided as output
when a particular job or function is finished. A declared function will return an empty string if no
return statement is written.
Example1:
def square( num ): Example 2:
return num**2 # Defining a function without return
# Calling function and passing statement
arguments. def square( num ):
print( "With return statement" ) num**2
print( square( 8 ) ) # Calling function and passing
arguments.
OUTPUT: print( "Without return statement" )
With return statement print( square( 8 ) )
64 OUTPUT:
Without return statement
None

FUNCTION ARGUMENTS:
The following are the types of arguments that we can use to call a function:
• Default arguments
• Keyword arguments
• Required arguments
• Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no
worth is provided for the contention when the capability is called. The following example
demonstrates default arguments.

Example:
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Passing only one argument" )
function(30)
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a
capability with watchword contentions, the client might tell whose boundary esteem it is by looking at
the boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python
translator will interface the furnished watchwords to connect the qualities with its boundaries. One
more method for utilizing watchwords to summon the capability() strategy is as per the following:
Example:
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Without using keyword" )
function( 50, 30)
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined
positional sequence. The number of arguments required in the method call must be the same as those
provided in the function's definition.
We should send two contentions to the capability() all put together; it will return a language
structure blunder, as seen beneath.
Example:
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
print( "Passing out of order arguments" )
function( 30, 20 )

print( "Passing only one argument" )


try:
function( 30 )
except:
print( "Function needs two positional arguments" )
Output:
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However,
we need a capability. This can be accomplished with one of two types of characters:"args" and
"kwargs" refer to arguments not based on [Link] help you understand arguments of variable
length, here's an example.
Example:
def function( *args_list ):
ans = []
for l in args_list:
[Link]( [Link]() )
return ans
object = function('Python', 'Functions', 'tutorial')
print( object )
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
[Link]([key, value])
return ans
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
RECURSION:
Any function that calls itself in its body repeatedly until a particular condition becomes false
and the target task is done is called a "Recursive function" and this procedure is called "Recursion".
When do we need to recurse a function?
When we want to perform a complex task, we generally break it into smaller tasks; doing them
one after the other decreases the burden and the complexity. Just like this, when we need to write a
code for a complex problem, we break it into smaller and repetitive parts.
Example:
def fact(num): print("The factorial of the given
if num == 1: number", num, "is", result)
return 1 Output:
else: Enter a number: 5
return (num * fact(num-1)) The factorial of the given number
num = int(input("Enter a number: ")) is 120
result = fact(num)

PYTHON STRINGS:
String is a data structure in Python Programming that represents a sequence of characters. It
is an immutable data type, meaning that once you have created a string, you cannot change it. Python
String are used widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
String Operations:
String Concatenation:
The + operator adds the multiple strings together. Strings must be assigned to the different
variables because strings are immutable. Let's understand the following example.
Example:
str1 = "Hello "
str2 = "Coders"
str3 = str1 + str2
print("The new combined string is:",str3)
Output:
The new combined string is: Hello Coders
String Appending:
Append means to add something at the [Link] python you can add one string at the end of
another string using the += operator.
Example:
Str=”Hello,”
name=input(“\n Enter your name:”)
str+=name
str+=”.Welcome to Python Programming.”
Print(str)
Output:
Enter your name:Mani
Hello,Mani. Welcome to Python Programming.
String Repeating:
The * operator used to repeat the string n number of times
Example:
Str=”Hello”
Print(str*3)
Output:
Hello Hello Hello
STRINGS ARE IMMUTABLE:
Since strings in Python are immutable data structures, we cannot add or edit any data. We
encountered warnings stating that strings are not changeable when modifying any section of the
[Link] is an illustration of that:
Example: 3 string = 'hello world'
string = 'hello world' 4
string[0] = 'X' ----> 5 string[0] = 'X'
print(string) 6
7 print(string)
Output: TypeError: 'str' object does not support item
TypeError Traceback (most recent call last) assignment
<ipython-input-3-4e0fff91061f>in <module>

BUILT IN STRING METHODS AND FUNCTIONS:


String Comparision:
Python has a number of operators and techniques for comparing strings, each with a specific
[Link] relational operators compare the Unicode values of the characters of the strings from the
zeroth index till the end of the string. It then returns a boolean value according to the operator used. It
checks Python String Equivalence.
Example:
print("Geek" == "Geek") Output
print("Geek" < "geek") True
print("Geek" > "geek") True
print("Geek" != "Geek") False
False
MODULES:
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code. Grouping related code into
a module makes the code easier to understand and use. It also makes the code logically organized
CREATE A PYTHON MODULE
To create a Python module, write the desired code and save that in a file with .py extension.
Let’s understand it better with an example:
Example:
Let’s create a simple [Link] in which we define two functions, one add and another subtract.
# A simple module, calc.p
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
IMPORT MODULE IN PYTHON
We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a module.
For example, to import the module [Link], we need to put the following command at the top of
the script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the module only.
To access the functions inside the module the dot(.) operator is used.
Example:
# importing module [Link]
import calc
print([Link](10, 2))
Python Import From Module
Python’s from statement lets you import specific attributes from a module without importing
the module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))

Output:
4.0
720
The dir() Built-in Function
We may use the dir() method to identify names declared within a module.
For instance, we have the following names in the standard module str. To print the names, we
will use the dir() method in the following way:
Example:
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Output:
List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
MODULES AND NAMESPACES:

In Python, everything is an object like variable, function, etc. A name is nothing but something that we
use to refer to an object. It is also called an identifier.
For example, in the code below, ‘text’ is an identifier to the variable that stores ‘PythonGeeks’.

Example of name in Python:


text="PythonGeeks"
To check if the ‘text’ variable stores “PythonGeeks” , we can see the address in which they are stored in
the memory. We can use the built-in function ‘id()’ for this purpose.

Example of memory allocation while variable changes:


name="Python"
print("id of name:",id(name))
print("id of Python:",id("Python"))
name ="PythonGeeks"
print("id of name:",id(name))
print("id of PythonGeeks:",id("PythonGeeks"))
text="Python"
print("id of text:",id(text))
print("id of Python:",id("Python"))
Output:
id of name: 2786126438960
id of Python: 2786126438960
id of name: 2786161874800
id of PythonGeeks: 2786161874800
id of text: 2786126438960
id of Python: 2786126438960

• local and global namespace variables can be accessed by a Python statement. When two
variables with the same name are local and global, the local variable takes the role of the
global variable. There is a separate local namespace for every function.
• The scoping rule for class methods is the same as for regular functions. Python
determines if parameters are local or global based on reasonable predictions.
• Any variable that is allocated a value in a method is regarded as being local.
• Therefore, we must use the global statement before we may provide a value to a global
variable inside of a function.
• Python is informed that Var_Name is a global variable by the line global Var_Name.
Python stops looking for the variable inside the local namespace.
• We declare the variable Number, for instance, within the global namespace. Since we
provide a Number a value inside the function, Python considers a Number to be a local
variable.
• UnboundLocalError will be the outcome if we try to access the value of the local variable
without or before declaring it global.
Example:
Number = 204
def AddNumber():
Number = Number + 200
print("The number is:", Number)
AddNumber()
print("The number is:", Number)
Output:
The number is: 204
The number is: 40
a. Built-in Namespace in Python
This namespace gets created when the interpreter starts. It stores all the keywords or the built-
in names. This is the superset of all the Namespaces. This is the reason we can use print, True, etc.
from any part of the code.

b. Python Global Namespace


This is the namespace that holds all the global objects. This namespace gets created when the
program starts running and exists till the end of the execution.
Example of Global Namespace in Python:
text="PythonGeeks"
def func():
print(text)
func()
print(text)
Output:
PythonGeeks
PythonGeeks
We can see that we can access the variable ‘text’ from any part of the program. This is a global
variable and exists in the global namespace.

c. Python Local Namespace


This is the namespace that generally exists for some part of the time during the execution of the
program. This stores the names of those objects in a function. These namespaces exist as long as the
functions exist. This is the reason we cannot globally access a variable, created inside a function.
Example of local namespace:
var1="PythonGeeks"
def func():
var2="Python"
print(var2)
func()
Output:
Python
Here the local namespace is created when the ‘func()’ is called and stores ‘var2’. This
namespace gets deleted when the use of ‘func()’ is done. Because of this when we try to access ‘var2’
outside, globally, we get an error as shown below-
Example that shows we cannot access local variable globally:
print(var2)
Output:
Traceback (most recent call last):
File “<pyshell#7>”, line 1, in <module>
print(var2)
NameError: name ‘var2’ is not defined

Example of using same name for global and local variable:


var= "PythonGeeks"
def func():
var="Python"
print(var)
func()
print(var)

Output:
Python
PythonGeeks
When we print ‘var’ inside the function we could see the changed value but couldn’t observe the
same outside the function. This is because the local namespace is isolated and creates its own variable
‘var’.
To avoid this we can use the keyword ‘global’ inside the function for the ‘var’.
Look at the below results.

Example on use of ‘global’ keyword:


var="PythonGeeks"
def func():
global var
var="Python"
print(var)
func()
print(var)

Output:
Python
Python
The use of global keywords tells the interpreter to use the global variable, rather than creating
its own. This makes us observe the changes globally.
The same concept applies to nested functions, a local namespace exists separately for that
function. And it exists only during the function’s execution.

DEFINING OUR OWN MODULE


Consider a module to be the same as a code library.A file containing a set of functions you want
to include in your [Link] this code in the file [Link]
EXAMPLE:
person1 = { "name": "John", "age": 36, "country": "Norway"}

import mymodule
a = mymodule.person1["age"]
print(a)

OUTPUT:36
UNIT IV
List
Definition:
✓ A list is a built-in dynamic sized array (automatically grows and shrinks).
✓ We can store all types of items (including another list) in a list.
✓ A list may contain mixed type of items, this is possible because a list
mainly stores references at contiguous locations and actual items maybe
stored at different locations.
✓ List can contain duplicate items.
✓ List in Python are Mutable. Hence, we can modify, replace or delete the
items.
✓ List are ordered. It maintain the order of elements based on how they are
added.
✓ Accessing items in List can be done directly using their position (index),
starting from 0.

Example:
# Creating a Python list with different data types
a = [10, 20, "GfG", 40, True]
print(a)

# Accessing elements using indexing


print(a[0]) # 10
print(a[1]) # 20
print(a[2]) # "GfG"
print(a[3]) # 40
print(a[4]) # True

# Checking types of elements


print(type(a[2])) # str
print(type(a[4])) # boolAccess Items
Explanation:
• The list contains a mix of integers (10, 20, 40), a string ("GfG") and a boolean
(True).
• The list is printed and individual elements are accessed using their indexes
(starting from 0).
• type(a[2]) confirms "GfG" is a str.
• type(a[4]) confirms True is a bool.

Creating a List

Using Square Brackets


# List of integers
Output
a = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
# List of strings
['apple', 'banana', 'cherry']
b = ['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
# Mixed data types
c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)
Using list() Constructor
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)

Output:
[1, 2, 3, 'apple', 4.5]

Accessing List Elements

Elements in a list can be accessed using indexing.


Python indexes start at 0, so a[0] will access the first element, while negative
indexing allows us to access elements from the end of the list. Like index -1
represents the last elements of list.

Example:
a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])
Output
10
50
Updating List Values
Due to their mutability and the slice and assignment operator's ability
to update their values, lists are Python's most adaptable data structure.
Python's append() and insert() methods can also add values to a list.
Consider the following example to update the values inside the List.
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)

# It will assign value to the value to the second index


list[2] = 10
print(list)

# Adding multiple-element
list[1:3] = [89, 78]
print(list)

# It will add value at the end of the list


list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Delete List Values
The list elements can also be deleted by using the del keyword. Python also
provides us the remove() method if we do not know which element is to be deleted
from the list.
Consider the following example to delete the list elements.
list = [1, 2, 3, 4, 5, 6]
print(list)

# It will assign value to the value to second index


list[2] = 10
print(list)

# Adding multiple element


list[1:3] = [89, 78]
print(list)

# It will add value at the end of the list


list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed
on different occasions.
Code
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code:
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
[Link]
The len() function returns the number of elements in the list.
Code:
# Example of length
my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)
print(list_length)

Output: 5

[Link]
Iteration involves looping through the elements of a list.
Code:
# Example of iteration
my_list = ['apple', 'banana', 'cherry']
for item in my_list:
print(item)
Output:
apple
banana
cherry

[Link]
Membership checks if an element is present in the list.
# Example of membership
my_list = [10, 20, 30, 40]
is_present = 20 in my_list
print(is_present)

Output: True

is_present = 50 in my_list
print(is_present)

Output: False

List methods:
The list data type has some more methods. Here are all of the methods of list
objects:
• Del()
• Append()
• Extend()
• Insert()
• Remove()
• Reverse()
• Sort()
Delete:
Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x [5, 8, 6] ------------
>>> del(x)
>>> x # complete list gets deleted
Append:
Append an item to a list
>>> x=[1,5,8,4]
>>>[Link](10)
>>> x [1, 5, 8, 4, 10]
Extend:
Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>[Link](y)
>>> x [1, 2, 3, 4, 3, 6, 9, 1]
Insert:
To add an item at the specified index, use the insert () method
>>> x=[1,2,4,6,7]
>>>[Link](2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
Remove:
The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>>[Link](33)
>>> x
[1, 2, 10, 4, 6]
>>>[Link](4)
>>> x
[1, 2, 10, 6]
Reverse:
Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>>[Link]()
>>> x
[7, 6, 5, 4, 3, 2, 1]

Sort:
Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>>[Link]()
>>> x
[1, 2, 3, 4, 5, 6, 7]

Tuple:
✓ A comma-separated group of items is called a Tuple .Tuples are used to store
multiple items in a single variable.
✓ Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities and
usage.
✓ A tuple is a collection which is ordered and unchangeable.
✓ Tuples are written with round brackets ( ) .
✓ The main difference between the two is that we cannot alter the components
of a tuple once they have been assigned. On the other hand, we can edit the
contents of a list.
Create a List of Tuples
• Use parentheses () to create a tuple and separate elements with commas.
• Tuples can also be created without parentheses.
Example:
# This is a tuple with parentheses
my_tuple = (1, 2, 3)
# This is also a triple, which is just a tuple with exactly three items
my_triple = (1, 2, 3)
# This is a tuple without parentheses (Python allows this)
another_tuple = 4, 5, 6
print(type(my_tuple)) # <class 'tuple'>
print(type(my_triple)) # <class 'tuple'>
print(type(another_tuple)) # <class 'tuple'>

EXAMPLE:
Creating tuples
tuple1 = (1, 2, 3, 4)
tuple2 = (1,3.14)
tuple3 = (1,) # A tuple with one element (note the comma)
# Tuple without parentheses
tuple4 = 1, 2, 3, 4
# Accessing elements
print(tuple1[0]) # Output: 1
print(tuple2[1]) # Output: hello
# Slicing
print(tuple1[1:3]) # Output: (2, 3)
output:
('apple', 'banana', 'cherry')
Access Tuple Items
You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
Thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
output:
banana

Updating Tuples:
Tuples are immutable which means you cannot update or change the values
of tuple elements. You are able to take portions of existing tuples to create new
tuples as the following example demonstrates
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# tup1[0] = 100; # This action is not valid for tuples
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)
When the above code is executed, it produces the following
result − (12, 34.56, 'abc', 'xyz')

Delete Tuple Elements:


Removing individual tuple elements is not possible. To explicitly remove an entire
tuple, just use the del statement. For example –
tup = ('physics', 'chemistry', 1997, 2000);
print tup
del tup;
print "After deleting tup : “, tup
This produces the following result. Note an exception raised, this is because after
del tup tuple does not exist any more –
('physics', 'chemistry', 1997, 2000)
Traceback (most recent call last):
File "[Link]", line 8, in
print "After deleting tup : “, tup;
NameError: name 'tup' is not defined
Basic Tuples Operations:
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple, not a
string. In fact, tuples respond to all of the general sequence operations we used on
strings
Nested Tuples in Python
A nested tuple is a Python tuple that has been placed inside of another tuple.
Let's have a look at the following 8-element tuple.

1. tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is
known as a nested tuple since it is contained inside another tuple. The name of the
main tuple with the index value, tuple[index], can be used to obtain the nested tuple,
and we can access each item of the nested tuple by using tuple[index-1][index-2].
Example of a Nested Tuple
# Python program to create a nested tuple

# Creating a nested tuple of one element only


employee = ((10, "Raj", 13000),)
print(employee)

# Creating a multiple-value nested tuple


employee = ((10, "Raj", 13000), (24, "Harry", 15294), (15, "Nila", 20001), (40, "Pe
ter", 16395))
print(employee)

(10, 'Raj', 13000),)


((10, 'Raj', 13000), (24, 'Harry', 15294), (15, 'Nila’, 20001), (40, 'Peter', 16395))

Differences between List and Tuple in Python

S,no LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


2
consuming comparatively Faster
S,no LIST TUPLE

The list is better for performing


A Tuple data type is appropriate
3 operations, such as insertion and
for accessing the elements
deletion.

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many


5 Lists have several built-in methods
built-in methods.

Unexpected changes and errors are Because tuples don’t change


6
more likely to occur they are far less error-prone.

Dictionary
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.

The data is stored as key-value pairs using a Python dictionary.

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be
any Python object. The keys, in contrast, are immutable Python objects, such as
strings, tuples, or numbers.

dict = {'Alice': '2341', 'Arun': '9102', 'Raj': '3258'}


You can create dictionary in the following way as well:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
Each key is separated from its value by a colon(:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in curly
brackets and a colon separating each key from its value, the dictionary can be built.
(:). The following provides the syntax for defining the dictionary
Syntax:

1. Dict = {"Name": "Ravi", "Age": 25}


In the above dictionary Dict, The keys Name and Age are the strings which comes
under the category of an immutable object.

Accessing Values in Dictionary:


To access dictionary elements, you can use the familiar square brackets along with
the key to obtain in its value.
Following is a simple example:
dict = {'Name': 'abi', 'Age': 7, 'Class': 'First'}
print (dict['Name']: ", dict['Name'])
print (dict['Age']: ", dict['Age'])
When the above code is executed, it produces the following result:
dict['Name']: abi
dict['Age']: 7

Updating Dictionary:
You can update a dictionary by adding a new entry or item(i.e., a key-value pair),
modifying an existing entry, or deleting an existing entry as shown below in the
simple example:
dict = {'Name': 'abi', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print (dict['Age']: ", dict['Age'])
print (dict['School']: ", dict['School'])
When the above code is executed, it produces the following result:
dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements:


You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a sing le operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example:
dict = {'Name': 'abi', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
[Link](); # remove all entries in dict
del dict ; # delete entire dictionary
print (“dict['Age']: ", dict['Age'])
print (“dict['School']: ", dict['School'])
This will produce the following result. Note anexceptionraised, this is
because after del dict dictionary does not exist any more:
dict['Age']:
Trace back (most recent call last):
File "[Link]", line 8, in <module>
print (“dict['Age']: ", dict['Age'])
Type Error: 'type' object is un subscript able
Dictionary Function and Methods
Python has some built-in methods that dictionary objects can call. Some of
them are describe below
len()
(i)
This method is used to return the total length of the dictionary.
Syntax
len(dictionary_name)
For example,
dic ={1 : "This", 2 : "That", 3 : "The", 4 : "World"}
print(len (dic)) OUTPUT: 4
del dic[2]
print(len (dic)) OUTPUT: 3

dic[5]="Hello"
dic[6]="Wonder"
print(len (dic))
print(dic)

OUTPUT:
4
3
5
{1: 'This', 3: 'The', 4: 'World', 5: 'Hello', 6: 'Wonder'}

clear()
(ii)
This method is used to remove the elements of the dictionary. It produces
an empty dictionary. It will only delete elements not a dictionary. It does not
take any parameter and does not return any value.
Syntax
dictionary_name.clear()
For example,
>>>dic1 ={“Project” : “All In One”, “Days” : 15, “Level” : “High”}
>>>[Link]()
>>>dic1
{}
If you want to delete the dictionary with its elements, then del keyword is
used.
>>>dic1 {“Project” : “All in One”, “Days” : 15, “Level” : “High”}

>>>del dic1
>>>dic1
Trackback (most recent call last) :
File “<pyshell#5>”, line1, in <module> dic1
NameError : name ‘dic1’ is not defined

(iii)get()
This method returns the value for the given key, if present in the dictionary. It
takes maximum of two parameters.
Syntax
dictionary_name.get (Key[, value])
Here, Key to be searched in the dictionary value (optional) value to be returned if
the key not found. The default value is None.
For example,
>>>Student {‘Name’: ‘Siva’, ‘Roll No’: 21, ‘Marks’: 459, ‘Class’: 12}
>>>Student {‘Class’ : 12, ‘Roll No’ : 21, ‘Marks’ : 459, ‘Name’ : ‘Siva’}
>>>[Link] (‘Name’) ‘Siva’
>>>[Link] (‘Age’, ‘Not Found’) ‘Not Found’
>>>[Link] (‘Marks’, ‘Not Found’) 459
(iv)values ( )
This method returns a view object that displays a list of all the values in the
dictionary. It does not take any parameters.
Syntax
dictionary_name.values ()
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000,
‘Experience’ : 4}
>>>[Link]()
dict_values([28000, ‘Science’, ‘4’, ‘Akshat’])

(v) update ( )
This method updates the dictionary with the elements from the another
dictionary object or from an iterable of key/value pairs.
Syntax
dictionary_name1.update (dictionary_name2)
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000}

>>>Teacher1 {‘Name’ : ‘Akansha’, ‘Salary’ : 25000, ‘Experience’ : 5}


>>>[Link](Teacher1)
>>>Teacher
(‘Salary’ : 25000, ‘Subject’, ‘Science’, ‘Experience’ : 5, ‘Name’ :
Akansha}

(vi) sorted ()
This method returns a sorted sequence of the keys in the dictionary.
Syntax
sorted (dictionary_name)
For example,
>>>Teacher {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, ‘Salary’ : 28000,

‘Experience’ : 4}
>>>sorted(Teacher)
[‘Experience’, ‘Name’, ‘Salary’, ‘Subject’]
(vii)copy()
This method returns a shallow copy of the dictionary.
Syntax
[Link]( )
Here, copy( ) method does not take any parameters.
For example,
dic = {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’} dic1 = dic. copy ( )
print (‘Original dictionary : ’, dic) print (‘Copied
dictionary : ’, dic1)
Output
Original dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’}
Copied dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’}

(viii)pop item ()
This method in dictionary helps to achieve similar purpose. It removes the
arbitrary key value pair from the dictionary and returns it as a tuple. There is an
update for this method from Python version 3.7 onwards.
Syntax
[Link]( )
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} print (‘Before
deletion : ’, dic)
dic1 = [Link] ( )
print (‘Deleted element’, dic1) print (‘After deletion :’,
dic)
Output
Before deletion : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} Deleted element :
(‘Shrey’, : 27)
After deletion : {‘Akshat’ : 26, ‘Riya’ : 24}

(ix) max ()
This method is used to return the maximum key from the dictionary.
Syntax
max(dict)
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} dic1 = max(dic)
print (‘Dictionary : ’, dic) print (‘Maximum key : ’,
dic1)
Output
Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Maximum key : Shrey

(x) min ()
This method is used to return the minimum key from the dictionary.
Syntax
min(dict)
For example,
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} dic1 = min(dic)
print (‘Dictionary :’, dic) print (‘Minimum key :’,
dic1)
Output
Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Minimum key : Akshat

Difference Between List and Dictionary in Python

Parameter List Dictionary


An ordered collection of An unordered collection of data in a
Definition
items. key: value pair form.
Syntax Uses square brackets []. Uses curly braces {}.
Ordered: Items have a defined Unordered: Items do not have a
Ordering
order, which will not change. defined order.
Accessed by index, starting
Indexing Values are accessed using keys.
from 0.
Mutable: Values can be updated, and
Mutable: Items can be
Mutability key: value pairs can be added or
modified after creation.
removed.
Does not allow duplicate keys.
Uniqueness Allows duplicate items.
However, values can be duplicated.
Keys can be of any immutable data
Data Types It can store any data type. type (e.g., strings, numbers, tuples).
Values can be of any type.
When order matters or when
When you need a unique key for each
Use Case you need to store multiple
piece of data.
values for an item.
fruits = [“apple”, “banana”,
Example person = {“name”: “John”, “age”: 30}
“cherry”]
Built-in append(), remove(), pop(), keys(), values(), items(), get(), pop(),
Functions sort(), etc. etc.
Faster for ordered operations Faster for lookup operations due to the
Performance
like sorting. hash mapping of keys.
File Handling
 File handling in Python involves interacting with files on your computer to read data
from them or write data to them.
 Python provides several built-in functions and methods for creating, opening, reading,
writing, and closing files.

1. Introduction to Files:
 When a program is being executed, its data is stored in RAM. Though
RAM can be accessed faster by the CPU,it is also volatile, which means
when the program ends, or the computer shuts down, all the data is lost. If
you want to use the data in future,then you need to store this data on a
permanent or non- volatile storage media such as hard disk, USB drive
and DVD etc,
 A file is a collection of data stored on a secondary storage device like hard
disk.
 A file is basically used because real-life applications involve large
amounts of data and in such situations the console oriented I/O
operations pose two major problems:
 First, it becomes cumbersome and time consuming to handle huge
amount of data through terminals.
 Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off. Therefore, it
becomes necessary to store data on a permanent storage (the disks) and
read whenever necessary, without destroying the data.
2. File Types
 Like C and C++,Python also supports two types of files
1. ASCII Text Files
2. Binary Files
[Link] Text Files
 A text file is a stream of characters that can be sequentially
processed by a computer in forward direction. For this reason a
text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time.
 Because text files can process characters, they can only read or
write data one character at a time. In Python, a text stream is
treated as a special kind of file.
 Depending on the requirements of the operating system and on the
operation that has to be performed (read/write operation) on the file,
the newline characters may be converted to or from carriage-
return/linefeed combinations.
 Besides this, other character conversions may also be done to
satisfy the storage requirements of the operating system.
However, these conversions occur transparently to process a text
file. In a text file, each line contains zero or more characters and
ends with one or more characters.
 Another important thing is that when a text file is used, there are
actually two representations of data- internal or external.
 For example, an integer value will be represented as a number that
occupies 2 or 4 bytes of memory internally but externally the
integer value will be represented as a string of characters
representing its decimal or hexadecimal value.
Note: In a text file, each line of data ends with a newline character. Each file
ends with a special character called end-of-file (EOF) Marker.
2.2 Binary Files
 A binary file is a file which may contain any type of data, encoded in
binary form for computer storage and processing purposes. It includes
files such as word processing documents, PDFs, images, spreadsheets,
videos, zip files and other executable programs.
 Like a text file, a binary file is a collection of bytes. A binary file is
also referred to as a character stream with following two essential
differences.
 A binary file does not require any special processing of the data and
each byte of data is transferred to or from the disk unprocessed.
 Python places no constructs on the file, and it may be read from, or
written to, in any manner the programmer wants.
 While text files can be processed sequentially, binary files, on the
other hand, can be either processed sequentially or randomly
depending on the needs of the application.

Note: Binary files store data in the internal representation


[Link], an integervalue will be stored in binary form as 2 byte
[Link] same format is used to store data in memory as well as in
[Link] Text files,Binary files also ends with an EOF Marker
3. File
Path:
 Files that we use are stored on a storage medium like the hard disk in
such a way that they can be easily retrieved as and when required.
 Every file is identified by its path that begins from the root node or the
root folder. In Windows, C:\ (also known as C drive) is the root folder
but you can also have a path that starts from other drives like D:\, E:\,
etc. The file path is also known as pathname.
 In order to access a file on a particular disk we have two paths.
1. Absolute Path
2. Relative Path

 While an absolute path always contains the root and the complete
directory list to specify the exact location the file.
Example:To access BTech_CS.docx,The absolute path
is C:\Students\Under Graduate\BTech_CS.docx
 Relative path needs to be combined with another path in order to
access a file. It starts with respect to the current working directory and
therefore lacks the leading slashes.
Example: Suppose you are working on current directory Under Graduate in
order to access BTech_CS.docx,The Relative path is
Under Graduate\BTech_CS.docx
4. File Operations

 When we want to read from or write to a file we need to open it first.


When we are done, it needs to be closed, so that resources that are tied
with the file are freed.
 Python has many in-built functions and methods to manipulate
[Link]
 Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
4.1 Opening A File
 Before reading from or writing to a file, you must first open it using
Python‟s built-in open() function. This function creates a file object,
which will be used to invoke methods associated with it.

The Syntax of open() is:


fileObj = open(file_name [, access_mode])

Where file_name is a string value that specifies name of the file that you
want to access. access_mode indicates the mode in which the file has to be
opened, i.e., read, write, append, etc.
 Example:Write a Program to print the details of file object

Note:Access mode is an optional parameter and the default file access


mode is read(r).
Access modes
 Python supports the following access modes for opening a file those are :

The File Object Attributes


 Once a file is successfully opened, a file object is returned. Using this
file object, you can easily access different type of information related
to that file. This information can be obtained by reading values of
specific attributes of the file.
 The Following table shows list attributes related to file object.
 Example: Program to open a file and print its attribute values.
Closing A File
 The close() method is used to close the file object. Once a file object
is closed, you cannot further read from or write into the file
associated with the file object.
 While closing the file object the close() flushes any unwritten
information. Although, Python automatically closes a file when the
reference object of a file is reassigned to another file, but as a good
programming habit you should always explicitly use the close()
method to close a file.

 The syntax of close() is


[Link]()

 The close() method frees up any system resources such as file


descriptors, file locks, etc. that are associated with the file.
 Once the file is closed using the close() method, any attempt to use
the file object will result in an error.
Example2: Write a Python program to assess if a file is closed or not..
file = open('[Link]','wb')
print('Name of the file:',[Link])
print('File is closed:',[Link])
print('File is now being closed')
[Link]()
print('File is closed',[Link])
print([Link]())
Output:
Name of the file :
[Link] File is closed:
False
File is now being
closed File is closed
True
Traceback (most recent call last):
File "D:/Python/[Link]", line 7, in
<module> print([Link]())
[Link]: read

Writing A File
 The write() method is used to write a string to an already opened file.
Of course this string may include numbers, special characters or other
symbols.
 While writing data to a file, you must remember that the write()
method does not add a newline character ('\n') to the end of the string.

 The syntax of write() method is:


[Link](string)

Example:Program that writes a message in the file,[Link]


file=open('[Link]','w')
[Link]('hello cse we are learning python
programming') [Link]()
print('file writing successful') [Link]
Output:
hello cse we are learning python programming
file writing successful

writeline() method:
 The writelines() method is used to write a list of strings.
Example:Program to write to afile using the writelines()
method
file=open('[Link]','w')
lines=['hello','cse','hope to enjoy','learning','python programming']
[Link](line)
[Link]()
print('file writing
successful') [Link]

hello cse hope to enjoy learning python programming


Output:
file writing successful

append() method:
 Once you have stored some data in a file,you can always open that file
again to write more data or append data to it.
 To append a file, you must open it using „a‟ or „ab‟ mode depending on
whether it is text file or binary file.
 Note that if you open a file with „w‟ or „wb‟ mode and then start writing
data into it, then the existing contents would be overwritten.
Example:Program to append data to an already existing file
file=open('[Link]','a')
[Link]('\nHave a nice day')
[Link]()
print('Data appended successful')
Output:
Data appended successful
[Link]

hellocsehope to enjoylearningpython programming

4.2 Reading A File Have a nice day


 The read() method is used to read a string from an already opened
[Link] said before, the string can include, alphabets, numbers,
characters or other symbols.

 The syntax of read() method is


[Link]([count])

Where In the above syntax, count is an optional parameter which if passed to


the read() method specifies the number of bytes to be read from the opened file.
 The read() method starts reading from the beginning of the file and if
count is missing or has a negative value then, it reads the entire contents
of the file (i.e., till the end of file).
Example1:Program to print the first 8 characters of the file [Link]
file=open('[Link]','r
[Link]
') print([Link](8))
[Link]() hellocsehope to enjoylearningpython programming
Output:
hellocse Have a nice day
Example2:Program to display the content of file using for loop
file=open('[Link]','r
') for line in file: [Link]
print(line) hellocsehope to enjoylearningpython programming
[Link]()
Output: Have a nice day
hellocsehope to enjoylearningpython programming
Have a nice day
Note:read() methods returns a newline as „\n‟
4.4.1 readline() Method
 It is used to read single line from the file.
 This method returns an empty string when end of the file has been
reached.
ExampleProgram to demonstrate the usage of readline() function
file=open('[Link]','r')
print('firtsline:',[Link]()
) print('second [Link]
line:',[Link]()) hellocsehope to enjoylearningpython programming
print('third
line:',[Link]()) Have a nice day
[Link]()
Output:
firtsline: hellocsehope to enjoylearningpython
programming second line: Have a nice day
third line:

readlines() Method
 readlines() Method is used to read all the lines in the file.
Example:Program to demonstrate readlines() function
file=open('[Link]','r')
print([Link]()) [Link]
[Link]() hellocsehope to enjoylearningpython
Output:
programming
['hellocsehope to enjoylearningpython Have a nice day'Have a nice day']
programming\n',

list() Method
 list() method is also used to display entire contents of the [Link] need
to pass the file object as an argument to the list() method.
Example: Program to display the contents of the file [Link] using the
list() method
[Link]
file=open('[Link]','r')
print(list(file)) hellocsehope to enjoylearningpython
[Link]()
programmingHave a nice day
Output:
['hellocsehope to enjoylearningpython programming\n', 'Have a nice day']

Opening a file using with keyword:


 It is good programming habit to use the with keyword when working
with file objects.
 This has the advantage that the file is properly closed after it is used even if
an error occurs during read or write operation or even when you forget to
explicitly close the file.
Note: When you open a file for reading, or writing, the file is searched in the
current directory. If the file exists somewhere else then you need to specify
the path of the file.

Splitting Words:
 Python allows you to read line(s) from a file and splits the line
(treated as a string) based on a character. By default, this character
is space but you can even specify any other character to split words
in the string.
Example: Program to split the line into series of words and use space to
perform the split operation
with open('[Link]','r') as [Link]
file: line=[Link]()
words=[Link]() hellocsehope to enjoylearningpython programming
print(words)
Output:

['hellocsehope', 'to', 'enjoylearningpython', 'programming']


Some Other Useful File Methods:
 The following are some of additional methods which will work on files
.
4.3 File Positions:
 With every file, the file management system associates a pointer often
known as file pointer that facilitates the movement across the file for
reading and/ or writing data.
 The file pointer specifies a location from where the current read or
write operation is initiated. Once the read/write operation is completed,
the pointer is automatically updated.
 Python has various methods that tells or sets the position of the file
pointer.
 For example, the tell() method tells the current position within the file at
which the next read or write operation will occur. It is specified as
number of bytes from the beginning of the file.
 When you just open a file for reading, the file pointer is positioned at
location 0, which is the beginning of the file.

 The syntax for seek() function is


seek(offset[, from])

 The offset argument indicates the number of bytes to be moved and


the from argument specifies the reference position from where the bytes
are to be moved.
Example: Program that tells and sets the position of file pointer
[Link]
Hello All,
Hope you are enjoying learning python

Renaming and Deleting Files:


 The os module in Python has various methods that can be used to
perform file- processing operations like renaming and deleting files. To
use the methods defined in the os module, you should first import it in
your program then call any related functions.
 The rename() Method: The rename() method takes two arguments, the
current filename and the new filename.
Its syntax is: [Link](old_file_name, new_file_name)
 The remove() Method: This method can be used to delete file(s). The
method takes a filename (name of the file to be deleted) as an
argument and deletes that file.
Its syntax is: [Link](file_name)
Example: Program to rename file ‘[Link]’ to ‘[Link]’

Example: Program to delete a file named [Link]

5. Typesof Arguments
5.1 Command line Arguments:
The Python sys module provides access to any command-line
arguments via the [Link]. This serves two purposes −
 [Link] is the list of command-line arguments.
 len([Link]) is the number of command-line arguments.
Here [Link][0] is the program ie. script name.
Example1:Write a Python program to demonstrate the usage of Command
Line Arguments
[Link]
#!/usr/bin/python
import sys
print ('Number of arguments:', len([Link]),
'arguments.') print ('Argument List:', str([Link]))
Output:

Example2: Write a Python program to copy the content of one file to


another using command line arguments.
[Link] [Link]
#!/usr/bin/python Hello hi
How are you
import sys
print ('Number of arguments:', len([Link]),
'arguments.') with open(str([Link][1])) as f:
with open(([Link][2]), "w") as
[Link]
f1: for line in f:
Hello hi
[Link](line) How are you
print('File Copied Success')

6. File Handling Programs


1. Write a program to print each line of a file in reverse
order Program:
with open('[Link]','r') as fp: [Link]
for line in fp: Hello hi
print (line[::-1]) How are you
Output:
ih olleH
uoy era woH
2. Write a program to compute the number of characters, words and
lines in a file
Program:
fname = "[Link]"
num_lines = 0 [Link]
num_words = 0
hellocsehope to enjoylearningpython programming
num_chars = 0
with open(fname, 'r') as f: Have a nice day
for line in f:
words = [Link]()
num_lines += 1
num_words += len(words)
num_chars += len(line)
print('The no of lines in a given file is',num_lines)
print('The no of words in a given file is',num_words)
print('The no of chars in a given file is',num_chars)

Output:
The no of lines in a given file is
2
The no of words in a given file is
8
The no of chars in a given file is
63

[Link] a program to copy contents of one file to


another file Program:
with open("[Link]") as f:
with open("[Link]", "w") as
f1: for line in f:
[Link](line)
Output:

[Link]

hellocsehope to enjoylearningpython programming

Have a nice day


[Link]

hellocsehope to enjoylearningpython programming

Have a nice day

4. Write a Python Program to count number of Vowels and Number


of Consonants in a given file.(November 2018 Supplementary)
Program:
infile = open("[Link]", "r")
vowels = set("AEIOUaeiou")
cons=set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRST
VWXYZ")
countV = 0
countC = 0
for c in
[Link]():
if c in vowels:
countV +=1
elif c in cons:
countC += 1
print("The no of Vowels are",countV)
print("The no of Consonants are",countC)

Common questions

Powered by AI

Python handles absolute paths by specifying the complete directory list from the root to the target file, ensuring consistent file access regardless of the working directory. Relative paths start from the current directory, allowing for more flexible and environment-specific file location referencing. Absolute paths provide stability and predictability, crucial for cross-platform applications, while relative paths aid in portability and ease of adjustments across different environments. Choosing between them depends on the specific requirements for program deployment and usage scenarios.

Data types in Python are critical for defining the type of value a variable holds, influencing both how much memory is allocated and what operations can be performed on it. Effective data type usage allows the Python interpreter to manage memory efficiently, making programs faster and more efficient. Python supports both built-in data types like 'int', 'float', and 'str', and user-defined types, providing flexibility and robustness in handling varied data types and structures. Proper understanding and usage of data types help in preventing data errors and improving algorithm efficiency.

The 'pass' statement acts as a placeholder, allowing developers to define syntactically required code blocks, like empty loops or function bodies, without executing any operations. This facilitates iterative development by enabling code scaffolding, allowing developers to outline code structures for future development without causing syntax errors. It helps in maintaining code integrity when a particular block logic is yet to be implemented.

The 'read' method reads the entire file or a specified number of bytes, 'readline' reads a single line, and 'readlines' reads all lines and returns them as a list. 'Read' is suitable for handling small files, 'readline' is useful for processing files line-by-line without loading the entire content into memory, and 'readlines' is effective for obtaining all lines at once when dealing with manageable text sizes. Each method is chosen based on the file size, parsing requirement, and memory considerations.

The 'assert' keyword in Python is used for debugging purposes by testing a condition. If the condition evaluates to False, an AssertionError is raised, which helps identify logical errors in the code during development. This can otherwise be difficult to spot through normal operation and ensures that the expected program state is maintained as per assumptions.

Python's file handling uses the 'with' keyword to ensure that files are properly closed after operations, even if errors occur. This context manager handles the closing of open files automatically after their block of code is executed, maintaining resource integrity. While the 'open' function initiates file access, 'close' frees up system resources once operations are completed. This practice prevents data corruption and unintentional file lock states, contributing to stability and reliability of programs.

The 'break' statement terminates the loop entirely, skipping any remaining iterations, whereas the 'continue' statement skips the current iteration and proceeds to the next one. 'Break' can be used to exit a loop early if a certain condition is met, whereas 'continue' is used when specific conditions need to bypass certain part of the loop's code to proceed with the next iteration.

Slice operations in Python allow for extracting a subsequence from a list, using a specified start, stop, and step index. This provides a powerful tool for accessing and manipulating portions of the data efficiently. For example, given a list 'arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]', the operation 'arr[2:7:2]' will output '[3, 5, 7]', demonstrating selective extraction based on the defined step.

Functions in Python provide several advantages such as increasing code readability, promoting reusability, and enhancing maintainability. They allow grouping commonly performed operations, which reduces redundancy and minimizes errors. Functions support better organization of code, making it easier to debug and update. By allowing abstraction, functions enable breakdown of complex problems into simpler sub-problems, facilitating comprehensive testing and modular development.

Python's reserved keywords, such as 'def', 'class', 'if', and 'else', have predefined meanings and cannot be used as ordinary identifiers, ensuring a clear distinction between standard language constructs and user-defined names. This design minimizes ambiguity, enforcing consistent structure and behavior, which reduces errors related to accidental keyword conflicts. It also enhances code readability by ensuring universal understanding of these operations within the Python community.

You might also like