Unit 2
Unit 2
Introduction to python:
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version of Python
0.9.0 was released in 1991.
Features of Python:
o Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal language for
both beginners and experienced programmers. This simplicity can lead to faster development and
reduce the chances of errors.
o Dynamically Typed - The data types of variables are determined during run-time. We do not
need to specify the data type of a variable during writing codes.
o High-level - High-level language means human readable code.
o Compiled and Interpreted - Python code first gets compiled into bytecode, and then interpreted
line by line. When we download the Python in our system form org we download the default
implement of Python known as CPython. CPython is considered to be Complied and Interpreted
both.
o Garbage Collected - Memory allocation and de-allocation are automatically managed.
Programmers do not specifically need to manage the memory.
o Purely Object-Oriented - It refers to everything as an object, including numbers and strings.
o Cross-platform Compatibility - Python can be easily installed on Windows, macOS, and
various Linux distributions, allowing developers to create software that runs across different
operating systems.
o Rich Standard Library - Python comes with several standard libraries that provide ready-to-use
modules and functions for various tasks, ranging from web development and data
manipulation to machine learning and networking.
o Open Source - Python is an open-source, cost-free programming language. It is utilized in
several sectors and disciplines as a result.
For example -
def func():
statement 1
statement 2
…………………
…………………
statement N
In the above example, the statements that are the same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch
programmer. He wanted to create a successor to the ABC programming language that
would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This
marked the official birth of Python as an open-source project. The language was named
after the British comedy series "Monty Python's Flying Circus".
Python development has gone through several stages. In January 1994, Python 1.0 was
released as a usable and stable programming language. This version included many of the
features that are still present in Python today.
From the 1990s to the 2000s, Python gained popularity for its simplicity, readability, and
versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list
comprehensions, garbage collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-
incompatible changes to improve code readability and maintainability.
Throughout 2010s, Python's popularity increased, particularly in fields like data
science, machine learning, and web development. Its rich ecosystem of libraries and
frameworks made it a favourite among developers.
o Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
o Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
o Object-Oriented Language: It supports object-oriented programming, making writing
reusable and modular code easy.
o Open-Source Language: Python is open-source and free to use, distribute and modify.
o Extensible: Python can be extended with modules written in C, C++, or other languages.
o GUI Programming Support: Python provides several GUI frameworks, such
as Tkinter and PyQt, allowing developers to create desktop applications easily.
o Integrated: Python can easily integrate with other languages and technologies, such as
C/C++, Java, and . NET.
o Dynamic Memory Allocation: Python automatically manages memory allocation,
making it easier for developers to write complex programs without worrying about
memory management.
o Wide Range of Libraries and Frameworks: Python has a vast collection of libraries
and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a
wide range of problems.
o Versatility: Python is a universal language in various domains such as web
development, machine learning, data analysis, scientific computing, and more.
o Career Opportunities: Python is a highly popular language in the job market. Learning
Python can open up several career opportunities in data science, artificial intelligence,
web development, and more.
o High Demand: With the growing demand for automation and digital transformation, the
need for Python developers is rising. Many industries seek skilled Python developers to
help build their digital infrastructure.
o Big Data and Machine Learning: Python has become the go-to language for big data
and machine learning. Python has become popular among data scientists and machine
learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and
more.
o Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
o Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to create
cross-platform mobile applications.
o Software Development: Python is considered one of the best software-making
languages. Python is easily compatible with both from Small Scale to Large Scale
software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language
for artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools
like JavaScript HTML and CSS.
o Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
o 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
o Machine Learning: Python is widely used for machine learning due to its simplicity,
ease of use, and availability of powerful machine learning libraries.
o Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
o Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
o Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and
more.
o Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
o Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
o Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices
like Raspberry Pi, Arduino, and others.
o Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
o Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
o Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
The Python interpreter is a program that executes Python code. It takes the code written in
Python, parses it, and runs the instructions. The interpreter essentially allows a computer to
understand and execute Python code.
1. Reading the code: The interpreter reads Python code, line by line.
2. Parsing the code: It checks the syntax and structure of the code to ensure there are no
errors.
3. Executing the code: After parsing, the interpreter executes the instructions, performing
actions like calculations, printing output, or interacting with files, databases, etc.
4. Output: It provides feedback (if any), such as printed text or results, depending on what
the code instructs.
Python is often referred to as an interpreted language, which means it doesn't need a separate
compilation step like languages such as C or Java. You can run Python code directly in an
interpreter without needing to compile it beforehand.
Python can perform basic arithmetic operations like addition, subtraction, multiplication, and
division.
Example:
# Addition
result_add = 5 + 3
print(result_add)
Output: 8
# Subtraction
result_sub = 10 - 4
print(result_sub)
Output: 6
# Multiplication
result_mul = 7 * 6
print(result_mul)
Output: 42
# Division
result_div = 8 / 2
print(result_div)
Output: 4.0
Output: 3
Output: 1
# Exponentiation (Power)
result_pow = 2 ** 3
print(result_pow)
Output: 8
Just like in normal mathematical expressions, Python respects parentheses to control the order of
operations.
Example:
# Without parentheses
result1 = 5 + 3 * 2
print(result1)
Output: 11
Output: 16
Example:
You can enter the Python interactive shell (REPL) by just typing python or python3 in the
command line or terminal. This allows you to quickly type expressions and see the results
instantly.
Example:
$ python
Python 3.x.x (default, Jan 1 2025, 00:00:00)
>>> 10 / 3
Output: 3.3333333333333335
>>> 15 * 4
Output: 60
>>> 10 ** 2
Output:100
>>> exit()
Python shell
The Python shell, also known as the Python REPL (Read-Eval-Print Loop), is an interactive
environment that allows you to write and execute Python code line by line. It’s a great tool for
experimenting with Python commands, testing small snippets of code, and quickly getting
feedback.
On most systems, you can start the Python shell by typing python (for Python 3.x
versions) or python3 depending on your environment. If Python is correctly installed, it
will launch the Python shell.
>>>
The >>> symbol indicates that you are in the Python shell and ready to input Python code.
1. Interactive Mode: The Python shell allows you to type commands, execute them
immediately, and see the result.
Example:
>>> 3 + 5
8
2. Real-time Feedback: You can see the result of your calculations, assignments, or any
Python expressions immediately after typing them.
Example:
>>> a = 10
>>> b = 5
>>> a + b
15
3. Testing Functions and Code: The Python shell is useful for testing small functions or
code snippets without having to write an entire script.
Example:
4. Working with Variables: You can create variables, modify them, and perform
calculations directly.
Example:
>>> x = 15
>>> y = 10
>>> x * y
150
5. Multi-line Input: If you need to write multi-line code, you can use the shell for that as
well. For example, defining a function:
>>> def greet(name):
>>> print("Hello,", name)
>>> greet("Pramod")
Hello, Pramod
6. Importing Libraries: You can import Python modules (libraries) and use their functions
directly.
Example:
7. Exiting the Python Shell: To exit the Python shell, you can type exit() or press Ctrl + Z
(Windows).
Example:
>>> exit()
Indentation in Python
In Python, indentation is crucial for defining the structure and flow of a program. Unlike many
other programming languages that use curly braces {} to define code blocks, Python uses
indentation to determine what code belongs to which block (such as the body of loops,
functions, or conditionals).
1. Defining Code Blocks: Indentation tells the Python interpreter where a block of code begins and
ends. Code that is indented at the same level belongs to the same block. Without proper
indentation, Python will raise an IndentationError.
2. Readability: Proper indentation makes code readable and easy to understand for developers.
1. Consistency: You should use spaces or tabs, but spaces are preferred. The recommended
standard is to use 4 spaces per indentation level.
2. Indentation Level: All statements within the same block of code must have the same level of
indentation.
3. Mixing Spaces and Tabs: Never mix spaces and tabs for indentation. This will cause Python to
throw an error.
1. Control Structures: Indentation is used for the body of loops, conditionals, function
definitions, etc.
2. Nested Code: For nested control structures (like loops inside if statements), the
indentation helps visualize the hierarchy.
1. If-Else Statements
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
2. Functions
def greet(name):
print(f"Hello, {name}!")
greet("Pramod")
3. For Loop
for i in range(5):
print(i)
4. Nested If Statements
age = 20
if age >= 18:
print("You are an adult.")
if age == 20:
print("You are 20 years old.")
5. Multi-line Block
def check_even_or_odd(number):
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
check_even_or_odd(10)
1. Indentation Error: This occurs when the indentation is not consistent, or when a
statement that should be indented is not, or vice versa.
if True:
print("This will raise an error due to incorrect indentation")
Output:
# Using both tabs and spaces in the same code will cause an error
if True:
print("This uses a tab") # This uses a tab, which is inconsistent
print("This uses spaces") # This uses spaces
Output:
Atoms in Python
In Python, atoms refer to the simplest building blocks of the language. These are the basic
elements that Python uses to form more complex expressions and data structures. Atoms can be
variables, literals, operators, or even references to objects. Essentially, atoms are the smallest
units that Python can evaluate or work with.
These are predefined words in Python that have special meanings and cannot be used as variable
names.
if, else, elif, for, while, break, continue, return, def, class, import, from, as, pass, None, True, False, try,
except, raise, lambda, global, nonlocal, with, yield, assert, async, await
Example in Code:
if x > 10:
print("X is greater than 10")
Identifiers are the names assigned to variables, functions, classes, and objects. They must follow
Python's naming rules:
Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
Cannot start with a digit.
Cannot be a Python keyword.
Example in Code:
age = 25
def how():
print("Hello")
Examples:
Type Example
None None
Example in Code:
4. Operators
Examples of Operators:
Examples:
Parentheses: ()
Brackets: []
Braces: {}
Comma: ,
Colon: :
Semicolon: ;
Dot: .
Identifiers in Python
Identifiers are the names used to identify variables, functions, classes, or other objects. Python
has specific rules for naming identifiers:
Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we
can only apply for those functions. You'll never need to import any keyword into your
program because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as
keywords.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8.
You can check all Python keywords programmatically using the keyword module:
import keyword
print(keyword.kwlist)
Python Literals
Python Literals can be defined as data that is given in a variable or constant. Literals are constant
values that are used directly in the code. They represent fixed values assigned to variables or
used in expressions.
1. String Literals
String literals can be formed by enclosing a text in the quotes. We can use both single as well
as double quotes to create a string.
Example:
"Aman" , '12345'
Types of Strings:
Example:
text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
Example:
text1='Hello\
Students'
print(text1)
'HeloStudentsr'
Example:
str2=''''”Welcome
to
All'''
print str2
Output:
Welcome
to
All
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
None is used to specify to that field that is not created. It is also used for the end of lists in Python.
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals,
and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square brackets([]). We
can store different types of data in a List.
list1=['Amit',1001,5.6,'BCA']
list2=[1002,'Sumit’]
print(list1)
print(list1 + list1)
Output:
['Amit',1001, 5.6, 'BCA']
['Amit',1001, 5.6, 'BCA', 1002, 'Sumit']
Dictionary:
print(dict)
Output:
Tuple:
tup = (10,20,"Amit",[2,3,4])
print(tup)
Output:
Set:
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
Python Arithmetic Operators are used on two operands to perform basic mathematical
operators like addition, subtraction, multiplication, and division. There are different types of
arithmetic operators available in Python.
Types of arithmetic operators
Output:
For a = 46 and b = 4
Calculate the following:
1. Addition of two numbers: a + b = 50
2. Subtraction of two numbers: a - b = 42
3. Multiplication of two numbers: a * b = 184
4. Division of two numbers: a / b = 11.5
5. Floor division of two numbers: a // b = 11
6. Reminder of two numbers: a mod b = 2
7. Exponent of two numbers: a ^ b = 4477456
Comparison Operators
Python Comparison operators are mainly used for the purpose of comparing two values or variables
(operands) and return a Boolean value as either True or False accordingly.
Program Code:
Output:
For a = 46 and b = 4
Check the following:
1. Two numbers are equal or not: False
2. Two numbers are not equal or not: True
3. a is less than or equal to b: False
4. a is greater than or equal to b: True
5. a is greater b: True
6. a is less than b: False
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. Python
offers different assignment operators to assign values to the variable.
Program Code:
Output:
a += b: 40
a -= b: 28
a *= b: 204
a /= b: 5.666666666666667
a %= b: 4
a **= b: 1544804416
a //= b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. There are various Bitwise
operators used in Python, such as bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~),
Left shift (<<), and Right shift (>>).
Program Code:
Output:
a&b:0
a | b : 15
a ^ b : 15
~a : -8
a << b : 1792
a >> b : 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. Python offers
different types of logical operators such as and, or, and not. In the case of the logical AND, if the first
one is 0, it does not depend upon the second one. In the case of the logical OR, if the first one is 1, it
does not depend on the second one.
Program Code:
Output:
Membership Operators
We can verify the membership of a value inside a Python data structure using the Python
membership operators. The result is said to be true if the value or variable is in the sequence (list,
tuple, or dictionary); otherwise, it returns false.
Operator Meaning
in If the first operand (value or variable) is
present in the second operand (sequence), it
is evaluated to be true. Sequence can either
be a list, tuple, or dictionary
not in If the first operand (value or variable) is not
present in the second operand (sequence),
the evaluation is true. Sequence can either be
a list, tuple, or dictionary.
Program Code:
myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
Output:
Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
x = 31 is NOT present in the given list.
y = 28 is present in the given list.
Identity Operators
Python offers two identity operators as is and is not, that are used to check if two values are located
on the same part of the memory. Two variables that are equal do not imply that they are identical.
Operator Meaning
Is
If the references on both sides point to
the same object, it is determined to be
true.
Program Code:
Output:
a is c = True
a is not c = False
a is b = False
a is not b = True
a == b = True
a != b = False
Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.
Python provides built-in functions for handling input and output. These are commonly used to
interact with users.
1. Input Statements
The input() function is used to take user input as a string. You can prompt the user with a message
by passing a string argument to input().
The input() function always returns data as a string. To work with numbers, you must convert the
input using int(), float(), etc.
2. Output Statements
name = "Alice"
print("Hello,", name)
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
result = "Invalid operation"
Control statements in Python control the flow of execution in a program. These include
conditional statements, looping statements, and jump statements.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
if expression:
statement
Example 1
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
Output:
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
The syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
Enter your age: 90
You are eligible to vote !!
Example 2: Program to check whether a number is
even or not.
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
else:
print("The Given Number is an odd number")
Output:
enter the number: 10
The Given number is even number
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50");
elif number==100:
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Output:
Additionally, Python provides loop control statements (break, continue, pass) to alter the
loop’s flow.
Syntax:
python
CopyEdit
for variable in sequence:
# Code block
Example 1: Iterating Over a List
python
CopyEdit
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
python
CopyEdit
for i in range(1, 6): # Loops from 1 to 5
print(i)
Syntax:
python
CopyEdit
while condition:
# Code block
python
CopyEdit
for i in range(1, 10):
if i == 5:
break # Stops the loop when i is 5
print(i)
Output:
CopyEdit
1
2
3
4
Skips the remaining code for the current iteration and moves to the next one.
python
CopyEdit
for i in range(1, 6):
if i == 3:
continue # Skips when i is 3
print(i)
Output:
CopyEdit
1
2
4
5
The pass statement does nothing. It's used as a placeholder for future code.
python
CopyEdit
for i in range(5):
if i == 3:
pass # Placeholder for future logic
print(i)
1. Defining a Function
A function is defined using the def keyword, followed by the function name and parentheses ().
Syntax:
def function_name(parameters):
# Code block
return value # (optional)
Output:
def show(name):
print(f"Hello, {name}!")
Output:
CopyEdit
Hello, Pramod!
Hello, Amit!
result = add(5, 3)
print("Sum:", result)
Output:
Sum: 8
def show(name="Guest"):
print(f"Hello, {name}!")
Output:
Hello, Guest!
Hello, Pramod!
result = multiply(2, 3, 4)
print("Result:", result)
Output:
Result: 24
def total_sum(*numbers):
return sum(numbers)
print(total_sum(1, 2, 3, 4, 5)) # 15
def person_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
name: Alice
age: 25
city: New York
square = lambda x: x ** 2
print(square(5)) # 25
def outer():
print("Outer function")
def inner():
print("Inner function")
inner()
outer()
Output:
Outer function
Inner function
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Errors and Exceptions in Python
In Python, errors and exceptions are issues that occur during program execution, causing it to
stop. Understanding them helps in debugging and writing robust programs.
Syntax errors occur when the code is not written in the correct Python syntax.
Example:
print("Hello" # Missing closing parenthesis
Error:
Example:
x = 10 / 0 # Division by zero
Error:
Basic Example
try:
x = 10 / 0 # Error occurs
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
try:
num = int("abc") # Raises ValueError
except ValueError:
print("Invalid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
5. Using else with try-except
The else block runs if no exception occurs.
try:
num = int("10") # No error
except ValueError:
print("Invalid number!")
else:
print("Conversion successful:", num)
Output:
Conversion successful: 10
6. Using finally
The finally block always executes, whether an exception occurs or not.
try:
x = 10 / 0 # Error occurs
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute.")
Output:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
class NegativeNumberError(Exception):
pass
def check_positive(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed!")
try:
check_positive(-10)
except NegativeNumberError as e:
print(e)
Output:
1. Iteration (Looping)
Iteration is the process of executing a block of code multiple times using loops.
Conditional Execution
Conditional execution allows Python to execute code based on conditions using if, elif, and
else.
Nested Conditionals
Nested conditionals are if statements inside other if statements.
result = add(5, 3)
print(result) # Output: 8