[go: up one dir, main page]

0% found this document useful (0 votes)
33 views46 pages

Unit 2

Python is a versatile, high-level programming language created by Guido van Rossum in the late 1980s, with its first version released in 1991. It features a clear syntax, dynamic typing, and supports multiple programming paradigms, making it popular for various applications including web development, data science, and artificial intelligence. Python's extensive libraries and frameworks, along with its open-source nature, contribute to its widespread use and demand in the job market.

Uploaded by

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

Unit 2

Python is a versatile, high-level programming language created by Guido van Rossum in the late 1980s, with its first version released in 1991. It features a clear syntax, dynamic typing, and supports multiple programming paradigms, making it popular for various applications including web development, data science, and artificial intelligence. Python's extensive libraries and frameworks, along with its open-source nature, contribute to its widespread use and demand in the job market.

Uploaded by

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

Unit – 2

Introduction to python:

Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-


collected, and purely object-oriented programming language that supports procedural, object-
oriented, and functional programming. Python is a widely used programming language that offers
several unique features and advantages compared to languages like Java and C++.

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.

Python Basic Syntax


There is no use of curly braces or semicolons in Python programming language. It is an English-like
language. But Python uses indentation to define a block of code. Indentation is nothing but adding
whitespace before the statement when it is needed.

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.

Why learn Python?


Python provides many useful features to the programmer. These features make it the most popular
and widely used language. We have listed below few-essential features of Python.

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.

Where is Python used?


Python is a general-purpose, popular programming language, and it is used in almost every technical
field. The various areas of Python use are given below.

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.

Python Popular Frameworks and Libraries


Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - NumPy, Pandas, etc.
Python interpreter

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.

Here’s how it works:

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.

Using python as calculator


Using Python as a calculator is one of the simplest and most effective ways to perform calculations. You
can do this directly by running Python commands in an interactive environment like the Python shell or
using scripts.

1. Basic Arithmetic Operations:

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

# Integer Division (floor division)


result_floor_div = 7 // 2
print(result_floor_div)

Output: 3

# Modulus (remainder of division)


result_mod = 7 % 2
print(result_mod)

Output: 1

# Exponentiation (Power)
result_pow = 2 ** 3
print(result_pow)

Output: 8

2. Using Parentheses for Order of Operations:

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

# With parentheses to control order


result2 = (5 + 3) * 2
print(result2)

Output: 16

3. Working with Decimal Numbers:

Python handles both integers and floating-point numbers (decimals).

Example:

# Working with decimals (floating-point numbers)


result = 10.5 / 2
print(result)
Output: 5.25

4. Using the Python Interactive Shell (REPL) as a Calculator:

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)

>>> 100 + 200


Output: 300

>>> 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.

How to Access the Python Shell:

Type python or python3 and press Enter:

 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.

C:\program files\python3.10> python

You will see something like this:

Python 3.x.x (default, Jan 1 2025, 00:00:00)


[GCC 7.x.x] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>>

The >>> symbol indicates that you are in the Python shell and ready to input Python code.

Features of the Python Shell:

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:

>>> def square(x):


>>> return x * x
>>> square(4)
16

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:

>>> import math


>>> math.sqrt(16)
4.0

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).

Why is Indentation Important?

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.

Python Indentation Rules

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.

How Python Uses Indentation

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.

Examples of Proper Indentation in Python

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)

Common Errors with Indentation

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:

Indentation Error: expected an indented block


2. Mixing Tabs and Spaces: Mixing spaces and tabs will lead to unpredictable behavior
and errors. Python enforces this rule strictly.

# 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:

IndentationError: unindent does not match any outer indentation level

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.

Types of Atoms (Tokens) in Python

1. Keywords (Reserved Words)

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")

Here, if is a keyword token.

2. Identifiers (Variable & Function Names)

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")

Here, age and show are identifier tokens.

3. Literals (Constant Values)

Literals are fixed values assigned to variables.

Examples:
Type Example

Integer 10, -5, 1000

Float 3.14, -0.01, 1.5e3

String "hello", 'Python', '''Multiline'''

Boolean True, False

None None

Example in Code:

name = "Pramod" # String Literal


