Python UNIT-I
Python UNIT-I
1. Introduction to Python
1.1 What is Python?
Python is a high-level, interpreted programming language created by Guido van Rossum
and released in 1991. The language was named after the British comedy group Monty
Python, reflecting the creator's aim to make programming fun. It emphasizes code
readability with its notable use of significant whitespace and simple, clear syntax to bridge
the gap between C and shell scripting.
🔹 When writing full programs (automation scripts, data analysis, web development).
🔹 When working with large codebases (multiple functions, modules, or classes).
🔹 When performance is important (batch processing, file handling).
🔹 When using external libraries (NumPy, Pandas, TensorFlow, etc.).
When to Use Interactive Mode?
❌ No instant feedback – Unlike interactive mode, you won’t see results immediately.
❌ Debugging is slower – If an error occurs, you need to modify and re-run the script.
❌ Not ideal for quick testing – Interactive mode is better for testing small snippets of
code.
2.3 Comparing Interactive and Script Modes
Feature Interactive Mode Script Mode
Execution Line by line Entire file
Storage Temporary Permanent
Use Case Testing, Learning Development
Complexit Simple operations Complex programs
y
Reusability Limited High
3. Python Tokens
3.1 Understanding Tokens
Python tokens are the smallest meaningful individual units in a Python program, which the
interpreter recognizes and processes to execute the code. Every Python program is made
up of tokens, categorized into five main types.
Tokenization Process in Python
Python’s interpreter converts the raw source code into tokens using a process called
tokenization. The process involves:
1. Lexical Analysis: The interpreter reads the code line-by-line and breaks it down into
tokens (keywords, identifiers, operators, etc.).
2. Parsing: The tokens are analyzed to understand their meaning in the context of the
program.
Ex: x=10+5 Is broken down into the following tokens:
🔹 x (Identifier)
🔹 = (Assignment Operator)
🔹 10 (Literal)
🔹 + (Arithmetic Operator)
🔹 5 (Literal)
The interpreter then interprets these tokens based on Python’s syntax rules.
Identifiers Must start with a letter or _, can contain letters, digits, or _, case-sensitive
Operators Must be used with correct data types, assignment (=) vs. comparison (==)
Special Symbols Used for syntax ((), {}, [], :), comments (#, """ """)
4. Variables and Memory Management
In Python, a variable is a name or reference that refers to a value stored in the computer's
memory. Variables are used to store data so that you can manipulate, access, and modify it
throughout your program. Let's go over the concept of variables in Python in a detailed
manner.
4.1 What is a Variable?
A variable in Python is like a container that holds a value, and this value can change (hence
the name "variable"). The variable itself is a reference or label to the memory location
where the actual data is stored.
4.2 Creating Variables in Python
To create a variable in Python, all you need to do is assign a value to it using the =
(assignment operator). The syntax is: variable_name = value
Here, variable_name is the name you choose for the variable, and value is the data you
assign to that variable.
Heap Memory:,. Stores all Python objects like lists, dictionaries, and class instances and
dynamically allocated memory
Example: list1 = [1, 2, 3] # The list is stored in heap memory
4.12 Conclusion
In Python, variables are a fundamental part of any program. They allow you to store,
modify, and reference data. With Python's dynamic typing, variables can hold any data type
without needing explicit type definitions. Understanding how to create, assign, and
manipulate variables is key to writing Python programs.
5. Python Keywords
5.1 What are Keywords?
Keywords are reserved words that have special meanings in Python. They cannot be used
as variable names or identifiers. In Python the list of keywords can be viewed using the
keyword module.
import keyword
print(keyword.kwlist)
# while loop
while condition:
# code block
# for loop
for item in sequence:
# code block
# Class definition
class ClassName:
pass
Exception Handling Keywords:
try:
# code that might raise an exception
except Exception:
# handle exception
finally:
# always executed
1. False
Explanation: The False keyword represents a boolean value of false. It is used in logical
operations and control flow statements.
Example:
print(False)
Output:
False
2. None
Explanation: The None keyword represents the absence of a value or a null value. It is
commonly used to indicate that a variable has no assigned value.
Example:
x = None
print(x)
Output:
None
3. True
Explanation: The True keyword represents a boolean value of true. It is used in logical
operations and conditions.
Example:
print(True)
Output:
True
4. and
Explanation: The and keyword is used as a logical operator that returns True if both
conditions are True.
Example:
Output:
False
5. as
Example:
import math as m
print(m.sqrt(16))
Output:
4.0
6. assert
Explanation: The assert keyword is used for debugging; it raises an error if the condition
evaluates to False.
Example:
x=5
y = 10
assert x < y
print("Assertion Passed")
Output:
Assertion Passed
7. async:
Explanation: The async keyword in Python is used for writing asynchronous code, allowing
for non-blocking execution. It is primarily used with the await keyword to define
coroutines, which enable efficient execution of tasks like I/O operations (network requests,
file handling, etc.) without freezing the entire program.
import asyncio
async def task1():
print("Task 1 started")
await asyncio.sleep(3)
print("Task 1 completed")
async def task2():
print("Task 2 started")
await asyncio.sleep(1)
print("Task 2 completed")
async def main():
await asyncio.gather(task1(), task2()) # Run both tasks concurrently
asyncio.run(main())
Output:
Task 1 started
Task 2 started
(1 second delay)
Task 2 completed
(2 seconds delay)
Task 1 completed
8.await
Output:
import asyncio
Output:
Task started
(2 seconds delay)
Task finished
9. break
Explanation: The break keyword is used to exit a loop prematurely when a certain
condition is met. It is commonly used in for and while loops.
Example:
for i in range(5):
if i == 3:
break
print(i)
Output:
10. class
Explanation: The class keyword in Python is used to define a class, which is a blueprint for
creating objects. A class allows you to bundle data (attributes) and functions (methods)
together, supporting the principles of object-oriented programming (OOP) such as
encapsulation, inheritance, and polymorphism.
Example:
class Person:
# Constructor to initialize object attributes(Initializes each Person with a name and age.)
def introduce(self):
# Creating objects (instances) of the class(person1 with name and age, Person2 with name
and age)
person1.introduce()
person2.introduce()
Output:
Explanation: The continue keyword in Python is used inside loops (for or while) to skip the
current iteration and move to the next one. It does not terminate the loop but simply jumps
to the next iteration.
Example:
for i in range(5):
if i == 2:
continue
print(i)
Output:
12. def
Explanation: The def keyword in Python is used to define a function. A function is a reusable
block of code that performs a specific task. The def keyword is followed by the function
name, parentheses (), and a colon : to start the function body.
Example:
1) def greet():
print(greet())
Output:
Hello, World!
2) def greet(name):
print(f"Hello, {name}!")
# Calling the function with an argument
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
13. del
Explanation: The del keyword in Python is used to delete objects, variables, list elements,
dictionary keys, or attributes of an object. It helps manage memory by removing
unnecessary references to objects.
Example:
Deleting a variable:
x = 10
print(x) # Output: 10
del x
print(x) # Raises NameError: name 'x' is not defined
14. elif
Explanation: The elif keyword in Python is used for multiple conditional statements in an
if-elif-else structure. It allows checking multiple conditions sequentially, where only the
first true condition executes.
Example:
num = 15
if num < 10:
print("Number is less than 10")
elif num < 20:
print("Number is between 10 and 20")
elif num < 30:
print("Number is between 20 and 30")
else:
print("Number is 30 or more")
Output:
Number is between 10 and 20
15. else
Explanation: The else keyword in Python is used to define a block of code that executes
when the preceding conditional statements (if, elif, try-except, loops) fail. It works in
various contexts such as if-else statements, try-except blocks, and loops.
Example:
x=5
if x > 10:
else:
Output:
16. except
Explanation: The except keyword in Python is used in the context of exception handling.
The except keyword is used to handle exceptions and prevent crashes in Python programs.
An exception is an error that occurs during program execution. When an exception occurs,
Python stops executing the program and looks for a way to handle the error.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
Output:
17. finally
Explanation: The finally keyword is used in exception handling to define a block of code
that executes regardless of whether an exception occurs or not.
Example:
try:
x = 10 / 0
except:
print("Error Occurred")
finally:
print("Execution Completed")
Output:
Error Occurred
Execution Completed
18. for
Explanation: The for keyword is used to create loops that iterate over a sequence (e.g.,
lists, tuples, strings, or ranges).
Example:
for i in range(3):
print(i)
Output:
19. from
Explanation: The from keyword in Python is primarily used for importing modules or
specific attributes from a module. It helps in optimizing imports by allowing you to import
only what you need.
Example:
print(sqrt(25))
Output:
5.0
20. global
Explanation: The global keyword in Python is used to declare a global variable inside a
function, allowing modifications to a variable defined outside the function's local scope.
Normally, variables inside a function are local by default, meaning they do not affect
variables outside the function unless explicitly declared as global
Example:
x = 10 # Global variable
def modify():
print("Inside function:", x)
modify()
print("Outside function:", x)
Output:
Inside function: 20
Outside function: 20
21. if
Example:
x = 10
if x > 5:
Output:
x is greater than 5
22. import
Explanation: The import keyword is used to bring external modules or packages into the
current Python script. This allows you to access and use functions and classes from other
Python files or libraries.
Example:
import math
print(math.pi)
Output:
3.141592653589793
23. in
Explanation: The in keyword in Python is used for membership testing and iteration. It is
primarily used in two scenarios.
1)Membership Testing: To check if a value exists in a sequence (like lists, tuples, sets,
dictionaries, or strings).
2) Iteration: Used in for loops to iterate over iterable objects.
It returns True if the value is found and False otherwise.
Example:
Output:
True
24. is
Explanation: The is keyword is used to compare whether two variables point to the same
object in memory, rather than checking if their values are equal.
Example:
x = [1, 2, 3]
y=x
print(x is y)
Output:
True
25. lambda
Explanation: The lambda keyword is used to define small, anonymous functions in a single
line. These functions can take any number of arguments but can only contain a single
expression, that return a value without requiring a return statement.
Example:
square = lambda x: x * x
print(square(5))
Output:
25
26. nonlocal
Explanation: The nonlocal keyword is used inside nested functions to modify a variable
defined in an outer (but non-global) function.
Example:
def outer():
x = "Hello"
def inner():
nonlocal x
x = "World"
inner()
print(x)
outer()
Output:
World
27. not
Explanation: The not keyword is used to negate a boolean expression, returning the
opposite logical value.
Example:
print(not False)
Output:
True
28. or
Explanation: The or keyword is used in logical expressions to return True if at least one of
the conditions is true.
Example:
print(True or False)
Output:
True
29. pass
Explanation: The pass keyword in Python is a null statement that serves as a placeholder
where code is syntactically required but should do nothing when executed. It allows you to
write code structures that you plan to implement later without causing syntax errors.
Example:
def my_function():
Output:
30. raise
Explanation: The raise keyword in Python is used to explicitly throw an exception during
program execution. It allows programmers to trigger exceptions manually when a specific
condition occurs.
Example:
age = -5
if age < 0:
Output:
31. return
Explanation: The return keyword is used to exit a function and send back a value to the
caller.
Example:
return a + b
print(add(3, 4))
Output:
32. try
Explanation: The try keyword is used to define a block of code in which exceptions might
occur. It is usually paired with except to handle errors gracefully.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
Output:
33. while
Explanation: The while keyword is used to create loops that execute repeatedly while a
given condition is True.
Example:
x=0
while x < 3:
print(x)
x += 1
Output:
34. with
Explanation: The with keyword is used to simplify resource management, such as file
handling, ensuring that the resource is properly cleaned up after use.
Example:
file.write("Hello World")
35. yield
Explanation: The yield keyword is used in generator functions to return values one at a
time, allowing iteration without storing the entire sequence in memory. The keyword yield
is similar to return, but instead of terminating the function, it pauses the function and
allows it to be resumed later. When a function contains yield, it becomes a generator
function. Unlike normal functions that return a single value, a generator can produce a
sequence of values over time.
Example:
def generator():
yield 1
yield 2
yield 3
print(value)
Output:
def calculate_area(radius):
"""
Calculates the area of a circle.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2
7. Literals in Python
7.1 Understanding Literals
Literals are data items that have a fixed value. They represent themselves and are the
simplest form of data in Python.
# Float literals
pi = 3.14159
e = 2.71828
scientific = 1.23e-4
# Double quotes
double = "Hello"
# Triple quotes
multi = """This is a
multi-line
string"""
# Raw string
raw = r"C:\Users\name"
# Unicode string
unicode = u"Hello World"
# String formatting
name = "Alice"
age = 25
formatted = f"{name} is {age} years old"
8. Data Types
8.1 Numeric Types
8.1.2 Float
# Float examples
pi = 3.14159
e = 2.71828
small = 1.23e-4
8.1.3 Complex
# Complex number examples
c1 = 3 + 4j
c2 = complex(3, 4)
8.2.2 List
# List examples
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [1, [2, 3], 4]
# List operations
numbers.append(6)
numbers.extend([7, 8])
numbers.insert(0, 0)
8.2.3 Tuple
# Tuple examples
coordinates = (3, 4)
nested_tuple = (1, (2, 3), 4)
# Tuple unpacking
x, y = coordinates
# Dictionary operations
person["email"] = "john@example.com"
age = person.get("age")
8.4.1 Set
# Set examples
unique_numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}
# Set operations
unique_numbers.add(6)
unique_numbers.remove(1)
# Boolean operations
result = is_valid and not is_empty
9.3.1 If Statements
if condition:
# First level indentation
statement1
statement2
if another_condition:
# Second level indentation
statement3
statement4
else:
# Back to first level
statement5
9.3.2 Loops
for i in range(5):
# Loop body indented
print(i)
if i % 2 == 0:
# Nested block further indented
print("Even number")
9.3.3 Functions
def calculate_square(number):
# Function body indented
square = number ** 2
if square > 100:
# Nested block
return "Large number"
return square
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333...
floor_division = a // b # 3
modulus = a % b # 1
exponent = a ** b # 1000
equal = x == y # False
not_equal = x != y # True
greater_than = x > y # False
less_than = x < y # True
greater_equal = x >= y # False
less_equal = x <= y # True
# Compound assignment
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 4 # x = x * 4
x /= 2 # x = x / 2
x //= 3 # x = x // 3
x %= 3 # x = x % 3
x **= 2 # x = x ** 2
# Bitwise AND
c = a & b # 12 = 0000 1100
# Bitwise OR
d = a | b # 61 = 0011 1101
# Bitwise XOR
e = a ^ b # 49 = 0011 0001
# Bitwise NOT
f = ~a # -61 = 1100 0011
# Left shift
g = a << 2 # 240 = 1111 0000
# Right shift
h = a >> 2 # 15 = 0000 1111
is_same = x is z # True
is_not_same = x is y # False
# Complex expression
x = 5
y = 3
z = 2
result = x + y * z ** 2 - (x + y) / z
Arithmetic Expressions
# Simple arithmetic
result = 5 + 3 * 2
# Complex arithmetic
area = length * width
volume = length * width * height
# Mixed operations
total = price * quantity * (1 + tax_rate)
Boolean Expressions
# Comparison expressions
is_adult = age >= 18
String Expressions
# String concatenation
full_name = first_name + " " + last_name
# String formatting
greeting = f"Hello, {full_name}!"
# String operations
is_long_name = len(full_name) > 20
11.2 Statements
A statement is a complete line of code that performs an action.
Assignment Statements
# Simple assignment
x = 5
# Multiple assignment
a, b, c = 1, 2, 3
# Augmented assignment
counter += 1
Conditional Statements
# if statement
if temperature > 30:
print("It's hot!")
# if-else statement
if score >= 60:
print("Pass")
else:
print("Fail")
# if-elif-else statement
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
Loop Statements
# for loop
for i in range(5):
print(i)
# while loop
while counter < 10:
counter += 1
# Numeric input
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
# Using .format()
print("{} is {} years old".format(name, age))
# Currency formatting
price = 1234.5678
print(f"Price: ${price:,.2f}")
12.3 File Input/Output
# Processing phase
area = length * width
perimeter = 2 * (length + width)
diagonal = (length**2 + width**2) ** 0.5
# Output phase
print("\nResults:")
print(f"Area: {area:.2f} square units")
print(f"Perimeter: {perimeter:.2f} units")
print(f"Diagonal: {diagonal:.2f} units")
# Program execution
if __name__ == "__main__":
main()
13.5 Benefits and Limitations
Benefits:
• Simple to understand and implement
• Easy to debug
• Straightforward flow of control
• Good for simple calculations and processes
Limitations:
• Not suitable for complex problems
• Limited reusability
• Can become difficult to maintain for large programs
• No built-in error handling
while True:
try:
number = float(input("Enter a positive number: "))
if number <= 0:
raise ValueError("Number must be positive")
break
except ValueError as e:
print(f"Error: {e}")
def get_input():
# Input code here
return value
def process_data(value):
# Processing code here
return result
def display_result(result):
# Output code here
# Main program
value = get_input()
result = process_data(value)
display_result(result)
20. Error Handling
try:
# Main program logic
result = calculate_result(input_value)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Calculation successful")
finally:
print("Program completed")