History of Python Programming Language:
Python is a widely used general-purpose, high-level
programming language. It was initially designed
by Guido van Rossum in 1991 and developed by
Python Software Foundation. It was mainly
developed for emphasis on code readability, and its
syntax allows programmers to express concepts in
fewer lines of code.
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in
December 1989 by Guido Van Rossum at CWI
in Netherland.
o In February 1991, Guido Van
Rossum published the code (labeled version
0.9.0) to [Link].
o In 1994, Python 1.0 was released with new
features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list
comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called
"Py3K") was released. It was designed to rectify
the fundamental flaw of the language.
o ABC programming language is said to be the
predecessor of Python language, which was
capable of Exception Handling and interfacing
with the Amoeba Operating System.
o The following programming languages influence
Python:
o ABC language.
o Modula-3
Why the Name Python?
There is a fact behind choosing the
name Python. Guido van Rossum was reading the
script of a popular BBC comedy series "Monty
Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique,
sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying
Circus" for their newly created programming
language.
The comedy series was creative and well random. It
talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every
technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile
Application, Desktop Application, Scientific
Calculation, etc.
Thrust Areas of Python
Web Development. The programming language is
used in back-end logic of web applications. ...
Data Science. Data is the new oil and companies
around the world have acknowledged it. ...
Artificial intelligence and machine learning. ...
Embedded applications. ...
Game development. Python is open
source: The Python implementation is under an
open source license that makes it freely usable
and distributable, even for commercial use.
Python is interpreted: Python is a high level
language which is interpreted by a Python
interpreter.
Python is cross platform compatible: Python
can be executed on all major platforms
like Windows, Linux/Unix, OS/2, Mac and
others.
Python is Object-Oriented: In Python, we
encapsulate data within the objects as it supports
the object-oriented style of programming.
Python is a great choice for new
learners: Python is easy to learn and follows a
simple syntax, so it is a good choice for beginner
programmers. Python also supports wide range
of application development.
Python is extensible: Python has a wide range
of libraries and built-in functions which helps in
easy and rapid development of applications.
Python is interactive: Python users are
provided a command prompt where
they can interact directly with the interpreter to
write programs.
Database connectivity: Python provides
interfaces required to connect to all major
databases like Oracle, MySQL, PostgreSQL and
others.
Identifiers:
In Python, variables, functions, classes, modules
and objects are identified using a name
known as an identifier. An identifier can start
with an uppercase or lowercase character or an
underscore (_) followed by any number of
underscores, letters and digits. All identifiers in
Python are case sensitive.
Example: weight=10
In the above example, weight is an identifier.
Keyword
Keywords are the reserved words in Python. So
keywords cannot be used as identifiers or to
name variables and functions. Few of the
keywords are listed below.
Example: if, else, elif, for, where, break, continue
Declaring a variable:
Syntax: var_name = literal_value
where var_name is the name given to the container
holding the value specified as literal_value in the
syntax above.
Example: weight=10
In the above example, weight is the container
holding the value 10 which can change during the
execution of the program.
Python may have data belonging to different types.
Common data types used in programming are listed
below:
Categor Datat
Example
y ype
Int 123
Numeric 1237126381
Long
763817
Numeric Float 123.45
with
doubl 123123.3234
decimal
e 5324
point
Alphanu Char A
meric String Hello
boole
Boolean True, False
an
Python is a dynamically typed language!
In the above example, no datatype was mentioned
at the time of declaring variable. In Python, the
datatype of a variable is decided automatically at
the time of execution based on the value assigned
to it. This is called as dynamic typing.
Syntax:
Var_name=65
Var="A"
In line 1, variable num is assigned a value 65 which
is an integer, so the data type of num variable is
integer in line 1.
In line 2, variable num is assigned a value “A” which
is a string, so the data type of the num variable is
string in line 1.
Note: To check the datatype of the variable we can
use type(var_name) which in turn returns
the datatype of the variable.
Example:
[Link]=65
[Link](num,type(num))
[Link]="A"
[Link](num,type(num))
Output:
65<class'int'>
A <class 'str'>
The input() function:
Python provides the input() built-in function to read
an input from the user using the standard input
device (i.e. keyboard). The input() function always
returns string data irrespective of the type of
data entered through the keyboard.
Syntax: var_name = input([“interactive statement”])
where,
var_name is the variable assigned with the string
value which is read using input method.
Interactive statement is the statement displayed to
the user expecting the response from them.
Example:
1.input_var=input("please enter the value")
[Link](input_var)
sample output:
pleaseenterthevalue100
100
The print() function:
Python provides the print() built-in function to
display the output onto the standard output device
(i.e. Monitor)
Syntax: print(“var_name1, var_name2)
where,
var_name1, var_name2 are the variable names or
the literals you want to print or output
Statements and Expressions:
Statements
A statement is an instruction that the Python
interpreter can execute. There are various types of
statements in Python, including:
[Link] Statement:
Example: x = 5 name = "Alice"
2. Control Flow Statements:
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Loops:
For Loop:
for i in range(5):
print(i)
While Loop:
while x > 0:
print(x)
x -= 1
Function Definition:
def greet(name):
return f"Hello, {name}"
Class Definition:
class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
return "Woof!"
Import Statement:
import math
from datetime import datetime
Exception Handling:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Expressions
An expression is a combination of values,
variables, operators, and calls to functions that the
interpreter evaluates and produces another value.
Expressions can be used wherever Python expects
a value
[Link] Expressions:
2+3*4-5 #
Results in 9
[Link] Expressions:
5 > 3 # True
x == 10 # Evaluates to True or False depending
on the value of x
[Link] Expressions:
"Hello, " + "world!" # Results in "Hello,
world!"
[Link] Calls:
len("Python") # Results in 6
[Link] Comprehensions:
[x * 2 for x in range(5)] # Results in [0, 2, 4, 6,
8]
[Link] Expressions:
(lambda x: x + 1)(5) # Results in 6
Combining Statements and Expressions
Statements can contain expressions, and expressions
can appear within statements.
For example:
x = 10 Assignment statement
y = x * 2 Assignment statement with an expression
if y > 15: Conditional statement with an expression
print("y is greater than 15") # Print statement
Understanding the difference between statements
and expressions is crucial for writing efficient and
readable Python code. Statements control the flow of
the program, while expressions compute values
Variables:
In Python, variables are used to store data values. A
variable is essentially a name that refers to a value.
Python is dynamically typed, which means that you
don't have to declare the type of a variable when you
create one. The type of the variable is determined by
the value assigned to it. Here's a detailed overview
of variables in Python:
Creating and Assigning Variables
To create a variable, you simply assign a value to a
name using the = operator.
Example:
x=5
name = "Alice"
is_active = True
Naming Rules and Conventions
[Link] can contain letters, digits, and
underscores (_).
user_name = "Alice"
user1 = "Bob"
[Link] must start with a letter or an
underscore.
_private_variable = "secret"
[Link] cannot start with a digit.
1user = "Alice" # This will cause a syntax error
[Link] are case-sensitive.
name = "Alice"
Name = "Bob"
[Link] using Python reserved keywords as
variable names.
for = 5 # This will cause a syntax error
Types of Variables
Python variables can hold different types of values,
and the type is determined at runtime. Here are some
common types:
[Link]:
age = 30
[Link]:
price = 19.99
[Link]:
name = "Alice"
[Link]:
is_active = True
[Link]:
colors = ["red", "green", "blue"]
[Link]:
point = (10, 20)
[Link]:
person = {"name": "Alice", "age": 30}
[Link]:
unique_numbers = {1, 2, 3, 4, 5}
Variable Scope
The scope of a variable determines where in the
code a variable can be accessed.
[Link] Scope: Variables created inside a function
belong to the local scope of that function and
can only be used inside that function.
def my_function():
x = 10 # Local scope
print(x)
my_function()
print(x) # This will cause an error because x
is not defined outside the function
[Link] Scope: Variables created outside of all
functions are in the global scope and can be used
anywhere in the code.
y = 20 # Global scope
def my_function():
print(y)
my_function()
print(y)
[Link] Keyword: To modify a global variable
inside a function, you can use the global
keyword.
z = 30
def my_function():
global z
z = 40
my_function()
print(z) # This will print 40
Variable Type Casting
Sometimes, you may need to convert a variable from
one type to another.
[Link] to String:
x = 10
y = str(x) # y is now "10"
[Link] to Integer:
a = "5"
b = int(a) # b is now 5
[Link] to Float:
c = "3.14"
d = float(c) # d is now 3.14
[Link] to Float:
e=7
f = float(e) # f is now 7.0
Understanding variables and how to use them
effectively is fundamental to programming in
Python. They allow you to store, manipulate, and
retrieve data in your programs.
Operators:
In Python, operators are special symbols or
keywords that are used to perform operations on
variables and values. Python provides a variety of
operators that can be categorized into several groups
based on their functionality:
1. Arithmetic Operators
These operators are used to perform mathematical
operations.
Addition (+)
x=5
y=3
print(x + y) # Output: 8
Subtraction (-)
print(x - y) # Output: 2
Multiplication (*)
print(x * y) # Output: 15
Division (/)
print(x / y) # Output: 1.6666666666666667
Floor Division (//)
print(x // y) # Output: 1
Modulus (%)
print(x % y) # Output: 2
Exponentiation (**)
print(x ** y) # Output: 125
2. Comparison Operators
These operators are used to compare two values and
return a Boolean result (True or False).
Equal to (==)
print(x == y) # Output: False
Not equal to (!=)
print(x != y) # Output: True
Greater than (>)
print(x > y) # Output: True
Less than (<)
print(x < y) # Output: False
Greater than or equal to (>=)
print(x >= y) # Output: True
Less than or equal to (<=)
print(x <= y) # Output: False
3. Logical Operators
These operators are used to combine conditional
statements.
AND (and)
print(x > 0 and y > 0) # Output: True
OR (or)
print(x > 0 or y < 0) # Output: True
NOT (not)
print(not(x > 0)) # Output: False
4. Assignment Operators
These operators are used to assign values to
variables.
Assignment (=)
z = 10
Add and assign (+=)
z += 5 # z is now 15
Subtract and assign (-=)
z -= 3 # z is now 12
Multiply and assign (*=)
z *= 2 # z is now 24
Divide and assign (/=)
z /= 4 # z is now 6.0
Floor divide and assign (//=)
z //= 2 # z is now 3.0
Modulus and assign (%=)
z %= 2 # z is now 1.0
Exponent and assign (**=)
z **= 3 # z is now 1.0
5. Bitwise Operators
These operators are used to perform operations on
binary numbers.
AND (&)
print(5 & 3) # Output: 1 (binary: 101 & 011 =
001)
OR (|)
print(5 | 3) # Output: 7 (binary: 101 | 011 = 111)
XOR (^)
print(5 ^ 3) # Output: 6 (binary: 101 ^ 011 =
110)
NOT (~)
print(~5) # Output: -6 (binary: ~101 = -110)
Left Shift (<<)
print(5 << 1) # Output: 10 (binary: 101 << 1 =
1010)
Right Shift (>>)
print(5 >> 1) # Output: 2 (binary: 101 >> 1 =
10)
6. Membership Operators
These operators are used to test if a sequence is
present in an object.
IN (in)
list = [1, 2, 3, 4, 5]
print(3 in list) # Output: True
NOT IN (not in)
print(6 not in list) # Output: True
7. Identity Operators
These operators are used to compare the memory
locations of two objects.
IS (is)
a = [1, 2, 3]
b=a
print(a is b) # Output: True
IS NOT (is not)
c = [1, 2, 3]
print(a is not c) # Output: True
Understanding and using these operators effectively
is crucial for performing various operations and
manipulating data in Python.
Precedence and Associativity:
In Python, operator precedence and associativity
determine the order in which operators are evaluated
in expressions.
Precedence
Operator precedence determines which operator is
evaluated first in an expression with multiple
operators. Operators with higher precedence are
evaluated before operators with lower precedence.
Here's a list of Python operators, grouped by
precedence from highest to lowest:
[Link]: **
[Link] plus, unary minus, and bitwise NOT:
+, -, ~
[Link], division, floor division, and
modulus: *, /, //, %
[Link] and subtraction: +, -
[Link] shift operators: <<, >>
[Link] AND: &
[Link] XOR: ^
[Link] OR: |
[Link], including membership and
identity tests: ==, !=, >, <, >=, <=, is, is not, in,
not in
10. Boolean NOT: not
11. Boolean AND: and
12. Boolean OR: or
Associativity
Associativity determines the order in which
operators of the same precedence are evaluated.
Most operators in Python are left-associative,
meaning they are evaluated from left to right. The
exponentiation operator (**) is right-associative,
meaning it is evaluated from right to left.
Left-Associative Operators (evaluated from left
to right)
Multiplication, division, floor division, and
modulus (*, /, //, %)
Addition and subtraction (+, -)
Bitwise shift operators (<<, >>)
Bitwise AND (&)
Bitwise XOR (^)
Bitwise OR (|)
Comparisons (==, !=, >, <, >=, <=, is, is not, in,
not in)
Boolean AND (and)
Boolean OR (or)
Right-Associative Operators (evaluated from
right to left)
Exponentiation (**)
Unary plus, unary minus, and bitwise NOT (+, -,
~)
Boolean NOT (not)
Examples
Example 1: Operator Precedence
x=2+3*4
print(x) ‘P # Output: 14
In this example, multiplication (*) has higher
precedence than addition (+), so 3 * 4 is evaluated
first, resulting in 12, and then 2 + 12 gives 14.
Example 2: Using Parentheses to Override
Precedence
x = (2 + 3) * 4
print(x) # Output: 20
Parentheses have the highest precedence, so 2 + 3 is
evaluated first, resulting in 5, and then 5 * 4 gives
20.
Example 3: Associativity
x = 2 ** 3 ** 2
print(x) # Output: 512
Exponentiation is right-associative, so 3 ** 2 is
evaluated first, resulting in 9, and then 2 ** 9 gives
512.
Example 4: Mixed Associativity
x=5-3+2
print(x) # Output: 4
Both subtraction and addition are left-associative
and have the same precedence. So, 5 - 3 is evaluated
first, resulting in 2, and then 2 + 2 gives 4.
Understanding operator precedence and associativity
is crucial for writing clear and correct Python code,
especially in complex expressions. When in doubt,
using parentheses to explicitly define the evaluation
order can help ensure your code behaves as
expected.
In Python, data types specify the type of value a
variable holds. Python has several built-in data types
that are used to handle different kinds of data. Here's
a comprehensive overview of the most common data
types in Python:
Basic Data Types
[Link] (int):
o Whole numbers, positive or negative,
without decimals.
o Example:
python
Copy code
x = 10
y = -5
[Link] (float):
o Numbers, positive or negative, containing
one or more decimals.
o Example:
python
Copy code
pi = 3.14
gravity = 9.81
[Link] (str):
o Sequence of characters enclosed in single,
double, or triple quotes.
o Example:
python
Copy code
name = "Alice"
greeting = 'Hello, world!'
paragraph = """This is a paragraph
that spans multiple lines."""
[Link] (bool):
o Represents one of two values: True or False.
o Example:
python
Copy code
is_active = True
has_passed = False
Collection Data Types
[Link] (list):
o Ordered collection of items which can be of
different types. Lists are mutable.
o Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]
[Link] (tuple):
o Ordered collection of items which can be of
different types. Tuples are immutable.
o Example:
point = (10, 20)
colors = ("red", "green", "blue")
[Link] (set):
o Unordered collection of unique items.
o Example:
unique_numbers = {1, 2, 3, 4, 5}
letters = {"a", "b", "c"}
[Link] (dict):
o Unordered collection of key-value pairs.
o Example:
person = {"name": "Alice", "age": 30,
"city": "New York"}
scores = {"math": 95, "science": 90}
Special Data Types
[Link] (None):
o Represents the absence of a value or a null
value.
o Example:
x = None
[Link] (range):
o Represents an immutable sequence of
numbers, commonly used for looping a
specific number of times in for loops.
o Example:
numbers = range(10) # Creates a range
object from 0 to 9
Type Conversion
Python allows you to convert values from one data
type to another using type conversion functions.
[Link] to String:
x = 10
y = str(x) # y is now "10"
[Link] to Integer:
a = "5"
b = int(a) # b is now 5
[Link] to Float:
c = "3.14"
d = float(c) # d is now 3.14
[Link] to Integer:
e = 7.89
f = int(e) # f is now 7
[Link] to Tuple:
list_example = [1, 2, 3]
tuple_example = tuple(list_example) #
tuple_example is now (1, 2, 3)
[Link] to List:
tuple_example = (1, 2, 3)
list_example = list(tuple_example) #
list_example is now [1, 2, 3]
[Link] to Set:
list_example = [1, 2, 2, 3]
set_example = set(list_example) # set_example
is now {1, 2, 3}
Understanding and effectively using these data types
is fundamental to programming in Python. Each data
type has its own properties and is suited for different
kinds of tasks.
Indentation: Indentation refers to the spaces or tabs
used at the beginning of a line of code to indicate
that it is a part of a block of code. It is a crucial
aspect of programming, especially in languages like
Python where indentation is used to define the
structure and flow of the program.
Importance of Indentation
[Link]: Proper indentation makes code
easier to read and understand.
[Link]: In languages like Python, indentation
defines blocks of code such as loops,
conditionals, and functions.
[Link]: Well-indented code is easier to
debug and maintain.
Comments: In Python, comments are used to explain
code and make it more readable. They are ignored
by the Python interpreter and do not affect the
execution of the program. There are two main types
of comments in Python: single-line comments and
multi-line comments.
Single-Line Comments
Single-line comments start with the hash character
(#) and extend to the end of the line.
This is a single-line comment
print("Hello, World!")
# This comment is at the end of a line of code
Multi-Line Comments
While Python does not have a specific syntax for
multi-line comments, you can use multiple single-
line comments or triple-quoted strings (which are
generally used for docstrings) to achieve the same
effect.
Multi-Line Comments
While Python does not have a specific syntax for
multi-line comments, you can use multiple single-
line comments or triple-quoted strings (which are
generally used for docstrings) to achieve the same
effect.
Example using multiple single-line comments:
# This is a multi-line comment
# that spans multiple lines
print("Hello, World!")
Example using triple-quoted strings:
"""
This is a multi-line comment
using triple-quoted strings.
It can span multiple lines.
"""
print("Hello, World!")
Docstrings
Docstrings are a special type of comment used to
document modules, classes, functions, and methods.
They are written using triple quotes and are the first
statement in the object being documented.
def greet(name):
""" This function greets a person with the given
name.
Parameters:.
name (str): The name of the person to greet.
Returns:
None
"""
print(f"Hello, {name}!")
greet("Alice")
READING INPUT
Reading input in Python can be done using the built-
in input() function. This function reads a line from
the standard input (usually from the keyboard) and
returns it as a string.
Basic Usage
The input() function can be used to prompt the user
for input.
Example:
name = input("Enter your name: ")
print(f"Hello, {name}!")
Print Output
In Python, you can display output using the print()
function. Here are some examples:
[Link] a String:
print("Hello, World!")
Output:
Hello, World!
[Link] Variables:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
[Link] Numbers:
num1 = 10
num2 = 20
print("Sum:", num1 + num2)
Output:
Sum: 30
[Link] Output using f-strings (Python
3.6+):
product = "Computer"
price = 1200.50
print(f"Product: {product}, Price: ${price}")
Output:
Product: Computer, Price: $1200.50
[Link] Multiple Lines:
print("First line")
print("Second line")
Output:
First line
Second line
[Link] with Special Characters:
print("This\tis\ta\ttabbed\tline")
Output:
This is a tabbed line
[Link] with End Parameter (Python 3.x):
print("Hello", end="")
print(", World!")
Output:
Hello, World!
These are basic examples of how you can use the
print() function to display output in Python. It's a
versatile function that allows you to output strings,
numbers, variables, and formatted text to the console
or other output streams.
Type Conversions:
Type conversion in Python refers to the process of
converting one data type into another. This is useful
when you need to perform operations that involve
different types of data or when you want to represent
data in a different format. Here are some common
type conversions in Python:
1. Implicit Type Conversion (Coercion)
Python automatically converts data types in certain
situations, such as:
Integers to Floats: Conversion occurs when
performing operations that involve both integers
and floats.
num_int = 10
num_float = 5.5
result = num_int + num_float # num_int is
implicitly converted to float
print(result) # Output: 15.5
Floats to Integers: Conversion occurs when
assigning a float to an integer variable.
num_float = 15.8
num_int = int(num_float) # num_float is
explicitly converted to int
print(num_int) # Output: 15
2. Explicit Type Conversion (Type Casting)
You can explicitly convert data from one type to
another using built-in functions. Here are some
examples:
Integer to Float:
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
Float to Integer:
num_float = 5.6
num_int = int(num_float)
print(num_int) # Output: 5
String to Integer or Float:
num_str = "123"
num_int = int(num_str)
print(num_int) # Output: 123
num_str = "456.78"
num_float = float(num_str)
print(num_float) # Output: 456.78
Integer or Float to String:
num_int = 100
num_str = str(num_int)
print(num_str) # Output: "100"
num_float = 3.14
num_str = str(num_float)
print(num_str) # Output: "3.14"
the type () Function and Is Operator
In Python, the type() function and the is operator are
useful tools for working with data types and object
identity. Let's explore each of them:
1. type() Function
The type() function in Python is used to get the type
of an object. It returns the data type of the object
passed to it as an argument.
Syntax:
type(object)
Examples:
Checking the type of variables:
num = 10
print(type(num)) # Output: <class 'int'>
num_float = 5.5
print(type(num_float)) # Output: <class 'float'>
name = "Alice"
print(type(name)) # Output: <class 'str'>
Checking the type of more complex objects:
my_list = [1, 2, 3]
print(type(my_list)) # Output: <class 'list'>
my_dict = {'a': 1, 'b': 2}
print(type(my_dict)) # Output: <class 'dict'>
Using type() with functions:
def greet():
print("Hello!")
print(type(greet)) # Output: <class 'function'>
2. is Operator
The is operator in Python checks if two variables
refer to the same object in memory, not just if they
are equal.
Syntax:
x is y
Examples:
Checking identity with simple types:
a = 10
b = 10
print(a is b) # Output: True (since integers in
this range are cached in Python)
c = 1000
d = 1000
print(c is d) # Output: False (different objects
are created for large integers)
Checking identity with lists:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2) # Output: False (different
objects in memory)
list3 = list1
print(list1 is list3) # Output: True (both
variables refer to the same list object)
Checking identity with functions:
def foo():
return
def bar():
return
print(foo is bar) # Output: False (different
function objects)
Key Differences between type() and is:
Functionality:
o type() checks the data type of an object.
o is checks if two variables point to the same
object in memory.
Usage:
o Use type() to determine the type of an object
for type checking or debugging.
oUse is to check object identity, which is
particularly useful when dealing with
mutable objects or functions.
Output:
o type() returns the class/type of an object
(e.g., <class 'int'>, <class 'list'>).
o is returns a boolean (True or False)
indicating whether two variables refer to the
same object.
Understanding how to use type() and is effectively
can help you debug code, manage memory
efficiently, and write more robust Python programs.
Dynamic and Strongly Typed Language:
n the realm of programming languages, terms like
"dynamic" and "strongly typed" describe key
characteristics that influence how code is written,
executed, and managed. Let's explore each of these
concepts:
Dynamic Typing
Dynamic typing refers to the ability of a
programming language to automatically determine
the data type of a variable at runtime. In dynamically
typed languages, you do not need to explicitly
declare the type of a variable when you define it.
Instead, the type is inferred based on the value
assigned to it.
Characteristics of Dynamic Typing:
Implicit Declaration: Variables are declared
without specifying a type.
Type Checking at Runtime: Type
compatibility is checked during program
execution rather than at compile-time.
Flexibility: Variables can change type during
the execution of the program.
Examples of Dynamically Typed Languages:
Python: Variables are dynamically typed; their
types are determined based on the assigned
values.
JavaScript: Another example where variables
are dynamically typed, allowing for flexibility in
data manipulation and function invocation.
Example in Python:
# Dynamic typing in Python
x = 10 # x is an integer
print(type(x)) # Output: <class 'int'>
x = "Hello" # Now x is a string
print(type(x)) # Output: <class 'str'>
Strongly Typed
Strongly typed languages enforce strict type
constraints and do not perform implicit type
conversion. This means that operations between
different data types are not automatically allowed
and must be explicitly converted if necessary.
Characteristics of Strongly Typed Languages:
Explicit Type Conversion: Conversion
between types must be explicitly performed by
the programmer.
Type Safety: Types are strictly enforced to
prevent unintended operations or errors.
Less Implicit Conversion: Operations between
different types generally require explicit casting
or conversion.
Examples of Strongly Typed Languages:
Python: Despite being dynamically typed,
Python is also considered strongly typed because
it enforces strict type rules.
Java: Variables in Java must be declared with a
specific type, and operations between
incompatible types are not allowed without
explicit conversion.
Example of Strongly Typed Behavior:
# Strongly typed behavior in Python
x = 10
y = "20"
# This would raise a TypeError because you cannot
add an integer and a string directly
# Uncommenting this line would result in a
TypeError:
# print(x + y)
# Explicit conversion needed
print(x + int(y)) # Output: 30
Key Differences
Dynamic vs. Static Typing: Dynamic typing
refers to type determination at runtime (e.g.,
Python), while static typing involves type
checking at compile-time (e.g., Java).
Strong vs. Weak Typing: Strongly typed
languages enforce strict type rules and do not
automatically convert types (e.g., Python, Java),
whereas weakly typed languages may perform
implicit type conversions (e.g., JavaScript).
Understanding these concepts helps in choosing the
right language for a particular programming task and
in writing robust, maintainable code. Python, for
example, combines dynamic typing with strong type
enforcement, offering flexibility without sacrificing
safety and clarity.
Control Flow Statements if statement, if-else
statement, if...elif…else, Nested if statement, while
Loop, for Loop, continue and break Statements,
Catching Exceptions Using try and except
Statement.
if statement:
In Python, the if statement is used for conditional
execution. It allows you to execute a certain block of
code only if a specified condition is true. Here's the
basic syntax of an if statement in Python:
if condition:
# Code to be executed if the condition is true
statement1
statement2
# and so on
Here, condition is an expression that evaluates to
either True or False. If condition is True, then the
indented block of code following the if statement
(denoted by spaces or tabs) will be executed. If
condition is False, then the block of code is skipped.
Example:
x = 10
if x > 5:
print("x is greater than 5")
print("This statement is also executed because x >
5")
In this example, since x is indeed greater than 5,
both print statements inside the if block will be
executed.
Using else and elif:
You can also extend the if statement with else and
elif (short for else if) clauses to handle alternative
conditions:
else: Executes a block of code if the if condition
is False.
elif: Stands for "else if". It allows you to check
multiple conditions sequentially.
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition1 is false and
condition2 is true
else:
# Code to execute if both condition1 and
condition2 are false
Example with elif and else:
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("F")
In this example, based on the value of grade, a
corresponding grade letter is printed depending on
which condition (if, elif, or else) is satisfied first.
Notes:
Python uses indentation (typically 4 spaces) to
define blocks of code. This is different from
languages like C or Java, which use curly braces
{}.
The elif and else parts are optional. An if
statement can stand alone without them.
Understanding if statements are fundamental to
controlling the flow of your Python programs based
on different conditions.
Nested if:
Nested if statements in Python refer to placing one if
statement inside another if or else block. This allows
for more complex conditional logic where certain
conditions need to be checked only if another
condition is true. Here's how you can use nested if
statements in Python:
x = 10
y=5
if x > 5:
print("x is greater than 5")
if y > 2:
print("y is also greater than 2")
else:
print("y is not greater than 2")
else:
print("x is not greater than 5")
In this example:
The outer if statement checks if x is greater than
5.
If x is greater than 5 (True), it prints "x is greater
than 5".
Inside the outer if block, there is a nested if
statement that checks if y is greater than 2.
Depending on the value of y, it will print either
"y is also greater than 2" or "y is not greater than
2".
If x is not greater than 5 (False), it executes the
else block of the outer if statement and prints "x
is not greater than 5".
Nested if with elif:
You can also nest if, elif, and else statements to
handle multiple conditions in a more structured way:
x = 10
y=5
if x > 5:
if y > 2:
print("x is greater than 5 and y is greater than
2")
elif y == 2:
print("x is greater than 5 and y is exactly 2")
else:
print("x is greater than 5 but y is less than 2")
else:
print("x is not greater than 5")
In this example:
The outer if statement checks if x is greater than
5.
If x is greater than 5 (True), it then checks the
value of y using nested if, elif, and else
statements:
o If y is greater than 2, it prints "x is greater
than 5 and y is greater than 2".
o If y is exactly 2, it prints "x is greater than 5
and y is exactly 2".
o If y is less than 2, it prints "x is greater than
5 but y is less than 2".
If x is not greater than 5 (False), it executes the
else block of the outer if statement and prints "x
is not greater than 5".
Important Notes:
Proper indentation is crucial in Python to
indicate nested blocks of code.
Nesting if statements should be done carefully to
maintain code readability. Excessive nesting can
make code harder to understand and debug.
Nested if statements allow you to handle more
complex conditional logic based on multiple
conditions and their combinations.
Understanding how to use nested if statements
effectively can help you write more flexible and
expressive code in Python, especially when dealing
with complex conditions and decision-making
processes.
Certainly! Let's explore the while loop, for loop,
continue, and break statements in Python. These are
fundamental control flow statements that allow you
to iterate through sequences, skip certain iterations,
and break out of loops based on conditions.
while Loop:
The while loop in Python repeatedly executes a
block of statements as long as a specified condition
is true.
Syntax:
while condition:
# Code block to be executed while the condition is
true
statement1
statement2
# and so on
Example:
count = 0
while count < 5:
print(f"Current count: {count}")
count += 1
In this example:
count starts at 0.
The while loop continues executing as long as
count < 5.
Each iteration, it prints the current value of
count and increments count by 1 (count += 1).
The loop terminates when count reaches 5
because count < 5 becomes False.
for Loop:
The for loop in Python iterates over a sequence
(such as a list, tuple, string, or range) and executes a
block of code for each element in the sequence.
Syntax:
for item in sequence:
# Code block to be executed for each item in
sequence
statement1
statement2
# and so on
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"Current fruit: {fruit}")
In this example:
fruits is a list containing three strings.
The for loop iterates over each element (fruit) in
the fruits list.
For each iteration, it prints "Current fruit: "
followed by the value of fruit.
continue Statement:
The continue statement in Python is used to skip the
rest of the code inside a loop for the current iteration
and proceed to the next iteration.
Example (with while loop):
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(f"Current count: {count}")
In this example:
The while loop increments count from 1 to 5.
When count equals 3, the continue statement is
encountered.
The continue statement skips the remaining code
in the loop for that iteration.
Therefore, "Current count: 3" is not printed, but
the loop continues with other iterations.
break Statement:
The break statement in Python terminates the current
loop and resumes execution at the next statement
after the loop.
Example (with for loop):
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"Current fruit: {fruit}")
if fruit == "banana":
break
In this example:
The for loop iterates over the fruits list.
For each iteration, it prints "Current fruit: "
followed by the value of fruit.
When fruit is "banana", the if condition is true.
The break statement terminates the loop
immediately after "banana" is printed.
Therefore, only "apple" and "banana" are
printed, and "cherry" is not processed.
Summary:
while Loop: Executes a block of code
repeatedly while a condition is true.
for Loop: Iterates over a sequence (list, tuple,
string, etc.) and executes a block of code for
each element.
continue Statement: Skips the rest of the code
inside a loop for the current iteration and moves
to the next iteration.
break Statement: Terminates the loop it is in
and resumes execution at the next statement
after the loop.
These statements are essential for controlling the
flow of execution in Python programs, especially
when dealing with repetitive tasks or iterating over
data structures
Catching Exceptions Using try and except
Statement.
In Python, the try and except statements are used for
exception handling, which allows you to catch and
handle exceptions (errors) gracefully during program
execution. This mechanism helps in preventing your
program from crashing unexpectedly when errors
occur. Here's how try and except statements work:
Syntax:
try:
# Code block where exceptions may occur
statement1
statement2
# and so on
except ExceptionName as exception_variable:
# Code to handle the exception
statement3
statement4
# and so on
Example:
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print("Error: Division by zero!")
print(f"Exception details: {e}")
In this example:
The try block contains code that might raise an
exception (in this case, dividing by zero).
The except block catches the specific
ZeroDivisionError exception.
If a ZeroDivisionError occurs during the
execution of the try block, the code inside the
except block will execute.
The as e part captures the exception object
(ZeroDivisionError in this case) into the variable
e, allowing you to access details about the
exception.
Multiple except Blocks:
You can have multiple except blocks to handle
different types of exceptions separately.
try:
x = int(input("Enter a number: "))
result = 10 / x # This may raise
ZeroDivisionError or ValueError
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a valid
number.")
In this example:
The try block attempts to get an integer input
from the user and perform a division operation.
There are two separate except blocks:
o ZeroDivisionError catches division by zero
errors.
o ValueError catches errors when the input
cannot be converted to an integer.
Generic except Block:
You can also use a generic except block to catch any
type of exception that is not explicitly handled by
previous except blocks. However, it is generally
recommended to specify the specific exceptions you
expect to handle whenever possible.
try:
# Some code that may raise exceptions
except ZeroDivisionError:
# Handle ZeroDivisionError
except Exception as e:
# Handle all other exceptions
print(f"An error occurred: {e}")
finally Block:
Optionally, you can use a finally block to execute
cleanup code that should always be run, regardless
of whether an exception was raised or not.
try:
# Some code that may raise exceptions
except SomeException:
# Handle SomeException
finally:
# This block is always executed, whether there
was an exception or not
cleanup_code()
Summary:
try: Contains code that may raise exceptions.
except: Handles specific exceptions that occur
within the try block.
as exception_variable: Optionally captures the
exception object for further processing.
Multiple except blocks: Allows handling
different types of exceptions separately.
finally: Optional block for cleanup code that is
always executed, regardless of exceptions.
Using try and except statements effectively helps in
writing robust Python code that can gracefully
handle errors and exceptions during execution,
improving the reliability and stability of your
programs.
Program 01: Write a program to find the largest
element among three Numbers
Source Code:
num1 = 10
num2 = 14
num3 = 12
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
Output:
The Largest number is 14
Program 2: Write a Program to display all prime
numbers within an interval
Source code:
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper,
"are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Program 03
Write a program to swap two numbers without
using a temporary variable.
Source code:
x=5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output:
The value of x after swapping: 10
The value of y after swapping: 5
Program 04
Demonstrate the following Operators in Python
with suitable examples. i) Arithmetic
Operators
ii) Relational Operators iii) Assignment
Operators
Source code:
i) Arithmetic Operators
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)
Output:
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Relational Operators:
Source code:
a=4
b=5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Output:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
iii)Assignment Operators
# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)
Output:
a += 5 : 15
a -= 5 : 10
a *= 5 : 50
a /= 5 : 10.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
Program 5:
Write a program to add and multiply complex
numbers
Source Code:
print("Addition of two complex numbers : ",(4+3j)
+(3-7j))
print("Subtraction of two complex numbers : ",
(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",
(4+3j)*(3-7j))
print("Division of two complex numbers:",(4+3j)/(3-
7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-
0.15517241379310348+0.6379310344827587j)
Program 06:
Write a program to print multiplication table of a
given number.
# Multiplication table (from 1 to 10) in Python
num = 9
# To take input from the user
# num = int(input("Display multiplication table of?
"))
# Iterate 10 times from i = 1 to 10
for i in range(1, 10):
print(num, 'x', i, '=', num*i)
Output:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Strings: Creating and Storing Strings, Basic String
Operations, Accessing Characters in String by Index
Number, String Slicing and Joining, String Methods,
Formatting Strings.
Lists: Creating Lists, Basic List Operations,
Indexing and Slicing in Lists, Built-In Functions
Used on Lists, List Methods, del Statement.
Sample Experiments:
[Link] a program to define a function with multiple
return values.
[Link] a program to define a function using default
arguments.
[Link] a program to find the length of the string
without using any library functions.
10. Write a program to check if the substring is
present in a given string or not.
11. Write a program to perform the given operations
on a list:
i. Addition ii. Insertion iii. slicing
12. Write a program to perform any 5 built-in
functions by taking any list.
Built-In Functions
Python comes with a wide range of built-in functions
that help you perform common tasks without
needing to import additional libraries. Here’s a list
of some of the most commonly used built-in
functions in Python:
Basic Functions
print(): Outputs data to the console.
input(): Reads input from the user.
type(): Returns the type of an object.
id(): Returns the identity of an object (unique
and constant for the object during its lifetime).
len(): Returns the length of an object (e.g., a
string, list, or tuple).
int(), float(), str(), bool(): Type conversion
functions.
Numeric Functions
abs(): Returns the absolute value of a number.
pow(): Returns the value of a number raised to a
power.
round(): Rounds a floating-point number to a
specified number of decimal places.
divmod(): Returns a tuple containing the
quotient and remainder of dividing two numbers.
Sequence and Collection Functions
map(): Applies a function to all items in an input
list.
filter(): Constructs an iterator from elements of
an iterable for which a function returns true.
Functional Programming
sum(): Sums up the elements of an iterable.
max(), min(): Return the largest and smallest
items from an iterable, respectively.
Object and Class Utilities
callable(): Checks if an object appears to be
callable (i.e., a function or method).
getattr(), setattr(), delattr(): Access, modify,
or delete an attribute of an object.
Commonly Used Modules
1. Standard Library Modules
math: Contains mathematical functions like
sqrt, sin, cos, log, etc.
datetime: Supplies classes for manipulating
dates and times.
collections: Provides specialized data structures
like named tuples, defaultdict, and Counter.
2. Third-Party Modules
numpy: Fundamental package for numerical
computations, including support for arrays and
matrices.
pandas: Provides data structures like
DataFrames and functions for data manipulation
and analysis.
matplotlib: Plotting library for creating static,
animated, and interactive visualizations in
Python.
Function Definition and Calling the function:
Defining a Function
def function_name(parameters): """Docstring:
Description of the function (optional).""" # Code
block return value # Optional: return statement to
output a value
def greet(name):
"""This function greets the person whose name is
passed as a parameter."""
greeting = f"Hello, {name}!"
return greeting
Calling a Functon
# Calling the add_numbers function
result = add_numbers(5, 7)
print(result) # Output: 12
Function with Default Parameters
# Calling the greet function without arguments
print(greet()) # Output: Hello, Guest!
# Calling the greet function with an argument
print(greet("Bob")) # Output: Hello, Bob!
Function with Keyword Arguments
describe_pet("cat", pet_name="Whiskers")
Function Returning Multiple Values
# Calling the function and unpacking the returned
tuple
name, initials = get_full_name("John", "Doe")
print(name) # Output: John Doe
print(initials) # Output: J.D.
return Statement and void Function
Function Returning Multiple Values
The return Statement
def function_name(parameters):
# Code block
return value # Ends the function and returns
'value' to the caller
Returning Multiple Values
# Calling the function and unpacking the returned
tuple
q, r = divide_and_remainder(10, 3)
print(q) # Output: 3
print(r) # Output: 1
Void Function (Function Without return)
Scope and Lifetime of Variables
The scope of a variable refers to the region of the
code where that variable is accessible. Python has
several types of scope:
[Link] Scope
[Link] (Nonlocal) Scope
[Link] Scope
[Link]-in Scope
1. Local Scope
def my_function():
x = 10 # x is local to my_function
print(x)
my_function() # Output: 10
print(x) # Error: NameError because x is not
accessible outside the function
2. Enclosing (Nonlocal) Scope
def outer_function():
x = 20 # x is in the enclosing scope of
inner_function
def inner_function():
print(x) # Accesses x from the enclosing scope
inner_function() # Output: 20
outer_function()
3. Global Scope
x = 30 # x is a global variable
def my_function():
print(x) # Accesses the global variable x
my_function() # Output: 30
4. Built-in Scope
The built-in scope includes special names that
Python reserves, like keywords and built-in
functions (len, print, etc.).
These are available anywhere in your code.
print(len("hello")) # len is a built-in function
.
*args and **kwargs
1. *args (Non-keyword Variable-Length
Arguments)
*args allows you to pass a variable number of
non-keyword arguments to a function. Inside the
function, *args is treated as a tuple containing all
the additional positional arguments passed to the
function.
2. **kwargs (Keyword Variable-Length
Arguments)
**kwargs allows you to pass a variable number
of keyword arguments to a function. Inside the
function, **kwargs is treated as a dictionary
where the keys are the argument names, and the
values are the argument values.
Command Line Arguments
Accessing Command Line Arguments
[Link]: A list in Python, which contains the
command line arguments passed to the script.
The first element, [Link][0], is the name of the
script itself. The subsequent elements are the
arguments provided by the user.
Running the Script with Command Line
Arguments
Assuming the script is saved as [Link], you can
run it from the command line and pass arguments to
it:
python [Link] hello world 123
The output will be:
yaml
Script name: [Link]
Arguments:
Argument 1: hello
Argument 2: world
Argument 3: 123
Parsing Command Line Arguments
Example Using argparse
Here's how you might use argparse to handle
command line arguments:
import argparse
def main():
parser = [Link](description="A
simple script that greets users.")
parser.add_argument("name", help="Name of the
person to greet")
parser.add_argument("-c", "--count", type=int,
default=1, help="Number of times to greet")
args = parser.parse_args()
for _ in range([Link]):
print(f"Hello, {[Link]}!")
if __name__ == "__main__":
main()
Running the Script with argparse
You can run this script as follows:
python [Link] Alice -c 3
Output:
Hello, Alice!
Hello, Alice!
Hello, Alice!
Strings: Creating and Storing Strings, Basic String
Operations, Accessing Characters in String by Index
Number
Creating Strings
Strings in Python can be created using single quotes
('...'), double quotes ("..."), triple single quotes
('''...'''), or triple double quotes ("""...""").
Examples:
# Single quotes
string1 = 'Hello, World!'
# Double quotes
string2 = "Hello, World!"
# Triple quotes (for multi-line strings)
string3 = '''This is a
multi-line
string.'''
string4 = """This is another
multi-line
string."""
Storing Strings
Strings can be stored in variables, which you can
then use throughout your code.
Example:
greeting = "Hello, World!"
name = "Alice"
message = f"{greeting} My name is {name}."
print(message)
# Output: Hello, World! My name is Alice.
String Concatenation
You can combine strings using the + operator or by
using formatted strings.
Example:
# Using + operator
string1 = "Hello"
string2 = "World"
result = string1 + ", " + string2 + "!"
print(result) # Output: Hello, World!
# Using formatted strings (f-strings)
name = "Alice"
greeting = f"Hello, {name}!"
print(greeting) # Output: Hello, Alice!
String Methods:
1. [Link]()
Returns a new string with all characters converted to
uppercase.
text = "hello"
print([Link]()) # Output: HELLO
2. [Link]()
Returns a new string with all characters converted to
lowercase.
text = "HELLO"
print([Link]()) # Output: hello
3. [Link]()
Returns a new string with the first letter of each
word capitalized.
text = "hello world"
print([Link]()) # Output: Hello World
4. [Link]()
Returns a new string with the first character
capitalized and the rest in lowercase.
text = "hello world"
print([Link]()) # Output: Hello world
5. [Link]([chars])
Returns a new string with leading and trailing
whitespace removed. If chars is provided, it removes
those characters instead.
text = " hello "
print([Link]()) # Output: hello
text = "---hello---"
print([Link]('-')) # Output: hello
6. [Link]([chars])
Returns a new string with leading whitespace
removed. If chars is provided, it removes those
characters from the beginning of the string.
text = " hello "
print([Link]()) # Output: hello
text = "---hello"
print([Link]('-')) # Output: hello
7. [Link]([chars])
Returns a new string with trailing whitespace
removed. If chars is provided, it removes those
characters from the end of the string.
text = " hello "
print([Link]()) # Output: hello
text = "hello---"
print([Link]('-')) # Output: hello
8. [Link](old, new[, count])
Returns a new string with all occurrences of the
substring old replaced by new. If count is provided,
it replaces only the first count occurrences.
text = "hello world"
print([Link]("world", "Python")) # Output:
hello Python
text = "hello hello"
print([Link]("hello", "hi", 1)) # Output: hi
hello
Formatting Strings
1. Old-Style Formatting (% Operator)
The old-style formatting uses the % operator and is
reminiscent of C-style formatting.
Basic Syntax:
formatted_string = "format specifier" % value
Examples:
name = "Alice"
age = 30
# Basic string formatting
print("Name: %s, Age: %d" % (name, age)) #
Output: Name: Alice, Age: 30
2. [Link]() Method
The [Link]() method provides a more flexible
way to format strings. You use curly braces {} as
placeholders within the string.
Basic Syntax:
formatted_string = "format string with {0}
placeholders".format(value)
Examples:
name = "Bob"
age = 25
Lists: Creating Lists
Basic List Creation
# Creating a list with integers
numbers = [1, 2, 3, 4, 5]
# Creating a list with strings
fruits = ["apple", "banana", "cherry"]
# Creating a list with mixed data types
mixed = [1, "hello", 3.14, [1, 2, 3]]
2. Empty List
You can create an empty list and then add elements
to it later.
# Creating an empty list
empty_list = []
# Adding elements to the empty list
empty_list.append(1)
empty_list.append(2)
empty_list.append(3)
print(empty_list) # Output: [1, 2, 3]
3. List with Repeated Elements
You can create a list with repeated elements using
multiplication.
# Creating a list with repeated elements
zeros = [0] * 5
print(zeros) # Output: [0, 0, 0, 0, 0]
4. List Comprehension
List comprehensions provide a concise way to create
lists based on existing lists or ranges.
# Creating a list of squares using list comprehension
squares = [x ** 2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49,
64, 81]
# Creating a list of even numbers using list
comprehension
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
Accessing List Elements
You can access elements of a list using indexing.
Python uses zero-based indexing.
# Accessing elements of a list
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple (first element)
print(fruits[1]) # Output: banana (second element)
# Negative indexing to access elements from the end
print(fruits[-1]) # Output: cherry (last element)
print(fruits[-2]) # Output: banana (second to last
element)
Slicing Lists
You can extract a portion of a list using slicing.
# Slicing a list
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4] (elements
from index 1 to 3)
print(numbers[:3]) # Output: [1, 2, 3] (elements
from the start to index 2)
print(numbers[3:]) # Output: [4, 5] (elements from
index 3 to the end)
print(numbers[::2]) # Output: [1, 3, 5] (every second
element)
Modifying Lists
Lists are mutable, so you can change their contents.
# Modifying elements of a list
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
# Adding elements to a list
[Link]("date")
print(fruits) # Output: ['apple', 'blueberry', 'cherry',
'date']
# Inserting elements at a specific position
[Link](1, "blackberry")
print(fruits) # Output: ['apple', 'blackberry',
'blueberry', 'cherry', 'date']
# Removing elements from a list
[Link]("blueberry")
print(fruits) # Output: ['apple', 'blackberry', 'cherry',
'date']
# Removing elements by index
del fruits[0]
print(fruits) # Output: ['blackberry', 'cherry', 'date']
List Methods
Python provides several built-in methods for
working with lists:
append(x): Adds an item to the end of the list.
numbers = [1, 2, 3]
[Link](4)
print(numbers) # Output: [1, 2, 3, 4]
extend(iterable): Extends the list by appending
elements from an iterable.
numbers = [1, 2, 3]
[Link]([4, 5])
print(numbers) # Output: [1, 2, 3, 4, 5]
insert(index, x): Inserts an item at a given
position.
numbers = [1, 2, 3]
[Link](1, 1.5)
print(numbers) # Output: [1, 1.5, 2, 3]
remove(x): Removes the first item with the
specified value.
numbers = [1, 2, 3, 2]
[Link](2)
print(numbers) # Output: [1, 3, 2]
Indexing and Slicing in Lists
Indexing
Indexing is used to access individual elements in a
list. Python uses zero-based indexing, meaning the
index of the first element is 0.
Basic Indexing
Accessing elements:
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10 (first element)
print(my_list[3]) # Output: 40 (fourth element)
Negative Indexing:
Negative indexing allows you to access elements
from the end of the list. The index -1 refers to
the last element.
print(my_list[-1]) # Output: 50 (last element)
print(my_list[-2]) # Output: 40 (second to last
element)
Slicing
Slicing allows you to access a sublist or a portion of
the list. The syntax for slicing is [start:stop:step],
where:
start: The index to start slicing (inclusive).
stop: The index to stop slicing (exclusive).
step: The interval between elements to include
(optional).
Basic Slicing
Extracting a portion:
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
(elements from index 1 to 3)
Omitting start and stop:
If start is omitted, slicing starts from the
beginning of the list. If stop is omitted, slicing
goes to the end of the list.
print(my_list[:3]) # Output: [10, 20, 30] (from
the start to index 2)
print(my_list[2:]) # Output: [30, 40, 50] (from
index 2 to the end)
del Statement
Deleting Variables
Syntax:
del variable
Example:
x = 10
print(x) # Output: 10
del x
# print(x) # This will raise a NameError because
x has been deleted.
Deleting List Elements
Syntax:
del list[index]
Example:
my_list = [1, 2, 3, 4]
del my_list[1]
print(my_list) # Output: [1, 3, 4]
Program no.7
Write a program to define a function with
multiple return values.
def name():
return "John","Armin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)
Output:
('John', 'Armin')
John Armin
Program no. 8:
Write a program to define a function using
default arguments
def add_numbers(a, b):
sum = a + b
print('Sum:', sum)
add_ numbers(2, 3)
Output: Sum: 5
Program 9: Write a program to find the length of
the string without using any library functions.
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
Output:
5
Program 10:
Write a program to check if the substring is present
in a given string or not
Source code:
string="helllo world python"
substring="python"
print("Does ",substring," exist in ",string,"?")
if substring in string:
print("Yes")
else:
print("False")
Output:
Does python exist in helllo world python ?
Yes
Program 11:
Write a program to perform the given operations
on a list:
[Link] ii. Insertion iii. slicing
def main():
# Create an initial list
my_list = [1, 2, 3, 4, 5]
print("Initial list:", my_list)
# Addition: Append an element to the list
my_list.append(6)
print("After addition (append 6):", my_list)
# Insertion: Insert an element at a specific index
my_list.insert(2, 10) # Insert 10 at index 2
print("After insertion (insert 10 at index 2):",
my_list)
# Slicing: Get a subset of the list
sliced_list = my_list[1:4] # Slice from index 1 to
3 (4 is exclusive)
print("Sliced list (from index 1 to 3):", sliced_list)
if __name__ == "__main__":
main()
Output:
Initial list: [1, 2, 3, 4, 5]
After addition (append 6): [1, 2, 3, 4, 5, 6]
After insertion (insert 10 at index 2): [1, 2, 10, 3, 4,
5, 6]
Sliced list (from index 1 to 3): [2, 10, 3]
Program no.12
Write a program to perform any 5 built-in
functions by taking any list.
def main():
# Example list
my_list = [3, 1, 7, 2, 5]
# 1. len() - Length of the list
print("Length of the list:", len(my_list))
# 2. max() - Maximum element in the list
print("Maximum element in the list:",
max(my_list))
# 3. min() - Minimum element in the list
print("Minimum element in the list:",
min(my_list))
# 4. sum() - Sum of all elements in the list
print("Sum of all elements in the list:",
sum(my_list))
# 5. sorted() - Sorted version of the list
sorted_list = sorted(my_list)
print("Sorted list:", sorted_list)
if __name__ == "__main__":
main()
Output:
Length of the list: 5
Maximum element in the list: 7
Minimum element in the list: 1
Sum of all elements in the list: 18
Sorted list: [1, 2, 3, 5, 7]
Creating Dictionary
A Python dictionary is a data structure that stores
the value in key:value pairs.
dict = {
1: 'Python',
2: 'dictionary',
3: 'example'
}
Syntax
dict_var = {key1 : value1, key2 : value2, …..}
Example:
Dict = {1: 'hello', 2: 'every', 3: 'one'}
print(Dict)
Accessing and Modifying key: value Pairs in
Dictionaries
A dictionary is quite a useful data structure in
Python programming that is usually used to hash a
particular key with value so that it can be retrieved
efficiently.
To access an item in the dictionary, refer to its key
name inside square brackets.
Example
dict = {
"country" : "India",
"continent" : "Asia",
"Other_name" : "Bharat"
}
x = dict["continent"]
print(x)
Output
Asia
Built-In Functions Used on Dictionaries,
Dictionary Methods
Python Dictionary is like a map that is used to
store data in the form of a key: value pair. Python
provides various built-in functions to deal with
dictionaries. In this article, we will see a list of all
the functions provided by Python to work with
dictionaries.
List of Python Dictionary Methods
Python provides several built-in methods for
dictionaries that allow for efficient manipulation,
access, and transformation of dictionary data.
Here’s a list of some important Python dictionary
methods:
Functions Name Descriptions
Removes all items
clear() from the dictionary
Returns a shallow
copy of the
copy() dictionary
Creates a dictionary
from the given
fromkeys() sequence
Returns the value
get() for the given key
Return the list with
all dictionary keys
items() with values
keys() Returns a view
object that displays
Functions Name Descriptions
a list of all the keys
in the dictionary in
order of insertion
Returns and
removes the element
pop() with the given key
Returns and
removes the key-
value pair from the
popitem() dictionary
Returns the value of
a key if the key is in
the dictionary else
inserts the key with
a value to the
setdefault() dictionary
values() Returns a view
object containing all
dictionary values,
which can be
Functions Name Descriptions
accessed and
iterated through
efficiently
Updates the
dictionary with the
elements from
another dictionary
or an iterable of
key-value pairs.
With this method,
you can include new
data or merge it
with existing
update() dictionary entries
del Statement:
Python’s del statement is used to delete variables and
objects in the Python program. Iterable objects such
as user-defined objects, lists, set, tuple, dictionary,
variables defined by the user, etc. can be deleted from
existence and from the memory locations in Python
using the del statement. The 2 reasons for using the
del statement are – The first is to remove elements
from dicts and lists by index; for lists, you can also
delete a slice. The second reason is to unbind a
variable. Deleting a variable has no greater impact on
memory use than changing the value to None.
To delete a variable or an object in Python, we use
the following syntax –
del obj_name[optional]
where,
obj_name = name of the variable, user-defined
object, list, tuple, set, dictionary, etc.
[optional] = Index value for slicing/deleting specific
data elements from the object iterables.
Example
games = ['cricket', 'football', 'hockey', 'golf', 'chess']
del games[2]
print('Games list:', games)
print()
food = ['burger', 'pizza', 'pattice', 'sandwich']
del food
print(food)
Output
Games list: ['cricket', 'football', 'golf', 'chess']
Traceback (most recent call last):
File "", line 9, in
NameError: name 'food' is not defined
Tuples and Sets: Creating Tuples
Python Tuple is a collection of Python
Programming objects much like a list. The sequence
of values stored in a tuple can be of any type, and
they are indexed by integers. Values of a tuple are
syntactically separated by ‘commas‘.
Creating a Tuple
In Python Programming, tuples are created by
placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping
the data sequence.
Python Program to Demonstrate the Addition of
Elements in a Tuple.
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple
# with the use of string
Tuple1 = ('VIGNAN', 'COLLEGE')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('VIGNAN')
print("\nTuple with the use of function: ")
print(Tuple1)
OUTPUT:
InitialemptyTuple:()
TuplewiththeuseofString:('VIGNAN','COLLEGE')
TupleusingList:
(1,2,45,6)
Tuplewiththeuseoffunction:
('V', 'I', 'G', 'N', 'A', 'N')
Basic Tuple Operations, tuple() Function, Indexing
and Slicing in Tuples, Built-In Functions Used on
Tuples, Relation between Tuples and Lists
Here are some basic operations you can perform
with tuples in Python:
1. Creating a Tuple
A tuple is defined by placing values inside
parentheses () separated by commas.
my_tuple = (1, 2, 3)
empty_tuple = ()
2. Accessing Tuple Elements
You can access elements of a tuple using indexing,
starting from 0.
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
3. Slicing a Tuple
Tuples can be sliced to get a sub-part of the tuple.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
4. Tuple Length
You can use the len() function to get the length of a
tuple.
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
5. Concatenating Tuples
You can concatenate two or more tuples using the +
operator.
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
6. Repeating Tuples
You can repeat elements of a tuple using the *
operator.
my_tuple = (1, 2)
result = my_tuple * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
7. Checking for an Element
You can check if an element exists in a tuple using
the in operator.
my_tuple = (1, 2, 3)
print(2 in my_tuple) # Output: True
print(4 in my_tuple) # Output: False
8. Tuple Unpacking
You can unpack the elements of a tuple into
variables.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
9. Converting a Tuple to a List
You can convert a tuple to a list using list().
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
10. Converting a List to a Tuple
Similarly, you can convert a list to a tuple using
tuple().
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
11. Tuple Methods
count(x): Returns the number of times x appears
in the tuple.
index(x): Returns the index of the first
occurrence of x in the tuple.
my_tuple = (1, 2, 3, 1, 2, 1)
print(my_tuple.count(1)) # Output: 3
print(my_tuple.index(2)) # Output: 1
12. Tuples are Immutable
Tuples cannot be changed after creation. Any
operation that tries to change a tuple will result in an
error.
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # TypeError: 'tuple' object does
not support item assignment
Tuple as Dictionary Keys
One of the main relationships between tuples and
dictionaries is that tuples can be used as dictionary
keys, whereas lists cannot. This is because tuples are
immutable (their elements cannot be changed), and
dictionaries require their keys to be immutable and
hashable.
For example:
# Using a tuple as a dictionary key
my_dict = {(1, 2): "point 1", (3, 4): "point 2"}
print(my_dict[(1, 2)]) # Output: "point 1"
Here, the tuples (1, 2) and (3, 4) are used as keys in
the dictionary.
2. Dictionaries Store Key-Value Pairs
Dictionaries store key-value pairs, and tuples can
sometimes be used to represent the values stored in
the dictionary.
For example:
# Dictionary with tuple values
student_scores = {"John": (85, 90), "Jane": (88, 92)}
print(student_scores["John"]) # Output: (85, 90)
In this case, the dictionary stores student names as
keys, and the corresponding exam scores are stored
as tuples.
3. Tuples in a Dictionary's .items() Method
The .items() method of a dictionary returns a list of
tuples, where each tuple represents a key-value pair.
For example:
my_dict = {"a": 1, "b": 2, "c": 3}
print(list(my_dict.items())) # Output: [('a', 1), ('b',
2), ('c', 3)]
Using zip() Function, Sets, Set Methods, Frozenset.
1. zip() Function
The zip() function in Python is used to combine
multiple iterables (like lists, tuples, etc.) element by
element into tuples. The result is an iterator of
tuples, where the i-th tuple contains the i-th element
from each of the input iterables.
Example:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
# Using zip() to combine
zipped = zip(list1, list2)
print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
If the iterables are of unequal length, zip() stops
when the shortest iterable is exhausted:
list1 = [1, 2]
list2 = ['a', 'b', 'c']
print(list(zip(list1, list2))) # Output: [(1, 'a'), (2, 'b')]
2. Sets in Python
A set is an unordered collection of unique elements.
Unlike lists or tuples, sets are mutable, but they do
not allow duplicate elements.
Creating a Set:
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
# Empty set is created using set() not {}
empty_set = set()
Key Features of Sets:
Unordered: Elements do not have a fixed order.
Unique Elements: A set cannot have duplicate
elements.
Mutable: Elements can be added or removed.
3. Set Methods
Here are some common set operations and methods:
Add Element:
my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
Remove Element:
my_set.remove(3) # Raises an error if element not
found
print(my_set) # Output: {1, 2, 4, 5}
# Use discard() if you don't want an error when
element is missing
my_set.discard(10) # No error
Union of Sets:
Combines all elements from both sets (duplicates are
removed).
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print([Link](set2)) # Output: {1, 2, 3, 4, 5}
Intersection of Sets:
Finds the common elements in both sets.
print([Link](set2)) # Output: {3}
Difference of Sets:
Finds elements in the first set that are not in the
second.
print([Link](set2)) # Output: {1, 2}
Symmetric Difference:
Finds elements in either set but not both.
print(set1.symmetric_difference(set2)) # Output: {1,
2, 4, 5}
Check Membership:
print(1 in set1) # Output: True
4. Frozen Set
A frozenset is an immutable version of a set. Once
created, its elements cannot be changed, added, or
removed. This makes it useful as keys in dictionaries
or other situations where immutability is required.
Creating a Frozenset:
my_frozenset = frozenset([1, 2, 3, 4])
print(my_frozenset) # Output: frozenset({1, 2, 3,
4})
Frozenset Operations:
While frozensets are immutable, you can still
perform operations like union, intersection, etc., and
they will return new frozensets.
set1 = frozenset([1, 2, 3])
set2 = frozenset([3, 4, 5])
print([Link](set2)) # Output: frozenset({1, 2, 3,
4, 5})
print([Link](set2)) # Output:
frozenset({3})
Experiments:
[Link] a program to create tuples (name, age,
address, college) for at least two members and
concatenate the tuples and print the concatenated
tuples.
Source code:
# Creating tuples for two members
member1 = ("Alice", 22, "123 Elm St", "Harvard")
member2 = ("Bob", 23, "456 Oak St", "MIT")
# Concatenating the tuples
concatenated_tuple = member1 + member2
# Printing the concatenated tuple
print("Concatenated Tuple:", concatenated_tuple)
Output:
Concatenated Tuple: ('Alice', 22, '123 Elm St',
'Harvard', 'Bob', 23, '456 Oak St', 'MIT')
[Link] a program to count the number of vowels
in a string (No control flow allowed).
Source code:
# Input string
input_string = "OpenAI creates amazing AI models"
# Set of vowels
vowels = set("aeiouAEIOU")
# Count the number of vowels using filter and len
vowel_count = len(list(filter(vowels.__contains__,
input_string)))
# Print the number of vowels
print("Number of vowels:", vowel_count)
Output:
Number of vowels: 12
[Link] a program to check if a given key exists in
a dictionary or not.
Source Code:
# Sample dictionary
my_dict = {
"name": "Alice",
"age": 22,
"address": "123 Elm St",
"college": "Harvard"
}
# Key to check
key_to_check = "age"
# Check if the key exists in the dictionary
if key_to_check in my_dict:
print(f"The key '{key_to_check}' exists in the
dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in
the dictionary.")
Output:
The key 'age' exists in the dictionary.
[Link] a program to add a new key-value pair to
an existing dictionary.
Source Code:
# Existing dictionary
my_dict = {
"name": "Alice",
"age": 22,
"address": "123 Elm St",
"college": "Harvard"
}
# New key-value pair
new_key = "major"
new_value = "Computer Science"
# Adding the new key-value pair to the dictionary
my_dict[new_key] = new_value
# Printing the updated dictionary
print("Updated Dictionary:", my_dict)
Output:
Updated Dictionary: {'name': 'Alice', 'age': 22,
'address': '123 Elm St', 'college': 'Harvard', 'major':
'Computer Science'}
[Link] a program to sum all the items in a given
dictionary.
Source code:
# Given dictionary
my_dict = {
"item1": 10,
"item2": 20,
"item3": 30,
"item4": 40
}
# Summing all the values in the dictionary
total_sum = sum(my_dict.values())
# Printing the total sum
print("Sum of all values in the dictionary:",
total_sum)
Output:
Sum of all values in the dictionary: 100
Types of Files:
In Python, different types of files are used for storing
and handling various kinds of data. Here are the
common file types and how they are generally used:
1. Text Files
Extension: .txt, .py, .csv, .json, etc.
Description: These files contain human-
readable data in plain text format.
Usage:
o .txt: For general text storage.
o .py: Python source code.
o .csv: Comma-separated values for tabular
data.
o .json: JavaScript Object Notation for
structured data storage.
Code:
# Reading a text file
with open('[Link]', 'r') as file:
content = [Link]()
2. Binary Files
Extension: .bin, .exe, .dat, etc.
Description: These files store data in binary
format, which is not human-readable. They are
used for storing things like images, executables,
and other non-text data.
Usage: Binary files are read and written in bytes.
Python Code:
# Reading a binary file
with open('[Link]', 'rb') as file:
content = [Link]()
3. Image Files
Extension: .jpg, .png, .gif, .bmp, etc.
Description: These files store image data.
Usage: They are often handled using libraries
such as Pillow.
from PIL import Image
img = [Link]('[Link]')
[Link]()
4. Audio Files
Extension: .mp3, .wav, .ogg, etc.
Description: These files store audio data.
Usage: They are often handled using libraries
such as wave, pydub, and pygame.
import wave
with [Link]('[Link]', 'rb') as audio_file:
audio_data =
audio_file.readframes(audio_file.getnframes())
5. Video Files
Extension: .mp4, .avi, .mkv, etc.
Description: Video files store multimedia data
(audio and video).
Usage: Libraries like OpenCV and moviepy are
used to handle them.
import cv2
video = [Link]('example.mp4')
6. Compressed Files
Extension: .zip, .tar, .gz, etc.
Description: These files store compressed data,
often combining multiple files into one.
Usage: Python provides libraries like zipfile and
tarfile for working with compressed files.
import zipfile
with [Link]('[Link]', 'r') as zip_ref:
zip_ref.extractall('extracted_folder')
Creating and Reading Text Data
1. Creating Text Data (Writing to a File)
You can create a text file and write data into it using
Python's open() function with the mode 'w' (write) or
'a' (append).
Example: Writing to a File
# Writing to a text file
with open('[Link]', 'w') as file:
[Link]("Hello, this is an example of writing text
to a file.\n")
[Link]("You can add multiple lines of text.\n")
2. Reading Text Data
You can read text data from a file using the open()
function in 'r' (read) mode. Python offers several
methods to read data, such as read(), readline(), and
readlines().
Example: Reading the Entire File
# Reading the entire content of a text file
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
Methods to Read and Write Data:
Methods to Read Data
[Link]()
o Reads the entire content of a file as a single
string.
o Useful for reading small or entire files at
once.
Example:
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
[Link]()
o Reads a single line from the file.
o The method moves the file pointer to the
beginning of the next line after each call.
Example:
with open('[Link]', 'r') as file:
first_line = [Link]()
print(first_line)
[Link]()
o Reads all lines from a file and returns them
as a list of strings.
o Each line will be a separate string element in
the list, including the newline character (\n).
Example:
with open('[Link]', 'r') as file:
lines = [Link]()
print(lines)
[Link] Through the File Object (Line by
Line)
o You can iterate over the file object to read
one line at a time without loading the entire
file into memory.
o This is especially useful for reading large
files.
Example:
with open('[Link]', 'r') as file:
for line in file:
print(line, end='') # 'end' to avoid double
new lines
Reading and Writing Binary Files
Writing Binary Data:
write() (in binary mode): Writes binary data to
the file.
Example:
with open('[Link]', 'wb') as file:
binary_data = b'\x00\x01\x02\x03' # Some
binary data
[Link](binary_data)
Reading Binary Data:
read() (in binary mode): Reads binary data
from the file.
Example:
with open('[Link]', 'rb') as file:
binary_data = [Link]()
print(binary_data)
Modes for Reading and Writing
Mode Description
Read (default mode), raises an error if the
'r'
file does not exist.
Write (creates the file if it doesn't exist,
'w'
overwrites if it does).
Append (creates the file if it doesn't exist,
'a'
appends to the end if it does).
'r+' Read and write (file must exist).
Write and read (creates the file if it
'w+'
doesn't exist, overwrites if it does).
Append and read (creates the file if it
'a+' doesn't exist, appends to the end if it
does).
Mode Description
'rb', 'wb', Same as the text modes but used for
'ab', etc. binary files (non-text data).
PICKLE MODULE
Basic Operations
[Link] (Serialization)
o Save an object to a file.
import pickle
# Sample Python object (a dictionary)
data = {'name': 'John', 'age': 30, 'city': 'New
York'}
# Open a file in write-binary mode
with open('[Link]', 'wb') as file:
[Link](data, file)
[Link] (Deserialization)
o Load an object from a file.
python
import pickle
# Open the file in read-binary mode
with open('[Link]', 'rb') as file:
data = [Link](file)
print(data)
Reading and Writing CSV Files
Basic CSV Operations
1. Writing to a CSV File
You can use the [Link] to write data to a CSV
file.
import csv
# Data to write into the CSV file
data = [
['Name', 'Age', 'City'],
['John', 28, 'New York'],
['Anna', 22, 'London'],
['Mike', 32, 'San Francisco']
]
# Writing to a CSV file
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](data)
2. Reading from a CSV File
To read data from a CSV file, use [Link].
import csv
# Reading from a CSV file
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
Python os and [Link] Modules
1. os Module
The os module provides a variety of functions to
interact with the operating system.
Common Operations with os Module
Getting the Current Working Directory:
import os
print([Link]()) # Returns the current
working directory
Changing the Current Working Directory:
[Link]('/path/to/directory') # Change the
working directory
Listing Files and Directories:
print([Link]()) # Lists files in the current
directory
print([Link]('/path/to/directory')) # Lists files
in a specific directory
Creating a Directory:
[Link]('new_directory') # Create a single
directory
Creating Nested Directories:
[Link]('parent_dir/child_dir/
grandchild_dir') # Create multiple directories
Removing a Directory:
[Link]('directory_to_remove') # Remove a
directory (only if empty)
Removing a File:
[Link]('file_to_remove.txt') # Remove a file
Renaming a File or Directory:
[Link]('old_name.txt', 'new_name.txt') #
Rename a file or directory
Executing System Commands: You can
execute a shell command using [Link](). For
example:
[Link]('ls') # Executes a shell command
2. [Link] Module
The [Link] module provides utilities to manipulate
and query file paths. It helps with platform-
independent path manipulation, avoiding issues
when working with paths on different operating
systems.
Common Operations with [Link]
Joining Paths:
import os
# Join multiple path components into a single
path
path = [Link]('folder', 'subfolder', '[Link]')
print(path) # Returns 'folder/subfolder/[Link]'
(or with backslashes on Windows)
Checking if a Path Exists:
print([Link]('path/to/file_or_directory'))
# Returns True or False
Checking if a Path is a File:
print([Link]('path/to/[Link]')) # Returns
True if it's a file
Object-Oriented Programming: Classes and
Objects
1. Classes: A class is like a blueprint for creating
objects (instances). It defines properties
(attributes) and behaviors (methods) that the
objects created from the class will have.
2. Objects: An object is an instance of a class. It
represents a specific example that follows the
blueprint provided by the class.
Basic Concepts of OOP in Python
1. Defining a Class
A class in Python is defined using the class
keyword.
class Car:
# Class attribute (shared by all instances)
wheels = 4
# Constructor method to initialize object attributes
def __init__(self, make, model, year):
# Object attributes (specific to each instance)
[Link] = make
[Link] = model
[Link] = year
# Method (Function inside a class) to display car
details
def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}
with {[Link]} wheels")
2. Creating Objects (Instances)
You can create objects (instances) of the class by
calling the class name and passing the required
arguments to the constructor.
python
Copy code
# Create instances of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2019)
# Accessing object attributes
print([Link]) # Output: Toyota
print([Link]) # Output: Civic
# Calling a method on an object
car1.display_info() # Output: 2020 Toyota Corolla
with 4 wheels
car2.display_info() # Output: 2019 Honda Civic
with 4 wheels
3. Instance and Class Variables
Instance variables (e.g., make, model, year) are
unique to each instance.
Class variables (e.g., wheels) are shared by all
instances of the class.
python
Copy code
[Link] = 6 # This changes the wheels for car1
only, not for car2
print([Link]) # Output: 6
print([Link]) # Output: 4
Creating Objects in Python
Defining a Class
A class is like a blueprint that defines the attributes
(data) and methods (functions) an object will have.
You define a class using the class keyword.
# Define a class
class Person:
# Constructor method to initialize the attributes
def __init__(self, name, age):
[Link] = name # Object attribute
[Link] = age # Object attribute
# Method to display information
def greet(self):
print(f"Hello, my name is {[Link]} and I am
{[Link]} years old.")
__init__(): This is the constructor method,
called when an object is created. It initializes the
object’s attributes.
Attributes: name and age are the attributes for
each Person object.
Method: greet() is a method that prints out a
greeting using the object's attributes.
2. Creating Objects
You create an object (an instance of the class) by
calling the class with the required arguments.
# Create an object (instance) of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing object attributes
print([Link]) # Output: Alice
print([Link]) # Output: 25
# Calling a method on an object
[Link]() # Output: Hello, my name is Alice
and I am 30 years old.
[Link]() # Output: Hello, my name is Bob
and I am 25 years old.
Constructor Method
The constructor method in Python is a special
method used to initialize an object when it is
created. This method is called __init__(). It
allows you to assign values to object attributes or
perform any setup necessary for the object.
Syntax of the Constructor
The constructor method is defined within a class
using the def keyword, and it is named
__init__(). The first parameter of the constructor
is always self, which refers to the object itself.
Other parameters are used to initialize the
object’s attributes.
Example: Basic Constructor
class Person:
# Constructor method to initialize attributes
def __init__(self, name, age):
[Link] = name # Object attribute 'name'
[Link] = age # Object attribute 'age'
# Method to display information
def display(self):
print(f"My name is {[Link]} and I am
{[Link]} years old.")
# Creating objects of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing object attributes
print([Link]) # Output: Alice
print([Link]) # Output: 25
# Calling the method
[Link]() # Output: My name is Alice
and I am 30 years old.
[Link]() # Output: My name is Bob and I
am 25 years old.
Class Attributes Vs Data Attributes:
In Python, attributes can be classified into two main
categories: class attributes and instance (data)
attributes. Understanding the distinction between
these two types of attributes is crucial for effective
object-oriented programming. Let’s break down the
differences:
1. Class Attributes
Definition: Class attributes are defined within a
class and are shared across all instances of that
class. They belong to the class itself rather than
to any individual instance.
Scope: Class attributes can be accessed directly
using the class name or through any instance of
the class.
Use Cases: Class attributes are often used for
constants or shared values that apply to all
instances.
Example:
class Dog:
# Class attribute
species = "Canis lupus familiaris" # Shared by all
instances
def __init__(self, name, age):
[Link] = name # Instance attribute
[Link] = age # Instance attribute
# Creating instances of Dog
dog1 = Dog("Buddy", 5)
dog2 = Dog("Max", 3)
# Accessing class attribute
print([Link]) # Output: Canis lupus
familiaris
print([Link]) # Output: Canis lupus
familiaris
print([Link]) # Output: Canis lupus
familiaris
2. Instance (Data) Attributes
Definition: Instance attributes (also called data
attributes) are specific to an instance of a class.
They are defined within the constructor method
(__init__) and are unique to each object.
Scope: Instance attributes can only be accessed
through an instance of the class (using self).
Use Cases: Instance attributes are used to hold
data that is unique to each object, such as
properties or characteristics of that particular
instance.
Example:
class Dog:
species = "Canis lupus familiaris" # Class
attribute
def __init__(self, name, age):
[Link] = name # Instance attribute
[Link] = age # Instance attribute
# Creating instances of Dog
dog1 = Dog("Buddy", 5)
dog2 = Dog("Max", 3)
# Accessing instance attributes
print([Link]) # Output: Buddy
print([Link]) # Output: 3
Encapsulation
Encapsulation is the practice of bundling the data
(attributes) and methods that operate on that data
into a single unit, or class. You can control access to
attributes by making them private (inaccessible
outside the class) using a double underscore (__).
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")
def display_balance(self):
print(f"Balance: ${self.__balance}")
# Creating an instance of BankAccount
account = BankAccount("Alice", 1000)
[Link](500)
account.display_balance() # Output: Balance: $1500
# Trying to access the private attribute directly (this
will raise an error)
# print(account.__balance) # AttributeError:
'BankAccount' object has no attribute '__balance'
Inheritance
Inheritance allows a class (child class) to inherit
attributes and methods from another class (parent
class). This promotes code reuse.
class Vehicle:
def __init__(self, brand, year):
[Link] = brand
[Link] = year
def start(self):
print(f"{[Link]} is starting...")
# Child class Car inherits from Vehicle
class Car(Vehicle):
def __init__(self, brand, year, model):
super().__init__(brand, year) # Inherit
attributes from parent class
[Link] = model
def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")
# Create an instance of Car (which inherits from
Vehicle)
car = Car("Tesla", 2022, "Model S")
[Link]() # Inherited method from Vehicle: Output:
Tesla is starting...
car.display_info() # Output: 2022 Tesla Model S
super(): This function allows the child class to
access methods and attributes from the parent
class.
Polymorphism
Polymorphism allows methods to have the same
name but behave differently based on the object or
class that calls them.
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must
implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Create instances of Dog and Cat
dog = Dog()
cat = Cat()
# Call the speak method
print([Link]()) # Output: Woof!
print([Link]()) # Output: Meow!
18. Write a program to sort words in a file and
put them in another file. The output file should
have only lower-case words, so any upper-case
words from source must be lowered.
Source code:
def sort_words_in_file(input_file, output_file):
try:
# Step 1: Read the words from the source
file
with open(input_file, 'r') as infile:
# Read words, split by whitespace and
convert to lower case
words = [Link]().split()
words = [[Link]() for word in
words]
# Step 2: Sort the words
sorted_words = sorted(set(words)) # Use
set to remove duplicates
# Step 3: Write the sorted words into the
output file
with open(output_file, 'w') as outfile:
for word in sorted_words:
[Link](word + '\n')
print(f"Sorted words have been written to
{output_file}.")
except FileNotFoundError:
print(f"Error: The file {input_file} does
not exist.")
except Exception as e:
print(f"An error occurred: {e}")
Example Input File ([Link])
Apple
banana
Cherry
apple
Banana
Cherry
Example Output File (sorted_words.txt)
apple
banana
cherry
19. Python program to print each line of a file in
reverse order.
Source code:
def print_lines_in_reverse_order(file_path):
try:
# Open the file in read mode
with open(file_path, 'r') as file:
# Read lines from the file
lines = [Link]()
# Print each line in reverse order
for line in lines:
print([Link]()[::-1]) # Strip to remove
leading/trailing whitespace and reverse the line
except FileNotFoundError:
print(f"Error: The file '{file_path}' does
not exist.")
except Exception as e:
print(f"An error occurred: {e}")
Example Input File ([Link])
Hello, World!
Python is great.
File handling in Python.
Example Output
!dlroW ,olleH
.taerg si nohtyP
.nohtyP ni gnidnal ehT
20. Python program to compute the number of
characters, words and lines in a file.
Source code
def compute_file_statistics(file_path):
try:
# Initialize counters
num_lines = 0
num_words = 0
num_characters = 0
# Open the file in read mode
with open(file_path, 'r') as file:
for line in file:
num_lines += 1 # Increment line
counter
num_characters += len(line) # Count
characters in the line
num_words += len([Link]()) #
Count words in the line
# Print the results
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters:
{num_characters}")
except FileNotFoundError:
print(f"Error: The file '{file_path}' does
not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
file_path = '[Link]' # Replace with your
file path
compute_file_statistics(file_path)
Example Input File ([Link])
Hello, World!
Python programming is fun.
This is a sample text file.
Example Output
Number of lines: 3
Number of words: 10
Number of characters: 60
21. Write a program to create, display, append,
insert and reverse the order of the items in the
array.
Source code
def display_array(arr):
"""Display the array."""
print("Current array:", arr)
def append_to_array(arr, item):
"""Append an item to the array."""
[Link](item)
print(f"'{item}' appended to the array.")
def insert_to_array(arr, index, item):
"""Insert an item at a specific index in the
array."""
if index < 0 or index > len(arr):
print("Error: Index out of bounds.")
else:
[Link](index, item)
print(f"'{item}' inserted at index {index}.")
def reverse_array(arr):
"""Reverse the array."""
[Link]()
print("Array reversed.")
def main():
# Create an array
array = []
# Display initial empty array
display_array(array)
# Append items to the array
append_to_array(array, 'apple')
append_to_array(array, 'banana')
append_to_array(array, 'cherry')
# Display after appending
display_array(array)
# Insert an item
insert_to_array(array, 1, 'orange') # Insert
'orange' at index 1
# Display after insertion
display_array(array)
# Reverse the array
reverse_array(array)
# Display final array
display_array(array)
if __name__ == "__main__":
main()
Output:
Current array: []
'apple' appended to the array.
'apple' appended to the array.
'banana' appended to the array.
'cherry' appended to the array.
Current array: ['apple', 'banana', 'cherry']
'orange' inserted at index 1.
Current array: ['apple', 'orange', 'banana',
'cherry']
Array reversed.
Current array: ['cherry', 'banana', 'orange',
'apple']
22. Write a program to add, transpose and
multiply two matrices.
Source code:
def add_matrices(matrix_a, matrix_b):
"""Add two matrices."""
rows = len(matrix_a)
cols = len(matrix_a[0])
result = [[0 for _ in range(cols)] for _ in
range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = matrix_a[i][j] + matrix_b[i]
[j]
return result
def transpose_matrix(matrix):
"""Transpose a matrix."""
rows = len(matrix)
cols = len(matrix[0])
result = [[0 for _ in range(rows)] for _ in
range(cols)]
for i in range(rows):
for j in range(cols):
result[j][i] = matrix[i][j]
return result
def multiply_matrices(matrix_a, matrix_b):
"""Multiply two matrices."""
rows_a = len(matrix_a)
cols_a = len(matrix_a[0])
rows_b = len(matrix_b)
cols_b = len(matrix_b[0])
# Check if multiplication is possible
if cols_a != rows_b:
raise ValueError("Number of columns in
the first matrix must be equal to the number of
rows in the second.")
# Initialize the result matrix
result = [[0 for _ in range(cols_b)] for _ in
range(rows_a)]
# Perform matrix multiplication
for i in range(rows_a):
for j in range(cols_b):
for k in range(cols_a):
result[i][j] += matrix_a[i][k] *
matrix_b[k][j]
return result
def print_matrix(matrix):
"""Print a matrix."""
for row in matrix:
print(row)
def main():
# Define two matrices
matrix_a = [
[1, 2, 3],
[4, 5, 6]
]
matrix_b = [
[7, 8, 9],
[10, 11, 12]
]
print("Matrix A:")
print_matrix(matrix_a)
print("\nMatrix B:")
print_matrix(matrix_b)
# Add matrices
print("\nAddition of A and B:")
added_matrix = add_matrices(matrix_a,
matrix_b)
print_matrix(added_matrix)
# Transpose a matrix
print("\nTranspose of Matrix A:")
transposed_matrix_a =
transpose_matrix(matrix_a)
print_matrix(transposed_matrix_a)
# Multiply matrices (A * transposed B)
print("\nMultiplication of A and Transpose of
B:")
transposed_matrix_b =
transpose_matrix(matrix_b)
multiplied_matrix =
multiply_matrices(matrix_a,
transposed_matrix_b)
print_matrix(multiplied_matrix)
if __name__ == "__main__":
main()
Output:
Matrix A:
[1, 2, 3]
[4, 5, 6]
Matrix B:
[7, 8, 9]
[10, 11, 12]
Addition of A and B:
[8, 10, 12]
[14, 16, 18]
Transpose of Matrix A:
[1, 4]
[2, 5]
[3, 6]
Multiplication of A and Transpose of B:
[ 58, 64]
[139, 154]
23. Write a Python program to create a class that
represents a shape. Include methods to calculate
its area and perimeter. Implement subclasses for
different shapes like circle, triangle, and square.
Source code:
import math
# Base class for Shape
class Shape:
def area(self):
raise NotImplementedError("Area method must
be implemented by subclasses.")
def perimeter(self):
raise NotImplementedError("Perimeter method
must be implemented by subclasses.")
# Subclass for Circle
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return [Link] * ([Link] ** 2)
def perimeter(self):
return 2 * [Link] * [Link]
# Subclass for Triangle
class Triangle(Shape):
def __init__(self, base, height, side1, side2):
[Link] = base
[Link] = height
self.side1 = side1
self.side2 = side2
def area(self):
return 0.5 * [Link] * [Link]
def perimeter(self):
return [Link] + self.side1 + self.side2
# Subclass for Square
class Square(Shape):
def __init__(self, side):
[Link] = side
def area(self):
return [Link] ** 2
def perimeter(self):
return 4 * [Link]
# Function to demonstrate the functionality
def main():
# Create instances of different shapes
circle = Circle(radius=5)
triangle = Triangle(base=6, height=4, side1=5,
side2=7)
square = Square(side=4)
# Display area and perimeter for Circle
print("Circle:")
print("Area:", [Link]())
print("Perimeter:", [Link]())
print()
# Display area and perimeter for Triangle
print("Triangle:")
print("Area:", [Link]())
print("Perimeter:", [Link]())
print()
# Display area and perimeter for Square
print("Square:")
print("Area:", [Link]())
print("Perimeter:", [Link]())
if __name__ == "__main__":
main()
Output:
Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793
Triangle:
Area: 12.0
Perimeter: 18
Square:
Area: 16
Perimeter: 16
Functional programming is a programming
paradigm in which we try to bind everything in
a pure mathematical functions style. It is a
declarative type of programming style.
Its main focus is on ” what to solve” in contrast
to an imperative style where the main focus is
“how to solve“. It uses expressions instead of
statements.
An expression is evaluated to produce a value
whereas a statement is executed to assign
variables.
Concepts of Functional Programming
Any Functional programming language is expected
to follow these concepts.
Pure Functions: These functions have two main
properties. First, they always produce the same
output for the same arguments irrespective of
anything else. Secondly, they have no side-effects
i.e. they do modify any argument or global
variables or output something.
Recursion: There are no “for” or “while” loop in
functional languages. Iteration in functional
languages is implemented through recursion.
Functions are First-Class and can be Higher-
Order: First-class functions are treated as first-
class variables. The first-class variables can be
passed to functions as a parameter, can be returned
from functions, or stored in data structures.
Variables are Immutable: In functional
programming, we can’t modify a variable after it’s
been initialized. We can create new variables – but
we can’t modify existing variables.
Functional Programming in Python
It also supports Functional Programming
paradigms without the support of any special
features or libraries.
Pure Functions
As Discussed above, pure functions have two
properties.
It always produces the same output for the same
arguments. For example, 3+7 will always be 10 no
matter what.
It does not change or modifies the input variable.
The second property is also known as immutability.
The only result of the Pure Function is the value it
returns. They are deterministic. Programs done
using functional programming are easy to debug
because pure functions have no side effects or
hidden I/O. Pure functions also make it easier to
write parallel/concurrent applications. When the
code is written in this style, a smart compiler can do
many things – it can parallelize the instructions,
wait to evaluate results when needing them, and
memorize the
JSON and XML in Python:
A JSON file is a file that stores simple data
structures and objects in JavaScript Object Notation
(JSON) format, which is a standard data interchange
format. It is primarily used for transmitting data
between a web application and a
server.A JSON object contains data in the form of a
key/value pair. The keys are strings and the values
are the JSON types. Keys and values are separated
by a colon. Each entry (key/value pair) is separated
by a comma. JSON files are lightweight, text-based,
human-readable, and can be edited using a text
editor.
XML is a markup language which is designed to
store data. It is case sensitive. XML offers you to
define markup elements and generate customized
markup language. The basic unit in the XML is
known as an element. The XML language has no
predefined tags. It simplifies data sharing, data
transport, platform changes, data availability
Extension of an XML file is .xml
Comparison between JSON and XML
JSON XML
JSON object has
XML data is typeless
a type
JSON types: All XML data should be string
string, number,
JSON XML
array, Boolean
Data is readily
accessible as XML data needs to be parsed
JSON objects
JSON is
Cross-browser XML parsing
supported by
can be tricky
most browsers
JSON has no XML offers the capability to
display display data because it is a
capabilities markup language
XML support various data types
JSON supports
such as number, text, images,
only text and
charts, graphs, etc. It also
number data
provides options for transferring
type.
the structure
NumPy with Python
NumPy is a Python library used for working with
arrays.
It also has functions for working in domain of linear
algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is
an open source project and you can use it freely.
NumPy stands for Numerical Python.
In Python we have lists that serve the purpose of
arrays, but they are slow to process.
NumPy aims to provide an array object that is up to
50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it
provides a lot of supporting functions that make
working with ndarray very easy.
Arrays are very frequently used in data science,
where speed and resources are very important.
NumPy arrays are stored at one continuous place in
memory unlike lists, so processes can access and
manipulate them very efficiently.
This behavior is called locality of reference in
computer science.
This is the main reason why NumPy is faster than
lists. Also it is optimized to work with latest CPU
architectures.
Which Language is NumPy written in?
NumPy is a Python library and is written partially in
Python, but most of the parts that require fast
computation are written in C or C++.
The source code for NumPy is located at this github
repository [Link]
Pandas
What is Pandas?
Pandas is a Python library used for working with
data sets.
It has functions for analyzing, cleaning, exploring,
and manipulating data.
The name "Pandas" has a reference to both "Panel
Data", and "Python Data Analysis" and was created
by Wes McKinney in 2008.
Pandas allows us to analyze big data and make
conclusions based on statistical theories.
Pandas can clean messy data sets, and make them
readable and relevant.
Relevant data is very important in data science.
Pandas gives you answers about the data. Like:
Is there a correlation between two or more
columns?
What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not
relevant, or contains wrong values, like empty or
NULL values. This is called cleaning the data
The source code for Pandas is located at this github
repository [Link]
[Link] program to check whether a JSON string
contains complex object or not.
import json
def is_complex_json(json_str):
try:
# Load JSON string
json_data = [Link](json_str)
# Check if the loaded JSON contains a complex
object
# Complex objects are lists or dictionaries
if isinstance(json_data, (dict, list)):
return True
else:
return False
except [Link]:
# Invalid JSON string
return False
# Test cases
json_str1 = '{"name": "John", "age": 30}' # This is a
complex object (dictionary)
json_str2 = '[1, 2, 3, 4]' # This is a complex object
(list)
json_str3 = '"Hello World"' # This is not a complex
object (string)
json_str4 = '12345' # This is not a complex object
(integer)
print(is_complex_json(json_str1)) # True
print(is_complex_json(json_str2)) # True
print(is_complex_json(json_str3)) # False
print(is_complex_json(json_str4)) # False
Output:
True
True
False
False
[Link] Program to demonstrate NumPy arrays
creation using array () function
import numpy as np
# Creating a 1D array (one-dimensional array)
array_1d = [Link]([1, 2, 3, 4, 5])
print("1D Array:")
print(array_1d)
# Creating a 2D array (two-dimensional array)
array_2d = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array_2d)
# Creating a 3D array (three-dimensional array)
array_3d = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9],
[10, 11, 12]]])
print("\n3D Array:")
print(array_3d)
# Creating an array with mixed data types (NumPy
will cast all elements to a common type)
mixed_array = [Link]([1, 2.5, 3])
print("\nArray with mixed data types:")
print(mixed_array)
# Creating an array from a tuple
array_from_tuple = [Link]((10, 20, 30))
print("\nArray from tuple:")
print(array_from_tuple)
# Creating an empty array (no elements)
empty_array = [Link]([])
print("\nEmpty Array:")
print(empty_array)
# Creating an array with specified data type
array_with_dtype = [Link]([1, 2, 3], dtype=float)
print("\nArray with specified data type (float):")
print(array_with_dtype)
Output:
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Array with mixed data types:
[1. 2.5 3. ]
Array from tuple:
[10 20 30]
Empty Array:
[]
Array with specified data type (float):
[1. 2. 3.]
[Link] program to demonstrate use of ndim,
shape, size, dtype.
import numpy as np
# Creating a 2D NumPy array
array_2d = [Link]([[1, 2, 3], [4, 5, 6]])
# Display the array
print("Array:")
print(array_2d)
# Number of dimensions (ndim)
print("\nNumber of dimensions (ndim):",
array_2d.ndim)
# Shape of the array (shape)
print("Shape of the array (shape):", array_2d.shape)
# Total number of elements (size)
print("Total number of elements (size):",
array_2d.size)
# Data type of the elements (dtype)
print("Data type of the elements (dtype):",
array_2d.dtype)
# Creating a 3D NumPy array
array_3d = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Display the 3D array
print("\n3D Array:")
print(array_3d)
# Demonstrating ndim, shape, size, dtype for the 3D
array
print("\nNumber of dimensions (ndim):",
array_3d.ndim)
print("Shape of the array (shape):", array_3d.shape)
print("Total number of elements (size):",
array_3d.size)
print("Data type of the elements (dtype):",
array_3d.dtype)
Output:
Array:
[[1 2 3]
[4 5 6]]
Number of dimensions (ndim): 2
Shape of the array (shape): (2, 3)
Total number of elements (size): 6
Data type of the elements (dtype): int64
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Number of dimensions (ndim): 3
Shape of the array (shape): (2, 2, 2)
Total number of elements (size): 8
Data type of the elements (dtype): int64
[Link] program to demonstrate basic slicing,
integer and Boolean indexing.
import numpy as np
# Creating a 2D NumPy array for demonstration
array_2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print("Original 2D Array:")
print(array_2d)
# 1. Basic Slicing
# Slicing specific rows and columns
print("\nBasic Slicing - First two rows and
columns 1 to 3:")
sliced_array = array_2d[:2, 1:3] # Get first 2
rows and columns 1 to 2 (slice does not include
upper bound)
print(sliced_array)
# 2. Integer Indexing
# Selecting specific elements based on their
integer indices
print("\nInteger Indexing - Specific elements at
[0,1], [1,2], and [2,3]:")
int_indexing_result = array_2d[[0, 1, 2], [1, 2, 3]]
# Selecting (0,1), (1,2), (2,3)
print(int_indexing_result)
# 3. Boolean Indexing
# Creating a Boolean condition to filter elements
print("\nBoolean Indexing - Elements greater
than 5:")
bool_indexing_result = array_2d[array_2d > 5] #
Get elements greater than 5
print(bool_indexing_result)
Output:
Original 2D Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Basic Slicing - First two rows and columns 1 to 3:
[[2 3]
[6 7]]
Integer Indexing - Specific elements at [0,1], [1,2],
and [2,3]:
[ 2 7 12]
Boolean Indexing - Elements greater than 5:
[ 6 7 8 9 10 11 12]
[Link] program to find min, max, sum,
cumulative sum of array
import numpy as np
# Create a NumPy array for demonstration
array = [Link]([1, 2, 3, 4, 5])
print("Original Array:")
print(array)
# Finding the minimum value
min_value = [Link](array)
print("\nMinimum value in the array:", min_value)
# Finding the maximum value
max_value = [Link](array)
print("Maximum value in the array:", max_value)
# Finding the sum of all elements in the array
sum_value = [Link](array)
print("Sum of all elements in the array:", sum_value)
# Finding the cumulative sum of the array
cumulative_sum = [Link](array)
print("Cumulative sum of the array:",
cumulative_sum)
Output:
Original Array:
[1 2 3 4 5]
Minimum value in the array: 1
Maximum value in the array: 5
Sum of all elements in the array: 15
Cumulative sum of the array: [ 1 3 6 10 15]
[Link] a dictionary with at least five keys and
each key represent value as a list where this list
contains at least ten values and convert this
dictionary as a pandas data frame and explore the
data through the data frame as follows:
a) Apply head () function to the pandas data
frame
b) Perform various data selection operations
on Data Frame
import pandas as pd
# Step 1: Create a dictionary with 5 keys, each
having a list of 10 values
data_dict = {
'Ages': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70],
'Salaries': [50000, 55000, 60000, 65000, 70000,
75000, 80000, 85000, 90000, 95000],
'Departments': ['HR', 'Finance', 'IT', 'Sales',
'Marketing', 'HR', 'Finance', 'IT', 'Sales', 'Marketing'],
'Years_of_Experience': [1, 3, 5, 7, 9, 11, 13, 15,
17, 20],
'Locations': ['New York', 'Los Angeles', 'Chicago',
'Houston', 'Phoenix', 'Philadelphia', 'San Antonio',
'San Diego', 'Dallas', 'San Jose']
}
# Step 2: Convert the dictionary to a pandas
DataFrame
df = [Link](data_dict)
# Step 3: Explore the data using the head() function
print("First 5 rows of the DataFrame using head():")
print([Link]())
# Step 4: Perform various data selection operations
# Select specific columns
print("\nSelect 'Ages' and 'Salaries' columns:")
print(df[['Ages', 'Salaries']])
# Select rows where 'Ages' is greater than 40
print("\nRows where 'Ages' is greater than 40:")
print(df[df['Ages'] > 40])
# Select rows where 'Departments' is 'IT'
print("\nRows where 'Departments' is 'IT':")
print(df[df['Departments'] == 'IT'])
# Select a specific value based on index and column
print("\nSelect the value at index 3 and 'Salaries'
column:")
print([Link][3, 'Salaries'])
# Slice the DataFrame to select specific rows and
columns
print("\nSlice the DataFrame to select rows 2 to 4
and columns 'Ages' and 'Years_of_Experience':")
print([Link][2:4, ['Ages', 'Years_of_Experience']])
Output:
First 5 rows of the DataFrame using head():
Ages Salaries Departments Years_of_Experience
Locations
0 25 50000 HR 1 New York
1 30 55000 Finance 3 Los
Angeles
2 35 60000 IT 5 Chicago
3 40 65000 Sales 7 Houston
4 45 70000 Marketing 9
Phoenix
Select 'Ages' and 'Salaries' columns:
Ages Salaries
0 25 50000
1 30 55000
2 35 60000
3 40 65000
4 45 70000
5 50 75000
6 55 80000
7 60 85000
8 65 90000
9 70 95000
Rows where 'Ages' is greater than 40:
Ages Salaries Departments Years_of_Experience
Locations
4 45 70000 Marketing 9
Phoenix
5 50 75000 HR 11 Philadelphia
6 55 80000 Finance 13 San
Antonio
7 60 85000 IT 15 San Diego
8 65 90000 Sales 17 Dallas
9 70 95000 Marketing 20 San
Jose
Rows where 'Departments' is 'IT':
Ages Salaries Departments Years_of_Experience
Locations
2 35 60000 IT 5 Chicago
7 60 85000 IT 15 San Diego
Select the value at index 3 and 'Salaries' column:
65000
Slice the DataFrame to select rows 2 to 4 and
columns 'Ages' and 'Years_of_Experience':
Ages Years_of_Experience
2 35 5
3 40 7
4 45 9
30. Select any two columns from the above data
frame, and observe the change in one attribute with
respect to other attribute with scatter and plot
operations in matplotlib
import pandas as pd
import numpy as np
#creating sample data
sample_data={'col_name_1':[Link](20),
'col_name_2': [Link](20)}
df= [Link](sample_data)
[Link](x='col_name_1', y='col_name_2', style='o')
Output:
<Axes: xlabel='col_name_1'>