age = 30 # Integer Literal
pi = 3.14 # Float Literal
is_valid = True # Boolean Literal

Here, "Pramod", 30, 3.14, and True are literal tokens.

4. Operators

Operators are symbols that perform operations on variables and values.

Examples of Operators:

 Arithmetic Operators: +, -, *, /, %, **, //


 Comparison Operators: ==, !=, >, <, >=, <=
 Logical Operators: and, or, not
 Assignment Operators: =, +=, -=, *=, /=
 Bitwise Operators: &, |, ^, ~, <<, >>
5. Punctuators (Delimiters & Symbols)

These are special symbols used in Python syntax.

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:

Rules for Identifiers:

1. Must start with a letter or underscore (_):


o Valid: num, _first_num
o Invalid: 1num, -test
2. Can be followed by letters, digits, or underscores:
o Valid: num1, temp_value
o Invalid: num!, temp-value
3. Cannot use Python reserved keywords (e.g., if, for, while, etc.).
4. Case-sensitive:
o Num and num are different identifiers.
5. No length restrictions.
6. Cannot have spaces: Use underscores (_) for readability, like first_name.

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.

False Await else import pass


None Break except in raise

True Class finally is return

And Continue for lambda try

As Def from nonlocal while

Assert Del global not with

Async Elif if or yield

Checking Keywords in Python:

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.

Types of Literals in Python

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:

There are two types of Strings supported in Python:


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

Example:

text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.

There are two ways to create multiline strings:

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

Example:

text1='Hello\
Students'
print(text1)
'HeloStudentsr'

2) Using triple quotation marks:-

Example:

str2=''''”Welcome
to
All'''
print str2
Output:

Welcome
to
All

II. Numeric literals:


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

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


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

Example - Numeric Literals

x = 0b10100 #Binary Literals


y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal

#Float Literal
float_1 = 100.5
float_2 = 1.5e2

#Complex Literal
a = 5+3.14j

print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:

20 100 141 301


100.5 150.0
(5+3.14j) 3.14 5.0

III. Boolean literals:


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

Example - Boolean Literals

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

IV. Special literals.


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

None is used to specify to that field that is not created. It is also used for the end of lists in Python.

Example - Special Literals

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.

Example - List literals

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:

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


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

dict = {'name': 'Amit', 'Age':18,'Roll_num':1001}

print(dict)
Output:

{'name': 'Amit', 'Age': 18, 'Roll_num': 1001}

Tuple:

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


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

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

print(tup)
Output:

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

Set:

o Python set is the collection of the unordered dataset.


o It is enclosed by the {} and each element is separated by the comma(,).
Example: - Set Literals

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

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


Python Operators
In general, Operators are the symbols used to perform a specific operation on different values and
variables. These values and variables are considered as the Operands, on which the operator is
applied. Operators serve as the foundation upon which logic is constructed in a program in a
particular programming language. In every programming language, some operators perform several
tasks.

Different Types of Operators in Python


Same as other languages, Python also has some operators, and these are given below -

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

Operator Meaning Example


+ Addition a+b
- Subtraction a–b
* Multiplication a*b
/ Division a/b
% Modulus a%b
** Exponent a ** b
// Floor Division a // b
Program Code:

0a = 46 # Initializing the value of a


b = 4 # Initializing the value of b

print("For a =", a, "and b =", b,"\n Calculate the following:")

# printing different results


