Introduction to Python and Its Features...
Introduction to Python and Its Features...
Introduction to Python
Python is a high-level, interpreted programming language created by Guido van
Rossum and first released in 1991. It's known for its simplicity, readability, and
versatility, making it one of the most popular programming languages today. Python is
widely used in various fields, such as web development, data analysis, artificial
Python's design philosophy emphasizes code readability and simplicity, with a syntax
languages like C++ or Java. Its extensive standard library and large ecosystem of
third-party libraries make it a powerful tool for both beginners and experienced
developers.
Features of Python
1. Simple and Easy to Learn: Python's straightforward syntax and readability make
it easy to learn, especially for beginners. The language is designed to be intuitive
and mirrors natural language to some extent.
2. Interpreted Language: Python code is executed line by line, which makes
debugging easier and more interactive. You don't need to compile your code
before running it, which speeds up the development process.
3. Cross-Platform Compatibility: Python is available on various platforms, including
Windows, macOS, Linux, and even mobile devices. This allows you to write code
that can run on multiple systems without modification.
1
4. Extensive Standard Library: Python comes with a rich standard library that
provides modules and functions for various tasks, such as file I/O, regular
expressions, web services, and more. This reduces the need to write code from
scratch for common tasks.
5. Large Ecosystem of Libraries: Python has a vast collection of third-party libraries
and frameworks for different domains, such as NumPy and pandas for data
analysis, TensorFlow and PyTorch for machine learning, Django and Flask for
web development, and many more.
6. Object-Oriented Programming: Python supports object-oriented programming
(OOP) paradigms, allowing you to create reusable code and build complex
applications. It also supports procedural and functional programming styles,
making it a flexible language.
7. Dynamic Typing: Python is dynamically typed, meaning you don't need to declare
the type of a variable. The type is inferred at runtime, which simplifies the code
and makes it more flexible.
8. Memory Management: Python handles memory management automatically with
built-in garbage collection, so developers don't need to worry about manually
allocating and deallocating memory.
9. Community Support: Python has a large and active community, which means
there are plenty of resources, tutorials, and forums where you can get help and
share knowledge.
10.Extensible and Embeddable: Python can be extended with modules written in C
or C++, and it can also be embedded into other applications as a scripting
language, allowing for more flexibility and integration with other systems.
11.High-Level Language: Python abstracts many complex details of the machine,
allowing you to focus more on problem-solving than on the intricacies of
hardware-level programming.
12.Scalable and Versatile: Python can be used for small-scale scripts to automate
tasks, as well as for large-scale enterprise applications. It is versatile enough to
2
be used in web development, scientific computing, data analysis, artificial
intelligence, and more.
13.Support for Scripting and Automation: Python is often used as a scripting
language for automating repetitive tasks. Its ability to interface with system calls
and other languages makes it ideal for writing scripts that control other software
applications.
around objects rather than functions or logic. An object is a collection of data (attributes)
and methods (functions) that operate on the data. OOP allows you to model real-world
things like cars, animals, or even more abstract concepts like a bank account, as
In OOP, you focus on creating classes, which are blueprints for objects. A class defines
the properties (attributes) and behaviors (methods) that the objects created from that
class will have. Once you create a class, you can create multiple objects (instances)
from it.
1. Class: A blueprint or template for creating objects. It defines what attributes and
methods the objects will have.
3
2. Object: An instance of a class. It represents a specific item or concept created
from the class.
3. Encapsulation: The practice of keeping data (attributes) and methods (functions)
within a class and controlling access to them, often using access modifiers like
private or public.
4. Inheritance: The ability to create a new class based on an existing class,
inheriting its properties and behaviors while allowing for modifications or
extensions.
5. Polymorphism: The ability to use the same method name in different classes,
where each class defines the method differently, allowing for flexible code.
6. Abstraction: The practice of hiding complex implementation details and showing
only the essential features of an object.
Example:
python
Copy code
In this example, Car is a class, and my_car is an object (instance) of that class. The
code around procedures or functions. In this approach, the program is divided into small
4
chunks of code, called functions, that perform specific tasks. The focus is on writing
In POP, you think of the program as a series of steps or procedures to be followed. Data
and functions are typically separate, and functions operate on data passed to them.
1. Procedure/Function: A block of code that performs a specific task. You can call
the function whenever you need to perform that task.
2. Global and Local Variables: Variables can be defined globally (accessible
throughout the program) or locally (accessible only within a specific function).
3. Modularity: The program is divided into small, manageable functions that can be
reused in different parts of the program.
4. Top-Down Approach: The program is structured in a step-by-step manner, often
starting with the main function and breaking down tasks into smaller functions.
Example:
python
Copy code
In this example, start_engine is a function that performs a specific task. The data
(car_make and car_model) is passed to the function as arguments, and the function
5
Key Differences:
● Focus: OOP focuses on objects (data + behavior), while POP focuses on
functions and the sequence of tasks.
● Data and Functions: In OOP, data and methods are bundled together within
objects. In POP, data and functions are separate.
● Reusability: OOP encourages code reusability through inheritance and
polymorphism. POP achieves reusability by breaking down the program into
reusable functions.
● Approach: OOP takes a bottom-up approach (starting with objects), while POP
takes a top-down approach (starting with the main function and breaking it
down).
Both paradigms are useful, and the choice between them depends on the nature of the
problem you are trying to solve. OOP is often preferred for large, complex applications,
while POP can be simpler and more efficient for smaller tasks or straightforward
problems.
instructions or steps to get something done. You write functions (small pieces of
code) to perform each task, and you call these functions whenever you need
them.
6
Example: Making a Sandwich
Imagine you're writing a program to make a sandwich. In POP, you would write
python code
def get_bread::
# #Main program
get_bread()
add_filling()
close_sandwich()
In this program, each function does one job. The program runs from top to
bottom, calling each function in order to make the sandwich. Everything is done
7
Object-Oriented Programming (OOP)
In Object-Oriented Programming, instead of thinking about steps, you think about
things (objects) that have properties and actions. These things can interact with
each other.
Now, instead of just steps, you think of a sandwich as an object. A sandwich has
properties (like the type of bread and filling) and actions (like adding filling or
You create a class (a blueprint) for a sandwich, and then you can create different
sandwich objects.
python code
class Sandwich:
bread
self.filling = filling
{self.bread}")
"turkey") my_sandwich.make_sandwich()
8
In this example:
Summary of Differences:
● POP: Focuses on functions (steps) to get the job done. You think about
what steps need to be done, and you write those steps as functions.
Example: Making a sandwich step by step with individual functions.
● OOP: Focuses on objects (things) that have properties and actions. You
think about the "thing" you're working with (like a sandwich), and you write
a class that describes how that thing works.
Example: Creating a sandwich object with properties (bread, filling) and
actions (make the sandwich).
In simple terms, POP is like following a recipe one step at a time, while OOP is
like thinking of a sandwich as a whole thing that can make itself when you tell it
to.
2.
Execution mode
9
Python is a programming language that lets you work quickly and integrate
fewer lines of code. In the Python programming language, there are two
1. Interactive mode
2. Script mode
In this article, we’ll get to know what these modes are and how they differ
Interactive mode
impact of our work on the other’s work”. Interactive mode is based on this
enter, the very next step we get the output. The output of the code in the
mode is very convenient for writing very short lines of code. In python it is
also known as REPL which stands for Read Evaluate Print Loop. Here, the
read function reads the input from the user and stores it in memory. Eval
function evaluates the input to get the desired output. Print function outputs
the evaluated result. The loop function executes the loop during the
10
execution of the entire program and terminates when our program ends.
evaluate their code line by line and understand the execution of code well.
In order to run our program in the interactive mode, we can use command
the execution of python code in the command prompt with the help of an
example:
Example 1:
To run python in command prompt type “python”. Then simply type the
Python statement on >>> prompt. As we type and press enter we can see
Python3
# Python program to display "Hello GPF"
print("Hello GPF")
Output:
11
Let us take another example in which we need to perform addition on two
numbers and we want to get its output. We will declare two variables a and
b and store the result in a third variable c. We further print c. All this is
done in the command prompt.
Python3
# Python program to add two numbers
a = 2
b = 3
C = A + B
# Printing value of c
12
print (c)
Output:
We can see the desired output on the screen. This kind of program is a
very short program and can be easily executed in interactive mode.
Example 3:
In this example, we will multiply two numbers and take the numbers as an
input for two users. You will see that when you execute the input
command, you need to give input in the very next line, i.e. code is
interpreted line by line.
13
Python3
# Python program to take input from user
# Taking input from user
a = int(input())
# Taking input from user
b = int(input())
# Multiplying and storing result
c = a * b
# Printing the result
print ©
Output:
14
The interactive mode doesn’t save the statements. Once we make a program
it is for that time itself, we cannot use it in the future. In order to use it in the
future, we need to retype all the statements.
.Script Mode
Script etymologically means a system of writing. In the script mode, a
python program can be written in a file. This file can then be saved and
executed using the command prompt. We can view the code at any time
by opening the file and editing becomes quite easy as we can open and
view the entire code as many times as we want. Script mode is very
suitable for writing long pieces of code. It is much preferred over interactive
mode by experts in the program. The file made in the script mode is by
default saved in the Python installation folder and the extension to save a
python file is “.py”.
Step 1: Make a file using a text editor. You can use any text editor of your
choice(Here I use notepad).
Step 2: After writing the code save the file using “.py” extension.
15
Step 3: Now open the command prompt and command directory to the
one where your file is stored.
Example 1:
In order to execute “Hello gfg” using script mode we first make a file and
save it.
16
Output:
Example 2:
Our second example is the same addition of two numbers as we saw in the
interactive mode. But in this case, we first make a file and write the entire
code in that file. We then save it and execute it using the command
prompt.
17
Output:
Example 3:
In this example, we write the code for multiplying two numbers. And the
numbers which are to be multiplied are taken by the user as an input. In
the interactive mode, we saw that as we write the command so does it
18
asks for the input in the very next line. But in script mode we first code the
entire program save and then run it in command prompt. The python
interpreter executes the code line by line and gives us the result
accordingly.
In this example, we see that the whole program is compiled and the code
is executed line by line. The output on the shell is entirely different from the
interactive mode.
19
● In the script mode, the Python program is written in a file. Python
interpreter reads the file and then executes it and provides the
desired result. The program is compiled in the command prompt,
● The interactive mode is more suitable for writing very short
programs.
● Script mode is more suitable for writing long programs.
● Editing of code can be done but it is a tedious task.
● Editing of code can be easily done in script mode.
● We get output for every single line of code in interactive mode i.e.
result is obtained after execution of each line of code.
● In script mode entire program is first compiled and then executed.
● Code cannot be saved and used in the future.
● Code can be saved and can be used in the future.
● It is more preferred by beginners.
● It is more preferred by experts than the beginners to use script
mode.
Python uses a specific character set (Unicode) that includes letters, digits,
Character Set:
● Letters: Python supports both uppercase and lowercase letters (e.g., A-Z,
a-z).
20
● Whitespace Characters: Python recognizes spaces, tabs, and newlines as
whitespace.
1. Letters:
○ Lowercase letters: a, b, c, ..., z
○ Uppercase letters: A, B, C, ..., Z
○ Python is case-sensitive, which means a and A are
considered different characters.
2. Digits:
○ Numeric digits: 0, 1, 2, ..., 9
○ These are used in defining numbers (e.g., 123, 4.56).
3. Special Characters:
○ Operators: +, -, *, /, %, =, ==, !=, etc.
○ Punctuation: ,, :, ;, ., () (parentheses), [] (square
brackets), {} (curly braces).
○ Other symbols: @, #, $, &, ^, *, _, etc.
○ Whitespace characters: Space, Tab (\t), and Newline
(\n).
4. Unicode Support:
21
○ Python supports Unicode characters, meaning you can
include characters from different languages and symbols
in your code ChatGPT
Indentation in Python
What is Indentation?
Indentation refers to the spaces or tabs at the beginning of a line of code. In
For example, when you define a function or use a control structure like an if
statement, you need to indent the lines of code that are part of that function or
statement.
keywords like begin and end. However, Python uses indentation to define blocks
of code. This makes Python code visually cleaner but also means that the correct
Rules of Indentation:
22
1. Consistent Indentation: You must use the same number of spaces or tabs
for each level of indentation within a block. Mixing spaces and tabs in the
same block will result in an error.
2. Recommended Indentation: Python's official style guide, PEP 8,
recommends using 4 spaces per indentation level. While you can use tabs
or any other number of spaces, 4 spaces is the standard.
3. Indentation Levels: Each level of indentation represents a new block of
code. For example, after an if statement, the next line must be indented
to indicate that it is part of the if block. If you need to create a sub-block
within that block, you would increase the indentation further.
4. SyntaxError for Incorrect Indentation: If you do not follow the indentation
rules, Python will raise a SyntaxError. This error indicates that the code
structure is not defined properly.
python
Copy code
23
def greet(name):
if name:
print(f"Hello, {name}!")
else:
print("Hello, World!")
In this example:
def check_number(num):
if num > 0:
print("Positive number")
24
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
else:
print("Non-positive number")
Here:
def greet(name):
print(f"Hello, {name}!")
In this case, the if statement is indented with 4 spaces, but the print("Inside
the function") line is indented with only 2 spaces. This inconsistency will cause
Python to raise a SyntaxError.
Best Practices:
25
● Stick to 4 spaces per level: This is the convention and makes your code
consistent with most Python code you'll encounter.
● Avoid mixing tabs and spaces: Python 3 disallows mixing tabs and spaces
in indentation. Stick to one or the other (preferably spaces).
● Use a text editor or IDE that automatically handles indentation: Most
modern text editors and IDEs (like PyCharm, VSCode, or even Jupyter
Notebook) will automatically indent your code correctly.
PYTHON TOKENS
KEYWORDS
1. Keywords:
26
Definition: Keywords are reserved words in Python that have a
predefined meaning and cannot be used for anything other than their
intended purpose.
Usage: Keywords define the structure and flow of the program. For
example:
if x > 0:
print("Positive")
else:
print("Non-positive")
2. Identifiers:
Rules:
27
Cannot be a keyword (e.g., if, for).
pass
3. Literals:
Types of Literals:
28
Usage: Literals are the raw data you work with in your program. For
example:
4. Operators:
Types of Operators:
29
Usage: Operators are used to manipulate data. For example:
5. Punctuators:
Examples:
Braces: {}, used for defining dictionaries and code blocks in some
contexts (e.g., lambda functions).
30
Semicolon: ;, used to separate multiple statements on a single line
(though it's rarely used in Python).
Conclusion:
KEYWORDS
31
Keywords in Python are reserved words that have specific meanings
and purposes. These words are part of the syntax and structure of the
language and cannot be used as identifiers (names for variables,
functions, classes, etc.). Python's keywords define the control flow,
variable management, and overall structure of a Python program.
Characteristics of Keywords:
Categories of Keywords:
These keywords are used to control the flow of the program (i.e.,
decisions and loops).
32
Example:
if condition:
# code block
elif another_condition:
else:
Example:
for i in range(5):
print(i)
while condition:
# code block
33
break: Exits the loop entirely.
continue: Skips the rest of the code inside the loop for the current
iteration and moves to the next iteration.
Example:
for i in range(10):
if i == 5:
break
elif i % 2 == 0:
continue
else:
pass
These keywords are used for defining functions, classes, and methods.
34
Example:
def my_function():
print("Hello, World!")
Example:
return a + b
Example:
square = lambda x: x ** 2
print(square(4)) # Output: 16
35
Example:
class MyClass:
self.name = name
finally: Block of code that will be executed no matter what, after try
and except.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
36
print("Division by zero is not allowed.")
finally:
Example:
if x < 0:
Example:
37
global: Used to declare a global variable inside a function, making it
accessible throughout the program.
Example:
global_var = 10
def modify_global():
global global_var
global_var = 20
Example:
def outer():
x = 10
def inner():
nonlocal x
x = 20
38
inner()
print(x) # Output: 20
Example:
del my_variable
Example:
is_active = True
Example:
result = None
39
These keywords help in managing resources (e.g., files) and ensuring
that they are properly closed after use.
Example:
with open('file.txt', 'r') as file:
content = file.read()
Example:
import numpy as np
7. Miscellaneous Keywords:
These keywords have specific functions that don't fall into the above
categories.
40
Example:
import math
Example:
if 'a' in 'apple':
print("Found")
is / is not: Used to test object identity, i.e., whether two objects are
the same in memory.
Example:
if a is b:
41
Example:
if a > 0 and b > 0:
Example:
def generator():
yield 1
yield 2
yield 3
42
and continue for lambda try as
def from nonlocal while assert del
global not with async elif
if or yield
IDENTIFIERS
Naming Rules:
43
Invalid examples: 1variable, @name, #value.
Case Sensitivity:
Example:
var1 = 10
Var1 = 20
print(var1) # Outputs: 10
print(Var1) # Outputs: 20
Cannot Be a Keyword:
44
Python keywords (e.g., if, for, class, etc.) cannot be used as
identifiers. These are reserved for specific purposes in the Python
language.
Length:
There is no specific length limit for identifiers in Python, but it's a good
practice to keep them reasonably short and descriptive. Very long
identifiers can make your code hard to read and maintain.
Underscores in Identifiers:
Example:
_private_var = 42
Example:
class MyClass:
45
def __init__(self):
Example:
class MyClass:
def __init__(self):
self.value = 0
Conventions:
46
Class Names: Use CamelCase, where each word starts with an
uppercase letter. Example: MyClass, EmployeeData.
Bad example: l, o, i.
47
Good example: avg_temp for average temperature.
Examples of Identifiers:
# Variable identifier
student_name = "Alice"
# Function identifier
def calculate_area(radius):
# Class identifier
class Car:
self.model = model
48
# Constant identifier
MAX_SPEED = 120
Invalid Identifiers:
2ndVar = 10 # SyntaxError
my-var = 5 # SyntaxError
Using a keyword:
for = 100 # SyntaxError
49
Functions: When defining functions, identifiers are used as function
names.
def greet(name):
class Person:
pass
Modules: Identifiers are also used for module names when importing
modules in Python.
import math
3. LITERALS
50
In Python, literals are fixed values or constants that you write directly in
your code. These values are not calculated or evaluated but are
hard-coded in the program. Python supports several types of literals, each
corresponding to different data types. Let’s explore them in detail.
1. Numeric Literals
a. Integer Literals
51
Example: 0xA (which is 10 in decimal)
decimal_number = 10 # Decimal
b. Floating-Point Literals
Examples:
52
scientific_float = 1.5e2 # Scientific notation (1.5 *
10^2 = 150.0)
c. Complex Literals
Example:
2. String Literals
a. Single-line Strings
Single-line strings are enclosed in either single quotes (') or double quotes
(").
Examples:
53
single_quote_string = 'Hello'
double_quote_string = "World"
b. Multi-line Strings
Multi-line strings are enclosed in triple quotes (''' or """). They can span
multiple lines and are often used for docstrings or longer text blocks.
Examples:
Examples:
54
escaped_string = "He said, \"Hello!\""
d. Raw Strings
Raw strings are prefixed with an r or R, and they treat backslashes (\) as
literal characters, meaning escape sequences are not processed.
Example:
raw_string = r"C:\Users\Name\Documents"
3. Boolean Literals
Boolean literals represent the two truth values in Python: True and
False. These literals are used in conditional expressions and logical
operations.
Examples:
is_true = True
is_false = False
55
4. None Literal
Example
empty_value = None
5. Collection Literals
a. List Literals
Example:
b. Tuple Literals
56
Tuples are ordered, immutable collections of items, enclosed in
parentheses (()).
Example:
c. Dictionary Literals
Keys and values can be of any data type, and each key is associated with
a value.
Example:
d. Set Literals
57
Sets are unordered collections of unique items, enclosed in curly braces
({}).
Example:
my_set = {1, 2, 3, 4, 5}
6. Special Literals
Python also has special literals, such as Ellipsis (...), which is used in
certain advanced features like slicing multi-dimensional arrays in NumPy.
Example:
ellipsis_literal = ...
Summary of Literals:
58
Collection Literals: Lists ([]), tuples (()), dictionaries ({}), and sets ({}).
OPERATORS
1. Assignment operator =
2. Comparison operators
59
● Greater than (>), Less than (<), Greater than or equal to (>=), Less
than or equal to (<=)**: Used for comparisons. Example: if x > 5:.
3. Logical operators
4. Ellipsis ...
4. Operators +, -, *, /, etc.
5. Double Asterisk **
60
● Exponentiation: Used for raising numbers to a power. Example: x =
2 ** 3.
● Dictionary unpacking: Used to unpack dictionaries. Example:
function(**my_dict).
6. At symbol @
def my_function():
pass
7. Backslash \
8. Tilde ~
61
9. Pipe |
11. Caret ^
14. Underscore _
62
● Name mangling: Used in class methods to prevent accidental
access to private variables. Example: __my_var.
Multiline strings: Used for strings that span multiple lines. Example:
"""This is
a multiline
string."""
17. Hash #
63
● Floor division: Used to perform integer division. Example: 7 // 2
results in 3.
19. Percent %
1. Arithmetic Operators
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
64
* Multiplication 5 * 3 15
% Modulus 5 % 2 1
(remainder)
** Exponentiation 2 ** 3 8
(power)
// Floor division 5 // 2 2
(returns integer)
65
Operator Description Example Output
== Equal to 5 == 3 False
3. Logical Operators
66
Logical operators combine conditional statements and return a boolean
value.
4. Assignment Operators
67
= Assigns value x = 5 x = 5
+= Adds and x += 3 x = x + 3
assigns
-= Subtracts and x -= 3 x = x - 3
assigns
*= Multiplies and x *= 3 x = x * 3
assigns
/= Divides and x /= 3 x = x / 3
assigns
%= Modulus and x %= 3 x = x % 3
assigns
68
//= Floor division x //= 3 x = x // 3
and assigns
5. Bitwise Operators
` ` Bitwise OR `5
^ Bitwise XOR 5 ^ 3 6
69
~ Bitwise NOT ~5 -6
6. Membership Operators
70
not in Returns True if 'b' not in True
value is not 'apple'
found
7. Identity Operators
71
8. Ternary Operator
Syntax:
Example:
x = 5
9. Operator Precedence
72
PUNCTUATORS
1. Parentheses ( )
2. Square brackets [ ]
3. Curly braces { }
73
● Set: Also used to define sets. Example: my_set = {1, 2, 3}.
● Formatted strings (f-strings): Used in f-strings to embed
expressions. Example: f"Value is {variable}".
4. Colon :
5. Semicolon ;
6. Comma ,
74
● Multiple assignment: Used to assign multiple variables in one line.
Example: x, y = 1, 2.
7. Period .
These punctuators allow Python to interpret the structure, logic, and flow of
your code effectively.
ERRORS
Python, errors and exceptions are inevitable, and they occur when the
interpreter encounters something that prevents the program from
executing. The three main categories of errors are syntax errors, logical
errors, and runtime errors. Let's explore each in detail:
1. Syntax Errors
Definition:
A syntax error occurs when the Python interpreter encounters invalid
syntax. In simpler terms, the code does not follow the rules and structure
75
that Python expects. These errors are usually caught by the interpreter at
the time of code parsing before execution begins.
Common Causes:
Example:
Error Message:
Characteristics:
2. Logical Errors
76
Definition:
Logical errors occur when the program runs successfully but produces
incorrect or unintended results. These errors are due to a flaw in the logic
or algorithm used in the code, but Python itself does not flag these as
errors because they are technically valid operations.
Common Causes:
Example:
x = 10
y = 5
Here, the program runs successfully but gives an incorrect output because
the formula for calculating the average is wrong. The correct formula
should be (x + y) / 2.
Characteristics:
77
● The program continues running normally, but it produces the wrong
results.
● Debugging logical errors requires testing and analyzing the output.
Definition:
Runtime errors occur while the program is running, leading to abnormal
termination. Unlike syntax errors, the code passes the initial parsing stage
but fails during execution. These errors are typically caused by illegal
operations, such as division by zero, invalid memory access, or
file-handling issues.
Common Causes:
x = 10
y = 0
78
Error Message:
Error Message:
Error Message:
Characteristics:
79
● Detected at runtime (during the execution of the program).
● Can cause the program to terminate unless handled properly.
● Python provides mechanisms for handling runtime errors through
exception handling using try and except blocks.
Example:
try:
except ZeroDivisionError:
print("Program continues...")
Output:
80
You can't divide by zero!
Program continues...
Summary of Differences:
81
● TypeError: When an operation is applied to an object of
inappropriate type.
● IndexError: When trying to access an index that is out of range in
a list or tuple.
● KeyError: When trying to access a dictionary with a key that doesn't
exist.
● FileNotFoundError: When trying to open a file that doesn’t exist.
● ValueError: When a function receives an argument of the correct
type but inappropriate value.
● ImportError: When an import statement fails to find the module
definition.
These errors can be prevented through careful testing, and runtime errors
can be managed through exception handling, ensuring the program
continues to function even in exceptional circumstances.
UNIT II
1. Expression
2. Evaluation of an expression
3. Type-conversion
4. Flow of Control,
82
5. Conditional statements
6. Iterative Statements
1. Expression
An expression in Python is a combination of values, variables, operators, and function
calls that are evaluated to produce another value. An expression can be as simple as a
Example of an expression:
x = 5 + 3 * 2 # 5 + 6 = 11
2. Evaluation of an Expression
Evaluation refers to the process of executing an expression and obtaining a final result.
Python follows the rules of operator precedence to determine the order in which parts of
the expression are evaluated. After each operation is performed, Python moves on to
83
Example:
x = 10
y = 5
x = 5 # int
y = 2.5 # float
# Output: 7.5
x = "100"
string to integer
84
print(y + 10) # Output: 110
4. Flow of Control
Flow of control determines the order in which individual statements, instructions, or
function calls are executed or evaluated. In Python, the flow of control is determined by
Example:
x = 10
if x > 5:
else:
to 5")
5. Conditional Statements
85
Conditional statements allow Python to make decisions based on certain conditions.
These are implemented using the if, elif, and else keywords.
Syntax:
if condition:
condition is true
elif another_condition:
another_condition is true
else:
Example:
x = 8
if x > 10:
86
print("x is equal to 8")
else:
Output:
x is equal to 8
Nested if statements:
You can also nest if statements inside each other to evaluate multiple conditions in
sequence.
x = 10
if x > 5:
if x < 20:
loops:
● for loop: Iterates over a sequence (such as a list, tuple, string, or range).
● while loop: Repeats as long as a condition is true.
87
The for loop is used to iterate over elements in a sequence or range.
Syntax:
Example:
generates numbers 0 to 4
print(i)
Output:
0 1 2 3 4
my_list = [1, 2, 3, 4]
print(item)
Syntax:
Example:
88
x = 5
while x > 0:
print(x)
x -= 1 # Decrement x
Output:
5 4 3 2 1
Controlling Loops:
● break statement: Exits the loop immediately.
● continue statement: Skips the current iteration and proceeds to the next
iteration.
● else with loops: The else clause is executed if the loop completes all iterations
without encountering a break statement.
for i in range(10):
if i == 5:
print(i)
Output:
0 1 2 3 4
89
Example with continue:
for i in range(5):
if i == 2:
print(i)
Output:
0 1 3 4
for i in range(5):
print(i)
else:
Output:
0 1 2 3 4
90
● while loop: Used when the condition is more dynamic, or the number of
iterations is unknown beforehand (e.g., when waiting for a condition to become
false).
for i in range(3):
print("Hello")
x = 3
while x > 0:
print("Hello")
x -= 1
This loop prints "Hello" while x is greater than 0, and the iterations depend on the
changing value of x.
Conclusion
● Expressions: Combinations of variables and operators that are evaluated to a
result.
● Evaluation: The process of calculating the value of an expression.
● Type Conversion: Changing data types explicitly or implicitly.
● Flow of Control: Determines the execution path of a program.
● Conditional Statements: Control decision-making in the program.
91
● Iterative Statements (Loops): Repeat actions in a controlled manner using for
and while loops.
Strings in Python
String Operations
str1 = "Hello"
str2 = "World"
92
result = str1 + " " + str2
result = "Hello" * 3
# Output: "HelloHelloHello"
# Output: True
93
Slicing: Extracting a portion of the string using slice notation
[start:end:step].
You can traverse a string using for or while loops to access each character:
print(char)
This will print each character of the string "Hello" on a new line.
94
Built-in String Functions and Methods
len("Hello")
# Output: 5
"hello world".capitalize()
"hello world".title()
95
# Output: "Hello World"
"Hello".lower()
# Output: "hello"
"hello".upper()
# Output: "HELLO"
"hello hello".count("hello")
96
# Output: 2
"hello".find("l")
# Output: 2
"hello".index("l")
# Output: 2
97
"hello".endswith("lo")
# Output: True
"hello".startswith("he")
# Output: True
"Hello123".isalnum()
# Output: True
98
"Hello".isalpha()
# Output: True
"1234".isdigit()
# Output: True
"hello".islower()
# Output: True
99
isupper(): Returns True if all alphabetic characters in the string are
uppercase.
"HELLO".isupper()
# Output: True
" ".isspace()
# Output: True
" hello".lstrip()
# Output: "hello"
100
rstrip(): Removes trailing whitespace from the string.
"hello ".rstrip()
# Output: "hello"
# Output: "hello"
replace(old, new): Replaces all occurrences of the old substring with the
new substring.
101
join(iterable): Joins the elements of an iterable (like a list) into a string,
separated by the string it's called on.
"-".join(["hello", "world"])
# Output: "hello-world"
partition(separator): Splits the string into three parts: the part before the
separator, the separator itself, and the part after.
102
# Output: ['hello', 'world']
Summary
Strings in Python are powerful and come with various built-in operations
and methods that make manipulation easy, such as concatenation,
repetition, slicing, and several others for transforming and analyzing the
content.
ARRAY IN PYTHON
In Python, arrays can be managed using lists, as Python does not have a
dedicated array data type like some other languages (such as C or Java).
Lists are versatile, dynamic, and allow elements of any data type. Here's a
detailed explanation of common array (or list) operations in Python.
103
To access an element in a list, you use its index in square brackets.
Indexing in Python starts at 0, so the first element is at index 0, the second
at index 1, and so on.
# Define a list
# Access elements
print(arr[0]) # Output: 10
print(arr[2]) # Output: 30
2. Length of an Array
To get the length (number of elements) in a list, use the len() function.
104
arr = [10, 20, 30, 40, 50]
print(len(arr)) # Output: 5
Example
arr.append(40)
105
print(arr) # Output: [10, 20, 30, 40]
arr.extend([50, 60])
106
4. Removing Array Elements
Example
arr.remove(30)
107
print(arr) # Output: [10, 20, 40, 50]
arr.pop(1)
arr.pop()
108
# Clear all elements
arr.clear()
print(arr) # Output: []
You can use the insert() method to add an element at a specific position
and the pop() method with an index to remove an element at a specific
position.
Example
109
# Adding an element at index 2
Summary
110
● Adding Elements: Use append(), insert(), or extend() to add
elements.
● Removing Elements: Use remove(), pop(), or clear() to
remove elements.
● Adding/Removing at Specific Position: Use insert(position,
element) to add, and pop(index) to remove elements at a
specific position.
These operations make lists in Python a flexible tool for handling arrays.
Lists in Python
A list in Python is an ordered, mutable, and dynamic collection that allows
elements of different data types. Lists are one of the most versatile data
structures in Python and are used widely for data storage and
manipulation.
1. Introduction to Lists
# Creating a list
111
my_list = [1, 2, 3, 4, 5]
2. Indexing in Lists
Elements in a list are accessed by their index, with the first element at
index 0. Negative indexing allows access from the end of the list.
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
112
3. List Operations
list1 = [1, 2, 3]
list2 = [4, 5]
●
list1 = [1, 2]
●
●
113
4. Traversing a List Using Loops
You can use a for or while loop to iterate through each element in a list.
print(item)
i = 0
print(my_list[i])
i += 1
len(), list()
114
len(): Returns the number of elements in the list.
●
●
my_list = [1, 2, 3]
●
my_list = [1, 2, 3]
115
●
my_list = [1, 2, 4]
●
Count, Index
my_list = [1, 2, 2, 3, 2]
my_list.count(2) # Output: 3
●
my_list = [1, 2, 3]
my_list.index(3) # Output: 2
●
Remove, Pop
116
remove(element): Removes the first occurrence of the specified
element. Raises a ValueError if the element is not found.
my_list = [1, 2, 3, 2]
●
my_list = [1, 2, 3]
●
117
●
my_list = [3, 1, 2]
●
my_list = [3, 1, 2]
●
●
118
max(list): Returns the largest element in the list.
●
sum(list): Returns the sum of all elements in the list. Elements must be
numeric.
●
Summary
Lists in Python provide a wide range of functionality, from basic access and
modification to advanced sorting and aggregation functions. They support
various operations to facilitate data manipulation, making them a powerful
tool in Python programming.
Tuple
Tuples in Python
119
change throughout the program. Tuples are defined using parentheses ( ) and can
contain elements of any data type.
1. Introduction to Tuples
A tuple can hold any number of elements, including nested tuples or mixed data
types. They are defined by placing elements inside parentheses, separated by
commas.
# Creating tuples
my_tuple = (1, 2, 3)
single_element_tuple = (42,)
2. Indexing in Tuples
Elements in a tuple are accessed using an index, just like in lists. Indexing starts at
0 for the first element, and negative indexing starts at -1 for the last element.
120
# Accessing elements by positive index
print(my_tuple[0]) # Output: 10
print(my_tuple[2]) # Output: 30
print(my_tuple[-1]) # Output: 50
print(my_tuple[-3]) # Output: 30
3. Tuple Operations
Since tuples are immutable, they support fewer operations than lists. You can still
concatenate and repeat tuples.
tuple2 = (4, 5)
121
Repetition: Repeat elements in a tuple using the * operator.
tuple1 = (1, 2)
You can iterate through a tuple using a for loop to access each element.
print(item)
122
# Using a while loop
i = 0
print(my_tuple[i])
i += 1
print(len(my_tuple)) # Output: 3
123
list(): Converts a tuple to a list, allowing modification.
my_tuple = (1, 2, 3)
Count, Index
print(my_tuple.count(2)) # Output: 3
print(my_tuple.index(3)) # Output: 2
Note: Tuples do not have methods like append(), extend(), insert(), remove(), pop(),
reverse(), or sort(), as they are immutable.
min(tuple): Returns the smallest element in the tuple. All elements must be of
a comparable type (e.g., all integers or all strings).
my_tuple = (10, 20, 30)
124
print(min(my_tuple)) # Output: 10
print(max(my_tuple)) # Output: 30
sum(tuple): Returns the sum of all elements in the tuple. Elements must be
numeric.
my_tuple = (10, 20, 30)
print(sum(my_tuple)) # Output: 60
Here’s a comprehensive example using tuples and various functions and methods:
my_tuple = (1, 3, 5, 7)
# Tuple operations
125
concat_tuple = my_tuple + (9, 11) #
Concatenation
# Built-in functions
126
Summary
Tuples are used when you need a sequence of items that should remain constant
throughout the program.
Application example
1. Storing Coordinates
Tuples are often used to store fixed sets of related data, such as coordinates in a 2D
or 3D space.
127
# Representing a point in 2D space
Tuples are useful when a function needs to return multiple values. Instead of
creating separate variables, the function can return a single tuple containing all the
values.
def get_student_details():
128
# Unpacking the tuple into separate variables
3. Dictionary Keys
Tuples are often used as keys in dictionaries when you need a composite key (more
than one piece of data to act as a key). Since tuples are immutable, they can be
used as dictionary keys, whereas lists cannot.
location_data = {
129
4. Storing Immutable Data in a Collection
Sometimes, you need a list of data items that should not be changed once created.
Using a list of tuples ensures that the data remains immutable.
students = [
5. Database Records
130
When fetching data from a database, each record can be represented as a tuple.
This helps to group all related fields together as an immutable sequence.
print("Name:", record[0])
print("Age:", record[1])
print("Job:", record[2])
Since tuples are immutable, they are well-suited to storing constant data like the
days of the week, months, or other fixed categories.
131
print("First day of the week:", days_of_week[0])
Tuples make it easy to pack multiple values into one variable and later unpack
them. This can simplify code when handling related values together.
Summary
Tuples provide an efficient way to group related data and work especially well
when data immutability is important, such as in storing database records, handling
multiple return values from functions, or using as keys in dictionaries. Their
132
immutability also makes tuples efficient and reliable for storing constant or fixed
data.
Dictionary
In Python, a dictionary is an unordered collection of key-value pairs.
Dictionaries are mutable, which means you can add, update, or delete items.
However, the keys must be unique and immutable (e.g., strings, numbers, or
tuples), while the values can be of any type.
1. Introduction to Dictionaries
Dictionaries are created using curly braces {} with key-value pairs separated by
colons :. Each key-value pair is separated by a comma.
# Creating a dictionary
my_dict = {
"name": "Alice",
"age": 25,
133
"profession": "Engineer"
2. Indexing in Dictionaries
Dictionaries are not indexed by position but by keys. You can use a key to access
its associated value.
my_dict = {
"profession": "Engineer"
134
# Accessing values using keys
print(my_dict["age"]) # Output: 25
3. Dictionary Operations
● Adding a key-value pair: You can add new items by assigning a value to a new
key.
● Updating values: Assign a new value to an existing key.
● Removing items: Use del or pop() to remove elements.
135
# Adding a key-value pair
my_dict["profession"] = "Engineer"
# Updating a value
my_dict["age"] = 26
del my_dict["age"]
You can iterate over the keys, values, or both using loops.
136
my_dict = {"name": "Alice", "age": 25, "profession":
"Engineer"}
print(key)
print(value)
print(f"{key}: {value}")
len(), list()
137
len(dictionary): Returns the number of key-value pairs in the dictionary.
print(len(my_dict)) # Output: 3
●
●
These methods are not applicable to dictionaries as they are specific to lists.
138
● popitem(): Removes and returns the last key-value pair as a tuple (since
Python 3.7, dictionaries maintain insertion order).
profession = my_dict.pop("profession")
last_item = my_dict.popitem()
reverse(), sort()
139
● sorted(): Returns a sorted list of keys or values. It does not modify the
dictionary.
# Sorting keys
sorted_keys = sorted(my_dict)
# Sorting values
sorted_values = sorted(my_dict.values())
140
● max(dictionary): Returns the largest key.
● sum(dictionary): Returns the sum of all keys (if numeric).
print(min(my_dict)) # Output: 1
print(max(my_dict)) # Output: 3
print(sum(my_dict)) # Output: 6
141
● update(): Updates the dictionary with another dictionary or key-value
pairs.
print(my_dict.values()) # Output:
dict_values(['Alice', 25])
142
Application Example
grades["David"] = 88
# Update a grade
grades["Alice"] = 95
# Remove a student
grades.pop("Charlie")
143
average_grade = sum(grades.values()) / len(grades)
Summary
Ni
144
In Python, modules are collections of functions, classes, and variables that help
organize and reuse code. You can import these modules using two main
approaches: import and from ... import.
This method imports the entire module, allowing you to access its functions and
variables using the module name as a prefix.
Syntax:
import module_name
import math
pi_value = math.pi
sqrt_value = math.sqrt(16)
ceil_value = math.ceil(4.2)
145
Advantages:
Syntax:
print(pi) # 3.141592653589793
print(sqrt(25)) # 5.0
print(ceil(4.2)) # 5
146
Advantages:
1. math Module
147
floor() Rounds a number down math.floor(4.7)
to the nearest integer -> 4
Example Usage:
print(pi) # 3.141592653589793
148
print(e) # 2.718281828459045
print(sqrt(9)) # 3.0
print(ceil(3.7)) # 4
print(floor(3.7)) # 3
print(fabs(-5)) # 5.0
print(cos(0)) # 1.0
2. random Module
149
randint(a, b) Returns a random integer random.randint(1,
between a and b 10) -> 5
(inclusive)
Example Usage:
print(random())
# Example: 0.753849
print(randint(1, 6))
3. statistics Module
150
Provides functions for statistical calculations.
Example Usage:
data = [1, 2, 2, 3, 4, 4, 4, 5]
print(mean(data)) # 3.125
print(median(data)) # 3.5
print(mode(data)) # 4
151
Summary
Functions in Python
1. Types of Functions
152
print("Hello, World!") # Built-in function
import math
def greet(name):
153
print(greet("Alice")) # Output: Hello, Alice!
2. Function Arguments
Positional Arguments
Arguments passed in order.
return a + b
def greet(name="World"):
154
print(greet("Alice")) # Output: Hello, Alice!
def square(x):
return x * x
155
print(square(4)) # Output: 16
return a + b, a - b, a * b, a / b
4. Recursion
def factorial(n):
if n == 0:
156
return 1
else:
return n * factorial(n - 1)
5. Scope of a Variable
Local Scope
Variables declared inside a function.
def example():
x = 5 # Local variable
print(x)
example() # Output: 5
157
1. Global Scope
Variables declared outside functions.
x = 10 # Global variable
def example():
print(x)
example() # Output: 10
def modify_global():
global x
x += 5
modify_global()
print(x) # Output: 15
158
Summary
Concept Example
Recursion factorial(n)
159
FILES
Introduction to Files
Types of Files
160
○ Used for exchanging structured data.
○ Example: .csv.
Mode Description
161
w+ Opens a file for both writing and
reading.
file_object.close()
The with statement ensures the file is properly closed after its block of
code is executed:
# Perform operations
162
Writing/Appending to a Text File
Using write()
file.write("Hello, World!")
Using writelines()
file.writelines(lines)
Appending Data
163
Reading from a Text File
Using read()
content = file.read()
print(content)
Using readline()
line = file.readline()
print(line)
Using readlines()
164
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
# Writing to a file
165
with open("example.txt", "r") as file:
print("Full content:")
print(file.read())
print(line.strip())
lines = file.readlines()
print("\nLines as a list:")
print(lines)
Output:
166
Full content:
Lines as a list:
167
● The file must exist; otherwise, it raises a FileNotFoundError.
● Writing starts at the beginning of the file, overwriting existing content.
file.write("Original content.\n")
# Open in r+ mode
print("Before writing:")
print(file.read())
file.seek(0)
file.write("Updated content.")
168
# Move the cursor to the beginning again to read
updated content
file.seek(0)
print("\nAfter writing:")
print(file.read())
Output:
Before writing:
Original content.
After writing:
Updated content.
169
# Open in w+ mode
file.write("Writing in w+ mode.\n")
file.seek(0)
print(file.read())
Output:
Writing in w+ mode.
170
3. a+ (Append and Read)
file.write("Initial content.\n")
# Open in a+ mode
file.write("Appended content.\n")
file.seek(0)
171
print(file.read())
Output:
Initial content.
Appended content.
172
173
174