print('1. Addition of two numbers: a + b =', a + b)
print('2. Subtraction of two numbers: a - b =', a - b)
print('3. Multiplication of two numbers: a * b =', a * b)
print('4. Division of two numbers: a / b =', a / b)
print('5. Floor division of two numbers: a // b =', a // b)
print('6. Reminder of two numbers: a mod b =', a % b)
print('7. Exponent of two numbers: a ^ b =', a ** b)

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.

Operator Meaning Example


== Equals to a == b
!= Not Equals to a != b
<= Less than or equals to a <= b
>= Greater than or equals to a >= b
> Greater than a>b
< Less than a<b

Program Code:

a = 46 # Initializing the value of a


b = 4 # Initializing the value of b

print("For a =", a, "and b =", b,"\nCheck the following:")

# printing different results


print('1. Two numbers are equal or not:', a == b)
print('2. Two numbers are not equal or not:', a != b)
print('3. a is less than or equal to b:', a <= b)
print('4. a is greater than or equal to b:', a >= b)
print('5. a is greater b:', a > b)
print('6. a is less than b:', a < b)

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.

Operator Meaning Example


= Assignment a = 10
+= Addition with Assignment a +=10
-= Subtraction with Assignment a -=10
*= Multiplication Assignment a *=10
/= Division with Assignment a /=10
%= Modulus with Assignment a %=10
**= Exponent with Assignment a **=10
//= Float Division with Assignment a //=10

Program Code:

a = 34 # Initialize the value of a


b=6 # Initialize the value of b

# printing the different results


print('a += b:', a + b)
print('a -= b:', a - b)
print('a *= b:', a * b)
print('a /= b:', a / b)
print('a %= b:', a % b)
print('a **= b:', a ** b)
print('a //= b:', a // b)

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 (>>).

Operator Meaning Example


& Bitwise And A&b
| Bitwise OR
^ Bitwise XOR
~ Bitwise Not
<< Bitwise Left Shift
>> Bitwise Right Shft

Program Code:

a=7 # initializing the value of a


b=8 # initializing the value of b

# printing different results


print('a & b :', a & b)
print('a | b :', a | b)
print('a ^ b :', a ^ b)
print('~a :', ~a)
print('a << b :', a << b)
print('a >> b :', a >> b)

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.

Operator Meaning Example


and Logical AND a and b
or Logical OR a or b
not Logical NOT not a

Program Code:

a=7 # initializing the value of a

# printing different results


print("For a = 7, checking whether the following conditions are True or False:")
print('\"a > 5 and a < 7\" =>', a > 5 and a < 7)
print('\"a > 5 or a < 7\" =>', a > 5 or a < 7)
print('\"not (a > 5 and a < 7)\" =>', not(a > 5 and a < 7))

Output:

For a = 7, checking whether the following conditions are True or False:


"a > 5 and a < 7" => False
"a > 5 or a < 7" => True
"not (a > 5 and a < 7)" => True

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]

# initializing x and y with some values


x = 31
y = 28

# printing the given list


print("Given List:", myList)

# checking if x is present in the list or not


if (x not in myList):
print("x =", x,"is NOT present in the given list.")
else:
print("x =", x,"is present in the given list.")

# checking if y is present in the list or not


if (y in myList):
print("y =", y,"is present in the given list.")
else:
print("y =", y,"is NOT present in the given list.")

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.

is not If the references on both sides do not point


at the same object, it is determined to be
true.

Program Code:

# initializing two variables a and b


a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
# initializing a variable c and storing the value of a in c
c=a

# printing the different results


print("a is c = ", a is c)
print("a is not c = ", a is not c)
print("a is b = ", a is b)
print("a is not b = ", a is not b)
print("a == b = ", a == b)
print("a != b = ", a != b)

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.

S. No. perator Description

Overall other operators employed in the expression, the


1 **
exponent operator is given precedence.

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

the division of the floor, the modules, the division, and


3 *, /, %, //
the multiplication.

4 +, - Binary plus, and minus

5 >>, << Left shift. and right shift


6 & Binary and.

7 ^, | Binary xor, and or

Comparison operators (less than, less than equal to,


8 <=, <, >, >=
greater than, greater then equal to).

9 <>, ==, != Equality operators.

=, %=, /=, //=, -=, +=,


10 Assignment operators
*=, **=

11 is, is not Identity operators

12 in, not in Membership operators

13 not, or, and Logical operators

Input and Output Statements in Python

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().

Example 1: Simple Input

name = input("Enter your name: ")


print(f"Hello, {name}!")
Example 2: Input with Type Conversion

The input() function always returns data as a string. To work with numbers, you must convert the
input using int(), float(), etc.

age = int(input("Enter your age: "))


print(f"You will be {age + 1} years old next year!")

2. Output Statements

The print() function is used to display output to the console.

Example 1: Simple Output


print("Welcome to Python programming!")

Example 2: Output with Variables

name = "Alice"
print("Hello,", name)

Example 3: Using f-strings for Output


age = 25
print(f"Your age is {age}.")

Examples Combining Input and Output

Example 1: Simple Calculator


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter operation (+, -, *, /): ")

if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
result = "Invalid operation"

print(f"The result is: {result}")

Example 2: Greeting Based on Time of Day


hour = int(input("Enter the current hour (0-23): "))

if 5 <= hour < 12:


greeting = "Good Morning"
elif 12 <= hour < 18:
greeting = "Good Afternoon"
elif 18 <= hour < 22:
greeting = "Good Evening"
else:
greeting = "Good Night"

print(f"{greeting}! Have a great day!")

Example 3: Area of a Circle


import math

radius = float(input("Enter the radius of the circle: "))


area = math.pi * radius ** 2

print("The area of the circle is :", area)


Control Statements in Python

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.

The syntax of the if-statement is given below.

if expression:
statement

Example 1
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")

Output:

enter the number: 10


The Given number is an even number
Example 2 : Program to print the largest of the three
numbers.
a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
print ("From the above three numbers given a is largest");
if b>a and b>c:
print ("From the above three numbers given b is largest");
if c>a and c>b:
print ("From the above three numbers given c is largest");

Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

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)

Example 1 : Program to check whether a person is


eligible to vote or not.
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

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


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have any
number of elif statements in our program depending upon our need. However, using
elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.

The syntax of the elif statement is given below.

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:

Enter the number?15


The given number is not equal to 10, 50 or 100
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:

Enter the marks? 89


Congrats ! you scored grade A ...

Looping Statements in Python


Looping statements in Python are used to execute a block of code multiple times until a certain
condition is met. Python supports two types of loops:

1. for loop (Used for iteration over a sequence)


2. while loop (Runs as long as a condition is True)

Additionally, Python provides loop control statements (break, continue, pass) to alter the
loop’s flow.

1. for Loop (Definite Loop)


A for loop is used when the number of iterations is known or when iterating over a sequence
(list, tuple, string, etc.).

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)

Example 2: Using range()

The range(start, stop, step) function generates a sequence of numbers.

python
CopyEdit
for i in range(1, 6): # Loops from 1 to 5
print(i)

Example 3: Iterating Over a String


python
CopyEdit
for char in "Python":
print(char)

2. while Loop (Indefinite Loop)


A while loop executes as long as a given condition remains True.

Syntax:
python
CopyEdit
while condition:
# Code block

Example 1: Basic while Loop


python
CopyEdit
count = 1
while count <= 5:
print(count)
count += 1

Example 2: while with User Input


python
CopyEdit
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")

3. Loop Control Statements


Python provides three control statements to modify loop execution:

(a) break (Exit Loop Immediately)

Stops the loop when a condition is met.

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

(b) continue (Skip Current Iteration)

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

(c) pass (Placeholder Statement)

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)

4. else with Loops


Python allows an else block with loops. The else block executes only if the loop completes
normally (without break).

Example: else with for Loop


python
CopyEdit
for i in range(1, 6):
print(i)
else:
print("Loop completed successfully")

Example: else with while Loop


python
CopyEdit
x = 1
while x < 5:
print(x)
x += 1
else:
print("Loop finished without interruption")

Defining Functions in Python


A function in Python is a reusable block of code that performs a specific task. Functions help in
code organization, reusability, and modularity.

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)

2. Example: Basic Function


def show():
print("Hello, welcome to Python!")

Calling the Function


show()

Output:

Hello, welcome to Python!

3. Function with Parameters


Functions can accept parameters (inputs) to make them dynamic.

def show(name):
print(f"Hello, {name}!")

Calling the Function with an Argument


show("Pramod")
show("Amit")

Output:

CopyEdit
Hello, Pramod!
Hello, Amit!

4. Function with Return Value


A function can return a value using the return keyword.

def add(a, b):


return a + b

result = add(5, 3)
print("Sum:", result)

Output:

Sum: 8

5. Default Parameter Values


If a parameter is not provided, it takes a default value.

def show(name="Guest"):
print(f"Hello, {name}!")

show() # Uses default value


show("Pramod") # Overrides default

Output:

Hello, Guest!
Hello, Pramod!

6. Function with Multiple Parameters


You can pass multiple arguments to a function.

def multiply(a, b, c):


return a * b * c

result = multiply(2, 3, 4)
print("Result:", result)

Output:

Result: 24

7. Variable-Length Arguments (*args and **kwargs)


(a) *args (Multiple Positional Arguments)

Used when the number of arguments is unknown.

def total_sum(*numbers):
return sum(numbers)

print(total_sum(1, 2, 3, 4, 5)) # 15

(b) **kwargs (Multiple Keyword Arguments)

Used for passing a dictionary of key-value pairs.

def person_info(**details):
for key, value in details.items():
print(f"{key}: {value}")

person_info(name="Alice", age=25, city="New York")


Output:

name: Alice
age: 25
city: New York

8. Lambda (Anonymous) Functions


A lambda function is a one-liner function without a name.

square = lambda x: x ** 2
print(square(5)) # 25

9. Nested Functions (Functions Inside Functions)


A function can be defined inside another function.

def outer():
print("Outer function")

def inner():
print("Inner function")

inner()

outer()

Output:

Outer function
Inner function

10. Recursive Function (Function Calling Itself)


A recursive function calls itself until a base condition is met.

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.

1. Types of Errors in Python


(a) Syntax Errors (Compile-Time Errors)

Syntax errors occur when the code is not written in the correct Python syntax.

Example:
print("Hello" # Missing closing parenthesis

Error:

SyntaxError: unexpected EOF while parsing

(b) Runtime Errors (Exceptions)

Exceptions occur during execution, even when the syntax is correct.

Example:
x = 10 / 0 # Division by zero

Error:

ZeroDivisionError: division by zero

2. Common Python Exceptions


Exception Description Example

ZeroDivisionError Division by zero 10 / 0

NameError Using an undefined variable print(x) # x is not defined

TypeError Operation on incompatible types 5 + "hello"


Exception Description Example

my_list[5] (list has only 3


IndexError Accessing an invalid list index
elements)

Accessing a non-existent key in a


KeyError my_dict['missing_key']
dictionary

ValueError Invalid value for an operation int("abc")

AttributeError Accessing an invalid attribute "hello".missing_method()

ImportError Importing a missing module import nonexistent_module

FileNotFoundError File does not exist open("missing_file.txt")

3. Handling Exceptions with try-except


Python uses try-except blocks to handle exceptions and prevent program crashes.

Basic Example
try:
x = 10 / 0 # Error occurs
except ZeroDivisionError:
print("Cannot divide by zero!")

Output:

Cannot divide by zero!

4. Handling Multiple Exceptions


You can handle different exceptions in separate except blocks.

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:

Cannot divide by zero!


This will always execute.

7. Raising Custom Exceptions (raise)


You can raise your own exceptions using raise.

age = -5
if age < 0:
raise ValueError("Age cannot be negative")

8. Defining Custom Exceptions


You can create a custom exception by subclassing Exception.

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:

Negative numbers are not allowed!

Iteration and Recursion in Python


Iteration and recursion are two different approaches to repeating code execution.

1. Iteration: Uses loops (for, while) to repeat code.


2. Recursion: A function calls itself until a base condition is met.

1. Iteration (Looping)
Iteration is the process of executing a block of code multiple times using loops.

Example: Using a for loop


for i in range(1, 6):
print(i)

Example: Using a while loop


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

2. Recursion (Function Calling Itself)


Recursion is when a function calls itself until a base condition is met.

Example: Factorial using Recursion


def factorial(n):
if n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive case

print(factorial(5)) # Output: 120

Conditional Execution
Conditional execution allows Python to execute code based on conditions using if, elif, and
else.

Example: Basic Conditional Execution


age = 18
if age >= 18:
print("You are an adult")

Alternative Execution (if-else)


Alternative execution provides two paths: one when the condition is True and another when it is
False.

Example: Checking Even or Odd


num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")

Nested Conditionals
Nested conditionals are if statements inside other if statements.

Example: Checking Grades


score = 85
if score >= 50:
if score >= 80:
print("Excellent")
else:
print("Good job")
else:
print("Failed")

The return Statement


The return statement exits a function and returns a value.

Example: Function with return


def add(a, b):
return a + b

result = add(5, 3)
print(result) # Output: 8

You might also like