0% found this document useful (0 votes)
25 views

PYTHON PROGRAMMING. PDF

Uploaded by

S.Shantha Ruby
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

PYTHON PROGRAMMING. PDF

Uploaded by

S.Shantha Ruby
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

PYTHON PROGRAMMING

UNIT:I
History of Python
 Early Development:
1. 1980s - Inspiration and Design:
o Guido van Rossum, a Dutch programmer, began working on Python in the late 1980s. He was
influenced by the ABC language, which was designed to be simple and intuitive.
o Van Rossum aimed to create a language that was both easy to read and write, and which could
overcome some of the limitations he saw in other programming languages of the time.
2. 1989 - Python's Birth:
o Van Rossum started implementing Python as a hobby project during the Christmas holidays. The
project was initially named "Python" as a tribute to the British comedy group Monty Python,
whose work van Rossum enjoyed.
 Early Versions:
3. 1991 - Python 0.9.0:
o The first public release, Python 0.9.0, was made available in February 1991. It included many
features that are still present today, such as exception handling, functions, and core data types
like lists and dictionaries.
4. 1994 - Python 1.0:
o Python 1.0 was released in January 1994. This release marked the beginning of Python's journey
as a formal, widely recognized programming language.
 Growth and Development
5. 2000 - Python 2.0:
o Python 2.0 was released in October 2000. This version introduced list comprehensions, garbage
collection, and other features that greatly enhanced the language’s capabilities and usability.
o Python 2.x series continued to evolve with several significant updates, but the language’s syntax
and core features remained relatively stable during this period.
6. 2008 - Python 3.0:
o Python 3.0, released in December 2008, was a major milestone. It was designed to rectify design
flaws and streamline the language, but it introduced backward-incompatible changes.
o Key improvements included better Unicode support, a more consistent syntax, and the
introduction of new libraries and features.
 Modern Era
7. 2010s - Python’s Rise:
o Throughout the 2010s, Python’s popularity surged due to its readability, versatility, and the rise
of data science and machine learning. Libraries like NumPy, pandas, and TensorFlow became
widely used in these fields.
o Python became a go-to language for web development, automation, scientific computing, and
more.
8. 2020s - Python 3.x and Continued Growth:
o Python 3.x versions continued to be released, with Python 3.9 and Python 3.10 bringing new
features and optimizations.
o Python 2.x officially reached its end of life on January 1, 2020, with no more updates or support
from the Python Software Foundation.
 Key Features and Impact
 Simplicity and Readability: Python's syntax emphasizes readability and simplicity, which makes it
accessible to beginners and useful for rapid development.
 Extensive Libraries: The availability of a wide range of libraries and frameworks has made Python a
powerful tool for web development, data analysis, artificial intelligence, and more.
 Community and Ecosystem: A large and active community contributes to Python's development and
supports a thriving ecosystem of third-party packages and tools.

 Features of Python:
1. Easy to Learn and Use
 Readable Syntax: Python’s syntax is clear and straightforward, which makes it easy to read and write.
This is often described as "executable pseudocode."
 Minimalistic Design: The language is designed to be easy to understand, with a focus on simplicity and
reducing boilerplate code.
2. Interpreted Language
 Dynamic Typing: Python does not require explicit type declarations. Variable types are determined at
runtime, which simplifies coding but may lead to runtime type errors.
 Interactive Shell: Python comes with an interactive shell (REPL) that allows for quick testing and
experimentation with code snippets.
3. Object-Oriented and Functional
 Object-Oriented Programming (OOP): Python supports OOP principles, including classes and
inheritance. This allows for the creation of modular and reusable code.
 Functional Programming: Python supports functional programming features such as higher-order
functions, anonymous functions (lambdas), and list comprehensions.
4. Extensive Standard Library
 Rich Library Support: Python’s standard library includes modules and packages for a wide range of
tasks, including file I/O, regular expressions, networking, and web services.
 Batteries Included: The philosophy of "batteries included" means that Python comes with a
comprehensive set of modules and tools to handle many common programming tasks.
5. Cross-Platform Compatibility
 Platform Independence: Python is available on many operating systems, including Windows, macOS,
and Linux, allowing developers to write cross-platform code.
 Portability: Python code can often run on different systems with little to no modification.
6. Extensible and Embeddable
 C/C++ Integration: Python can be extended with C or C++ code to improve performance for critical
sections of code. Libraries like Cython also facilitate this integration.
 Embedding: Python can be embedded within other applications to provide scripting capabilities.
7. Dynamic Typing
 Flexible Data Types: Variables in Python do not have fixed types. This dynamic nature allows for
flexible and rapid development but requires careful handling of type-related issues.
8. Large Ecosystem
 Package Management: Python has a robust ecosystem of third-party packages and tools. The pip
package manager makes it easy to install and manage these packages.
 Frameworks and Libraries: Python boasts numerous frameworks for web development (e.g., Django,
Flask), data science (e.g., NumPy, pandas, scikit-learn), and more.
9. High-Level Language
 Abstraction: Python abstracts away many low-level details such as memory management, allowing
developers to focus on problem-solving rather than system-level concerns.
 Garbage Collection: Python has built-in garbage collection to manage memory automatically, reducing
the risk of memory leaks.
10. Versatility
 General-Purpose: Python is used in various domains including web development, data analysis,
machine learning, automation, scientific computing, and more.
 Integration Capabilities: Python integrates well with other languages and tools, making it a versatile
choice for many different types of projects.
11. Community and Support
 Active Community: Python has a large and active community that contributes to its development,
provides support, and creates a wealth of educational resources and documentation.
 Open Source: Python is open source and governed by the Python Software Foundation, which ensures
its continued development and availability.
 Literal:
1.Numeric Literals
 Integer Literals:
a = 10 # Decimal integer
b = 0b1010 # Binary integer (0b prefix)
c = 0o12 # Octal integer (0o prefix)
d = 0xA # Hexadecimal integer (0x prefix)
o 10 is a decimal integer.
o 0b1010 is a binary representation of the integer 10.
o 0o12 is an octal representation of the integer 10.
o 0xA is a hexadecimal representation of the integer 10.
 Floating-Point Literals:
e = 3.14 # Regular floating-point number
f = 1.5e2 # Scientific notation (1.5 * 10^2, which is 150.0)
g = 2.5e-3 # Scientific notation (2.5 * 10^-3, which is 0.0025)
 Complex Number Literals:
h = 2 + 3j # Complex number with real part 2 and imaginary part 3
i = 1 - 4j # Complex number with real part 1 and imaginary part -4
2. String Literals
 Single-Quoted Strings:
s1 = 'Hello, World!'
 Double-Quoted Strings:
s2 = "Python is awesome!"
 Triple-Quoted Strings:
s3 = '''This is a
multi-line string
enclosed in triple single quotes.'''

s4 = """This is another
multi-line string
enclosed in triple double quotes."""
3. Boolean Literals
 True and False:
flag1 = True
flag2 = False
4. Special Literals
 None:
value = None # Represents the absence of a value or a null value
5. Container Literals
 Lists:
list_literal = [1, 2, 3, 'Python', 3.14]
 Tuples:
tuple_literal = (1, 2, 3, 'Python', 3.14)
 Sets:
set_literal = {1, 2, 3, 'Python', 3.14}
 Dictionaries:
dict_literal = {'name': 'Alice', 'age': 30, 'city': 'New York'}
6. Binary Literals
 Bytes:
bytes_literal = b'Hello, World!' # Bytes literal with binary data
 Constants:
 Defining Constants
Here’s how you can define and use constants in Python:
1. Defining Constants:
o You simply assign a value to a variable with an uppercase name. This naming convention is a
convention rather than a restriction enforced by the language.
PI = 3.14159
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 5
2. Using Constants:
o You can use these constants throughout your code. Although Python won’t enforce immutability,
following naming conventions helps signal to other developers (and yourself) that these values
should not be changed.
def calculate_circumference(radius):
return 2 * PI * radius
def connect_to_server():
timeout = DEFAULT_TIMEOUT
# Code to connect to a server with a timeout
Examples
1. Mathematical Constants:
EULER_NUMBER = 2.71828 # Euler's number
GRAVITY = 9.81 # Acceleration due to gravity (m/s^2)
2. Configuration Constants:
API_KEY = '1234567890abcdef'
MAX_RETRIES = 5
BASE_URL = 'https://api.example.com'
3. Application Constants:
MAX_USERS = 5000
SYSTEM_NAME = 'MyApp'
LOG_LEVEL = 'DEBUG'
 Enforcing Constants
While Python does not enforce immutability for constants, you can use some techniques to make it
harder to accidentally modify them:
1. Using a Named Tuple:
o A named tuple is immutable and can be used to group related constants.
from collections import namedtuple
Constants = namedtuple('Constants', ['PI', 'MAX_CONNECTIONS', 'DEFAULT_TIMEOUT'])
CONST = Constants(PI=3.14159, MAX_CONNECTIONS=100, DEFAULT_TIMEOUT=5)
# Accessing constants
print(CONST.PI)
2. Using a Class with Read-Only Properties:
You can create a class with properties that only have getter methods and no setter methods
class Constants:
PI = 3.14159
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 5
# Accessing constants
print(Constants.PI)
3. Using an Immutable Mapping:
o For dictionary-like constants, you can use types.MappingProxyType from the types module to
create a read-only dictionary.
from types import MappingProxyType
CONSTANTS = MappingProxyType({
'PI': 3.14159,
'MAX_CONNECTIONS': 100,
'DEFAULT_TIMEOUT': 5
})
 Variables:
Defining Variables
You define a variable in Python by assigning a value to a name using the assignment operator (=). The syntax is
straightforward:

variable_name = value

Basic Variable Types and Examples


1. Integer Variables:
age = 30
year = 2024
2. Floating-Point Variables:
temperature = 98.6
pi = 3.14159
3. String Variables:
name = "Alice"
greeting = 'Hello, World!'
multiline_text = """This is a
multi-line string."""
4. Boolean Variables:
is_sunny = True
is_raining = False
5. List Variables:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
6. Tuple Variables:
coordinates = (10.0, 20.0)
person = ("Alice", 30, "Engineer")
7. Dictionary Variables:
student = {"name": "John", "age": 21, "major": "Computer Science"}
8. Set Variables:
unique _numbers = {1, 2, 3, 4, 5}
colors = {"red", "green", "blue"}
 Variable Naming Rules
1. Names can include letters, numbers, and underscores but must start with a letter or underscore.
valid_variable_1 = 10
_valid_variable = 20
variable2 = 30
2. Names cannot start with a number and should not be reserved keywords (like if, else, for).
3. Names should be descriptive to make code more readable. For example:
total_price = 100.50
number_of_items = 5
Reassigning Variables
Variables in Python are mutable; you can change their values after they have been defined.
counter = 1
counter = counter + 1 # Now counter is 2
Examples in Context
1. Basic Arithmetic Operations:
a = 10
b=5
sum_result = a + b # 15
difference = a - b #5
product = a * b # 50
quotient = a / b # 2.0
2. String Concatenation:
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name
3. Using Variables in Functions:
python
Copy code
def greet(name):
message = "Hello, " + name
return message

print(greet("Alice")) # Output: Hello, Alice


4. Updating Variables in a Loop:
total = 0
for i in range(5):
total += i
print(total) # Output: 10 (0 + 1 + 2 + 3 + 4)

 Identifiers:
In Python, an identifier is a name used to identify a variable, function, class, module, or other object.
Identifiers follow certain rules and conventions, and understanding these helps in writing clear and maintainable
code.
 Rules for Identifiers
1. Characters: Identifiers can include letters (a-z, A-Z), digits (0-9), and underscores (_).
2. Starting Character: An identifier must start with a letter or an underscore; it cannot start with a digit.
3. Case Sensitivity: Identifiers are case-sensitive. For example, Variable and variable are considered
different identifiers.
4. No Reserved Keywords: Identifiers cannot be the same as Python reserved keywords (e.g., if, for,
while, class).
Examples of Valid Identifiers
 Single Word Identifiers:
age = 25
name = "Alice"
total_sum = 100.5
 Identifiers with Underscores:
max_value = 100
user_name = "John"
total_items = 50
 Camel Case Identifiers:
camelCaseExample = "Example"
numberOfItems = 20
 Snake Case Identifiers:
snake_case_example = "Example"
number_of_items = 20
 Identifiers with Leading Underscores:
_private_variable = "This is private"
__very_private_variable = "This is very private"
Examples of Invalid Identifiers
 Starting with a Digit:
1st_place = "Invalid" # Invalid identifier, cannot start with a digit
 Containing Special Characters:
my-variable = 10 # Invalid identifier, hyphen is not allowed
my@variable = 20 # Invalid identifier, @ is not allowed
 Using Reserved Keywords:
if = 100 # Invalid identifier, `if` is a reserved keyword
class = "Python" # Invalid identifier, `class` is a reserved keyword
 Identifiers in Context
1. Variable Identifiers:
user_age = 30
user_name = "Alice"
2. Function Identifiers:
def calculate_area(radius):
return 3.14 * radius * radius
3. Class Identifiers:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
4. Module Identifiers:
import math # 'math' is the name of the module
5. Constants (conventionally named in uppercase):
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 5

 Keywords:
Python has many keywords that are reserved words with special meanings and cannot be used as
identifiers (variable names, function names, etc.). Here are some of the most commonly used Python keywords,
along with examples:
1. False, True, None
is_active = True
is_inactive = False
result = None
2. and, or, not
a = True
b = False

if a and b:
print("Both are True")
if a or b:
print("At least one is True")
if not b:
print("b is False")
3. if, elif, else
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is 10")
else:
print("x is greater than 5 but not 10")
4. for, while, break, continue, in
for i in range(5):
if i == 3:
break
print(i)
i=0
while i < 5:
if i == 3:
i += 1
continue
print(i)
i += 1
5. def, return
def add(a, b):
return a + b
result = add(2, 3)
print(result)
6. class
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
my_dog = Dog("Fido")
my_dog.bark()
7. import, as, from
import math
from math import sqrt as square_root
print(math.pi)
print(square_root(16))
8. try, except, finally, raise
try:
x=1/0
except ZeroDivisionError as e:
print("Cannot divide by zero!", e)
finally:
print("This will always run")
9. with, as
with open('file.txt', 'w') as file:
file.write('Hello, World!')
10. lambda
add = lambda x, y: x + y
print(add(2, 3))
11. assert
x=5
assert x == 5, "x should be 5"
12. global, nonlocal
x = 10
def change_global():
global x
x=5
def outer_function():
y = 20
def inner_function():
nonlocal y
y = 25
inner_function()
print(y)
change_global()
print(x)
outer_function()
13. pass
def empty_function():
pass
14. yield
def generate_numbers():
for i in range(5):
yield i
for number in generate_numbers():
print(number)
 Built-inData Types:

Python has several built-in data types that are used to store various types of data. Here are the main
ones, along with examples:
1. Numeric Types
Integer
x = 10
print(type(x)) # <class 'int'>
Float
y = 10.5
print(type(y)) # <class 'float'>
Complex
z = 1 + 2j
print(type(z)) # <class 'complex'>
2. Sequence Types
String
s = "Hello, World!"
print(type(s)) # <class 'str'>
List
lst = [1, 2, 3, "four", 5.0]
print(type(lst)) # <class 'list'>
Tuple
t = (1, 2, 3, "four", 5.0)
print(type(t)) # <class 'tuple'>
3. Set Types
Set
s = {1, 2, 3, 4, 5}
print(type(s)) # <class 'set'>
Frozen Set
fs = frozenset([1, 2, 3, 4, 5])
print(type(fs)) # <class 'frozenset'>
4. Mapping Types
Dictionary
d = {"name": "Alice", "age": 30}
print(type(d)) # <class 'dict'>
5. Boolean Type
b = True
print(type(b)) # <class 'bool'>
6. Binary Types
Bytes
b = b"Hello"
print(type(b)) # <class 'bytes'>
Bytearray
ba = bytearray(b"Hello")
print(type(ba)) # <class 'bytearray'>
Memoryview
mv = memoryview(b"Hello")
print(type(mv)) # <class 'memoryview'>
7. None Type
n = None
print(type(n)) # <class 'NoneType'>
Examples of Usage
Numeric Types
a=5 # integer
b = 3.2 # float
c = 1 + 2j # complex number
print(a + b) # 8.2
print(c.real) # 1.0
print(c.imag) # 2.0
Sequence Types
# String
greeting = "Hello"
print(greeting[1]) # 'e'
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits) # ['apple', 'banana', 'cherry', 'date']
# Tuple
coordinates = (10, 20)
print(coordinates[0]) # 10
Set Types
# Set
unique_numbers = {1, 2, 3, 4, 5}
unique_numbers.add(6)
print(unique_numbers) # {1, 2, 3, 4, 5, 6}
# Frozenset
frozen_numbers = frozenset([1, 2, 3, 4, 5])
print(frozen_numbers) # frozenset({1, 2, 3, 4, 5})
Mapping Types
person = {"name": "John", "age": 30}
print(person["name"]) # John
Boolean Type
is_valid = True
print(is_valid) # True
Binary Types
# Bytes
b = b"Hello"
print(b[1]) # 101

# Bytearray
ba = bytearray(b"Hello")
ba[1] = 111
print(ba) # bytearray(b'Hollo')

# Memoryview
mv = memoryview(b"Hello")
print(mv[1]) # 101
 Output Statements:
Python has several built-in data types that are used to store various types of data. Here are the main
ones, along with examples:
1. Numeric Types
Integer
x = 10
print(type(x)) # <class 'int'>
Float
y = 10.5
print(type(y)) # <class 'float'>
Complex
z = 1 + 2j
print(type(z)) # <class 'complex'>
2. Sequence Types
String
s = "Hello, World!"
print(type(s)) # <class 'str'>
List
lst = [1, 2, 3, "four", 5.0]
print(type(lst)) # <class 'list'>
Tuple
t = (1, 2, 3, "four", 5.0)
print(type(t)) # <class 'tuple'>
3. Set Types
Set
s = {1, 2, 3, 4, 5}
print(type(s)) # <class 'set'>
Frozen Set
fs = frozenset([1, 2, 3, 4, 5])
print(type(fs)) # <class 'frozenset'>
4. Mapping Types
Dictionary
d = {"name": "Alice", "age": 30}
print(type(d)) # <class 'dict'>
5. Boolean Type
b = True
print(type(b)) # <class 'bool'>
6. Binary Types
Bytes
b = b"Hello"
print(type(b)) # <class 'bytes'>
Bytearray
ba = bytearray(b"Hello")
print(type(ba)) # <class 'bytearray'>
Memoryview
mv = memoryview(b"Hello")
print(type(mv)) # <class 'memoryview'>
7. None Type
n = None
print(type(n)) # <class 'NoneType'>
Examples of Usage
Numeric Types
a=5 # integer
b = 3.2 # float
c = 1 + 2j # complex number
print(a + b) # 8.2
print(c.real) # 1.0
print(c.imag) # 2.0
Sequence Types
# String
greeting = "Hello"
print(greeting[1]) # 'e'
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits) # ['apple', 'banana', 'cherry', 'date']
# Tuple
coordinates = (10, 20)
print(coordinates[0]) # 10
Set Types
# Set
unique_numbers = {1, 2, 3, 4, 5}
unique_numbers.add(6)
print(unique_numbers) # {1, 2, 3, 4, 5, 6}
# Frozenset
frozen_numbers = frozenset([1, 2, 3, 4, 5])
print(frozen_numbers) # frozenset({1, 2, 3, 4, 5})
Mapping Types
person = {"name": "John", "age": 30}
print(person["name"]) # John
Boolean Type
is_valid = True
print(is_valid) # True
Binary Types
# Bytes
b = b"Hello"
print(b[1]) # 101
# Bytearray
ba = bytearray(b"Hello")
ba[1] = 111
print(ba) # bytearray(b'Hollo')
# Memoryview
mv = memoryview(b"Hello")
print(mv[1]) # 101
Each of these data types serves specific purposes and is used in different scenarios in Python programming.
4o
 Output Statements in python with examples
In Python, output statements are primarily used to display information to the console or another output
stream. The most commonly used output statement is the print() function. Here are various examples of how to
use print() effectively:
Basic print() Usage
print("Hello, World!")
Output:
Copy code
Hello, World!
Printing Multiple Arguments
print("The sum of 5 and 3 is", 5 + 3)
Output:
The sum of 5 and 3 is 8
 Using String Formatting
f-Strings (Python 3.6+)
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Output:
Alice is 30 years old.
format() Method
name = "Alice"
age = 30
print("{} is {} years old.".format(name, age))
Output:
Alice is 30 years old.
Old-Style String Formatting
name = "Alice"
age = 30
print("%s is %d years old." % (name, age))
Output:
Alice is 30 years old.
Printing with Separator and End
Separator (sep)
print("apple", "banana", "cherry", sep=", ")
Output:
apple, banana, cherry
End (end)
print("This is the first line.", end=" ")
print("This is on the same line.")
Output:
This is the first line. This is on the same line.
 Printing Special Characters
Newline (\n)
print("Hello\nWorld")
Output:
Hello
World
Tab (\t)
print("Hello\tWorld")
Output:

Hello World

 Printing to a File
with open('output.txt', 'w') as file:
print("Hello, file!", file=file)
This will write "Hello, file!" to output.txt.
 Printing Objects
Lists
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
['apple', 'banana', 'cherry']
Dictionaries
person = {"name": "Alice", "age": 30}
print(person)
Output:
{'name': 'Alice', 'age': 30}
 Printing Raw Strings
print(r"C:\Users\name\folder")
Output:
C:\Users\name\folder
 Using the flush Parameter
import time
for i in range(3):
print(i, end=' ', flush=True)
time.sleep(1)
This will print each number immediately, rather than waiting until the buffer is full.
 Combining Different Techniques:
name = "Alice"
age = 30
hobbies = ["reading", "cycling"]
print(f"{name} is {age} years old and loves {', '.join(hobbies)}.")
Output:
Alice is 30 years old and loves reading, cycling.
These examples cover various ways to use the print() function in Python to display information effectively.
 Input Statements:
In Python, input statements are used to get input from the user. The primary function for taking input is
input(). Here are examples of how to use input() in different scenarios:
Basic Input
name = input("Enter your name: ")
print(f"Hello, {name}!")
Example interaction:
Enter your name: Alice
Hello, Alice!
 Input and Type Conversion
By default, input() returns the input as a string. To handle other data types, you need to convert the
input.
Integer Input
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
Example interaction:
Enter your age: 30
You are 30 years old.
Float Input
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters.")
Example interaction:
Enter your height in meters: 1.75
Your height is 1.75 meters.
 Handling Multiple Inputs
Using Split
You can use the split() method to take multiple inputs from a single line.
numbers = input("Enter three numbers separated by spaces: ").split()
a, b, c = map(int, numbers)
print(f"The numbers you entered are: {a}, {b}, {c}")
Example interaction:
Enter three numbers separated by spaces: 1 2 3
The numbers you entered are: 1, 2, 3
Prompting for Multiple Lines of Input
Using Loops
lines = []
print("Enter multiple lines of text (type 'stop' to finish):")
while True:
line = input()
if line.lower() == 'stop':
break
lines.append(line)
print("You entered:")
for line in lines:
print(line)
Example interaction:
Enter multiple lines of text (type 'stop' to finish):
Hello
World
stop
You entered:
Hello
World
 Advanced Input Handling
Error Handling
To handle invalid input gracefully, you can use try-except blocks.
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Invalid input. Please enter a valid number.")
print(f"You are {age} years old.")
Example interaction:
Enter your age: thirty
Invalid input. Please enter a valid number.
Enter your age: 30
You are 30 years old.
Example Program
Here's a simple example program that combines various input techniques.
def get_user_info():
name = input("Enter your name: ")
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Invalid input. Please enter a valid number.")

hobbies = input("Enter your hobbies, separated by commas: ").split(',')

print("\nUser Info:")
print(f"Name: {name}")
print(f"Age: {age}")
print("Hobbies:", ', '.join(hobby.strip() for hobby in hobbies))

get_user_info()
Example interaction:
Enter your name: Alice
Enter your age: twenty
Invalid input. Please enter a valid number.
Enter your age: 30
Enter your hobbies, separated by commas: reading, cycling, cooking

User Info:
Name: Alice
Age: 30
Hobbies: reading, cycling, cooking
These examples demonstrate how to use the input() function in Python to gather user input effectively, handle
different data types, and manage multiple inputs.
 Comments:
In Python, comments are used to explain code, make it more readable, and prevent execution of specific
code lines during debugging. There are two types of comments: single-line comments and multi-line comments.
Single-Line Comments
Single-line comments begin with the hash character (#) and extend to the end of the line. They are often
used for short explanations or notes.
Example:
# This is a single-line comment
print("Hello, World!") # This prints Hello, World! to the console
Output:
Hello, World!
 Multi-Line Comments
Multi-line comments can be created using multiple single-line comments or by using triple quotes (''' or
"""). Triple-quoted comments are technically string literals that are not assigned to any variable, thus not
executed.
Example using multiple single-line comments:
# This is a multi-line comment
# using single-line comment syntax.
# It explains the following block of code.
print("Hello, World!") # Prints Hello, World!
Example using triple quotes:
"""
This is a multi-line comment.
It can span multiple lines.
It is often used for large explanations
or block comments.
"""
print("Hello, World!") # Prints Hello, World!
 Practical Usage of Comments
Documenting Code
def add(a, b):
# This function adds two numbers and returns the result.
return a + b
result = add(3, 4)
print(result) # Outputs: 7
Disabling Code
# print("This line is disabled and won't run.")
print("This line will run.")
Output:
This line will run.
Inline Comments
x = 10 # Initialize variable x with value 10
y = 20 # Initialize variable y with value 20
# Add x and y
z = x + y # z now holds the value 30
print(z) # Outputs: 30
 Using Comments for Documentation Strings (Docstrings)
Docstrings are a special kind of comment used to document modules, classes, and functions. They are
written using triple quotes and can be accessed via the __doc__ attribute.
Example:
def multiply(a, b):
"""
This function multiplies two numbers.
Parameters:
a (int, float): The first number.
b (int, float): The second number.
Returns:
int, float: The result of multiplying a and b.
"""
return a * b
print(multiply
Indentation is crucial in Python, as it defines the blocks of code. Unlike other programming languages
that use braces {} to define blocks of code, Python uses indentation. The standard practice is to use 4 spaces per
indentation level. Here's a detailed explanation with examples:
1. Basic Indentation in Functions
def greet(name):
print(f"Hello, {name}")
greet("Alice")
In this example, the print statement is indented to indicate that it belongs to the greet function.
2. Indentation in Conditional Statements
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
The print statements are indented to indicate they are part of the if and else blocks.
3. Indentation in Loops
for i in range(5):
print(f"Iteration {i}")
The print statement is indented to indicate it is part of the for loop.
4. Nested Indentation
x = 10
if x > 5:
print("x is greater than 5")
if x > 8:
print("x is also greater than 8")
else:
print("x is greater than 5 but not greater than 8")
else:
print("x is 5 or less")
Here, the nested if statement is further indented to indicate it is within the first if block.
5. Indentation in Functions and Loops
def check_even(numbers):
for number in numbers:
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
check_even([1, 2, 3, 4, 5])
The for loop and the if statement inside it are indented to indicate their hierarchical structure.
Common Mistakes and Errors
1. Inconsistent Indentation
def greet(name):
print(f"Hello, {name}") # 2 spaces
print("How are you?") # 4 spaces (Error)
Inconsistent use of spaces can cause an IndentationError.
2. Mixing Tabs and Spaces
def greet(name):
\tprint(f"Hello, {name}") # Tab
print("How are you?") # Spaces (Error)
Mixing tabs and spaces can cause an IndentationError. It's recommended to configure your editor to convert
tabs to spaces to avoid this issue.
Proper indentation ensures that the code structure is clear and that Python interprets the code correctly.

 Python Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
 Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.

Example:
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

 Python Operators

Operators are used to perform operations on variables and values.


In the example below, we use the + operator to add together two values:

Example

print(10 + 5)

Python divides the operators in the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Example Same As

= x=5 x=5
+= x += 3 x=x+3
-=
*= -= 33
x *= x=x* - 33
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


:= print(x := 3) x=3
print(x)

Python Comparison Operators


Comparison operators are used to compare two values:
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than x >= y


or equal to
<= Less than or x <= y
equal to
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:
Operator Description Example
is Returns True if both variables x is y
are the same object
is not Returns True if both variables x is not y
are not the same object
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in y
specified value is not present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two
bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off
Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated before
additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence at the top:
Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus,
and bitwise NOT
* / // % Multiplication, division,
floor division, and modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is Comparisons, identity, and
not in not in membership operators
not Logical NOT
and AND
or OR

Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other value.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
Python3
# Constant Expressions
x = 15 + 1.3
print(x)
Output:
16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and


sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators
in Python:
Operators Syntax Functioning
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer results after
all computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0

c = a + int(b)
print(c)
Output
25

4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5

c=a/b
print(c)
Output
2.6

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on


both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first,
and then compared as per relational operator and produce a boolean output in the end. These
expressions are also called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output:
True

6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to
as we know it is not correct, so it will return False. Studying logical expressions, we also come
across some logical operators which can be seen in logical expressions most often. Here are some
logical operators in Python:
Operator Syntax Functioning
It returns true if both P and Q are
and P and Q
true otherwise returns false
It returns true if at least one of P
or P or Q
and Q is true
It returns true if condition P is
not not P
false

Example:
P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q
T = not P

print(R)
print(S)
print(T)
Output
False
True
True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed
at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output:
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output:
22

 Python Type Conversion


In programming, type conversion is the process of converting data of one type to another.
For example: converting int data to str .
There are two types of type conversion in Python.
 Implicit Conversion - automatic type conversion
 Explicit Conversion - manual type conversion

 Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion.
Example 1: Converting integer to float
Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number
# display new value and resulting data type
print("Value:",new_number)
print("Data Type:",type(new_number))
Output

Value: 124.23
Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type respectively.
Then we added these two variables and stored the result in new_number .
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid the loss of
data.
 Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of
the objects.
Example 2: Addition of string and integer Using Explicit Conversion
num_string = '12'
num_integer = 23
print("Data type of num_string before Type Casting:",type(num_string))
# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output:
Data type of num_string before Type Casting: <class 'str'>
Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, we have created two variables: num_string and num_integer with str and int type
values respectively. Notice the code,
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int .

 Python Arrays
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
 Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to
import a library, like the NumPy library.
Arrays are used to store multiple values in one single variable:
Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]

 What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but
300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

 Access the Elements of an Array


You refer to an array element by referring to the index number.
Example
Get the value of the first array item:
x = cars[0]
Example
Modify the value of the first array item:
cars[0] = "Toyota"
 The Length of an Array
Use the len() method to return the length of an array (the number of elements in an array).
Example
Return the number of elements in the cars array:
x = len(cars)
Note: The length of an array is always one more than the highest array index.

 Looping Array Elements


You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)

 Adding Array Elements


You can use the append() method to add an element to an array.
Example:
Add one more element to the cars array:
 Removing Array Elements
You can use the pop() method to remove an element from the array.
Example
Delete the second element of the cars array:
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo")
Note: The list's remove() method only removes the first occurrence of the specified value.

 Array Methods:
Python has a set of built-in methods that you can use on lists/arrays.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
 Python List append() Method:
Definition and Usage:
The append() method appends an element to the end of the list.
Syntax:
list.append(elmnt)
Parameter Values:
Parameter Description
elmnt Required. An element of any type (string, number, object etc.)

Example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

Output:
['apple', 'banana', 'cherry', 'orange']

 Python List clear() Method:


Definition and Usage:
The clear() method removes all the elements from a list.
Syntax:
list.clear()
Parameter Values:
No parameters
Example:
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
Output:
[]

 Python List copy() Method:


Definition and Usage:
The copy() method returns a copy of the specified list.

Syntax:
list.copy()

Parameter Values:
No parameters

Example:
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)

Output:
['apple', 'banana', 'cherry']
 Python List count() Method:
Definition and Usage
The count() method returns the number of elements with the specified value.
Syntax:
list.count(value)
Parameter Values:
Parameter Description
value Required. Any type (string, number, list, tuple, etc.). The value to search
for.
Example:
fruits = ["apple", "banana", "cherry"]
x = fruits.count("cherry")
print(x)
Output:
1

 Python List extend() Method:


Definition and Usage
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
Syntax:
list.extend(iterable)
Parameter Values:
Parameter Description
iterable Required. Any iterable (list, set, tuple, etc.)
Example:
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
Output:
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

 Python List index() Method:


Definition and Usage:
The index() method returns the position at the first occurrence of the specified value.
Syntax:
list.index(elmnt)
Parameter Values:
Parameter Description
elmnt Required. Any type (string, number, list, etc.). The element to search for
Example:
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
Output:
2
 Python List insert() Method:
Definition and Usage
The insert() method inserts the specified value at the specified position.
Syntax:
list.insert(pos, elmnt)
Parameter Values
Parameter Description
pos Required. A number specifying in which position to insert the value
elmnt Required. An element of any type (string, number, object etc.)
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
Output:
['apple', 'orange', 'banana', 'cherry']

 Python List pop() Method:


Definition and Usage
The pop() method removes the element at the specified position.
Syntax:
list.pop(pos)
Parameter Values:
Parameter Description
pos Optional. A number specifying the position of the element you want to
remove, default value is -1, which returns the last item
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
Output:
['apple', 'cherry']

 Python List remove() Method:


Definition and Usage
The remove() method removes the first occurrence of the element with the specified value.
Syntax:
list.remove(elmnt)
Parameter Values:
Parameter Description
elmnt Required. Any type (string, number, list etc.) The element you want to
remove
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
Output:
['apple', 'cherry']
 Python List reverse() Method:
Definition and Usage:
The reverse() method reverses the sorting order of the elements.
Syntax:
list.reverse()
Parameter Values:
No parameters
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
Output:
['cherry', 'banana', 'apple']

 Python List sort() Method:


Definition and Usage:
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s).
Syntax:
list.sort(reverse=True|False, key=myFunc)
Parameter Values:
Parameter Description
reverse Optional. reverse=True will sort the list descending. Default is
reverse=False
key Optional. A function to specify the sorting criteria(s)
Example:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output:
['BMW', 'Ford', 'Volvo']

UNIT:II:
 Control Statements: Selection/Conditional Branching statements:
Control statements in Python allow the execution flow of a program to change based on conditions.
These are essential for decision-making in programming. Here's a breakdown of the selection/conditional
branching statements in Python:
1. if
2. if..else
3. Nested if
4. if-elif statements.
 if Statement
The if statement allows you to execute a block of code only if a specified condition is true.
Syntax:
if condition:
# block of code

Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5

 if-else Statement
The if-else statement provides an alternative path if the condition is false.
Syntax:
if condition:
# block of code if condition is true
else:
# block of code if condition is false
Example 1:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
x is not greater than 5
Example 2:
x=3
if x == 4:
print("Yes")
else:
print("No")
Output:
No

 Nested if Statement:
Nested if statements allow you to have an if statement inside another if statement, providing multiple
levels of conditions.
Syntax:
if condition1:
if condition2:
# block of code if both conditions are true

Example 1:
x = 10
y = 20

if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
Output:
x is greater than 5 and y is greater than 15

Example 2:

num = 10

if num > 5:

print("Bigger than 5")

if num <= 15:

print("Between 5 and 15")

Output:
Bigger than 5
Between 5 and 15

 if-elif-else Statement
The if-elif-else statement is used when you have multiple conditions to check. Only the first true
condition's block is executed.
Syntax:
if condition1:
# block of code if condition1 is true
elif condition2:
# block of code if condition2 is true
else:
# block of code if none of the above conditions are true
Example 1:
x = 10

if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but less than or equal to 15")
else:
print("x is 5 or less")
Output:
x is greater than 5 but less than or equal to 15
Example 2:
letter = "A"
if letter == "B":
print("letter is B")

elif letter == "C":


print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
Output:
letter is A

Summary:

 if Statement: Executes a block if a condition is true.


 if-else Statement: Executes one block if a condition is true, another if it is false.
 Nested if Statement: Allows if statements within another if.
 if-elif-else Statement: Checks multiple conditions, executing the block for the first true condition.
These control statements are fundamental to building logic in Python programs.

 Iterative Statements:
Iterative statements and jump statements are essential for controlling the flow of loops in Python. Here's
a breakdown of these concepts:
 while Loop
 for Loop
 else Suite in Loops
 Nested Loops
 while Loop

A while loop repeatedly executes a block of code as long as a specified condition is true.

Syntax:
while condition:
# block of code

Example:
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

 for Loop
A for loop iterates over a sequence (like a list, tuple, string, or range) and executes a block of code for
each item.
Syntax:
for item in sequence:
# block of code
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")

Output:
I like apple
I like banana
I like cherry

 else Suite in Loops


The else suite in loops executes a block of code after the loop completes normally (i.e., without hitting a
break statement).
Syntax:
for item in sequence:
# block of code
else:
# block of code after loop ends

while condition:
# block of code
else:
# block of code after loop ends
Example:
for number in range(1, 4):
print(number)
else:
print("Loop is complete.")
Output:
1
2
3
Loop is complete.

 Nested Loops
Nested loops are loops within loops. The inner loop runs to completion for each iteration of the outer
loop.
Syntax:
for item1 in sequence1:
for item2 in sequence2:
# block of code

Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

 Jump Statements:
 break Statement
 continue Statement
 pass Statement

1. break Statement

The break statement terminates the loop prematurely.


Syntax:
for item in sequence:
if condition:
break
Example:
for number in range(1, 10):
if number == 5:
break
print(number)
Output:
1
2
3
4

2. continue Statement

The continue statement skips the current iteration and proceeds to the next iteration of the loop.
Syntax:
for item in sequence:
if condition:
continue
# block of code
Example:
for number in range(1, 6):
if number == 3:
continue
print(number)
Output:
1
2
4
5
3. pass Statement

The pass statement is a null operation; it does nothing. It’s a placeholder for code that you may write
later.
Syntax:
for item in sequence:
if condition:
pass
# block of code

Example:
for number in range(1, 4):
if number == 2:
pass
print(number)
Output:
1
2
3

Summary
 while Loop: Repeats as long as the condition is true.
 for Loop: Iterates over a sequence.
 else Suite in Loops: Executes after the loop ends without a break.
 Nested Loops: A loop inside another loop.
 break Statement: Exits the loop prematurely.
 continue Statement: Skips the current iteration.
 pass Statement: Does nothing, acts as a placeholder.
These statements and concepts are fundamental to controlling the flow of loops in Python programs.
UNIT III

1. Function Definition

A function in Python is defined using the def keyword, followed by the function name,
parentheses (which may include parameters), and a colon. The code inside the function is
indented.

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

This function takes a single argument name and prints a greeting.

2. Function Call

A function call executes the code inside the function. You can call the function by using
its name followed by parentheses, passing in any required arguments.

greet("Alice") # Output: Hello, Alice!

3. Variable Scope and Lifetime

In Python, variable scope determines where a variable can be accessed. There are two
main types of scope:

 Local Scope: Variables defined inside a function are local to that function and cannot be
accessed outside it.
 Global Scope: Variables defined outside all functions are global and can be accessed
anywhere in the program.

x = 10 # Global variable

def show_local():
x = 5 # Local variable
print(f"Local x: {x}")

show_local() # Output: Local x: 5


print(f"Global x: {x}") # Output: Global x: 10

 Lifetime of Variables: The lifetime of a local variable is limited to the execution of the
function. Once the function finishes, the local variables are destroyed.

def demo_lifetime():
y = 20 # Local variable, exists only during the function's execution
print(f"y inside function: {y}")
demo_lifetime()
# The following will give an error, as y doesn't exist outside the function
# print(y)

4. Return Statement

The return statement is used to send back a result from a function to the caller. Once return is
executed, the function terminates.

def add(a, b):


return a + b

result = add(3, 4)
print(f"The sum is: {result}") # Output: The sum is: 7

The function add takes two parameters, computes their sum, and returns the result.

Putting It All Together:

def calculate_area(radius):
pi = 3.14159 # Local variable
area = pi * radius ** 2
return area

r=5
area_result = calculate_area(r) # Function call
print(f"Area of the circle: {area_result}") # Output: Area of the circle: 78.53975

Here, we define a function calculate_area, which calculates the area of a circle given its radius
and returns the result.

1. Required Arguments

These are the arguments that must be passed to the function in the correct order. If they are not
provided, Python will raise an error.

def greet(name, message):


print(f"{message}, {name}!")

greet("Alice", "Hello") # Output: Hello, Alice!


# greet("Alice") # This will raise an error: TypeError: greet() missing 1 required positional
argument

In this example, both name and message are required arguments.

2. Keyword Arguments
Keyword arguments allow you to pass arguments by explicitly naming the parameter in the
function call, which makes the order of arguments irrelevant.

def greet(name, message):


print(f"{message}, {name}!")

greet(message="Good morning", name="Bob") # Output: Good morning, Bob!

Here, we use keyword arguments to change the order of name and message.

3. Default Arguments

In Python, you can assign default values to function parameters. If the caller does not provide a
value for such arguments, the default is used.

def greet(name, message="Hello"):


print(f"{message}, {name}!")

greet("Alice") # Output: Hello, Alice!


greet("Bob", "Good evening") # Output: Good evening, Bob!

In this example, message has a default value of "Hello", so it is not necessary to pass it when
calling the function.

4. Variable-Length Arguments

There are two ways to define variable-length arguments:

 *args for non-keyword arguments


 **kwargs for keyword arguments

*args (Non-keyword Variable Arguments)

This allows a function to accept any number of positional arguments, which are collected as a
tuple.

def add_numbers(*args):
total = sum(args)
print(f"Sum: {total}")

add_numbers(1, 2, 3, 4) # Output: Sum: 10


add_numbers(5, 10) # Output: Sum: 15
**kwargs (Keyword Variable Arguments)

This allows a function to accept any number of keyword arguments, which are collected as a
dictionary.

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

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


# Output:
# name: Alice
# age: 25
# city: New York

5. Recursion

Recursion is a process where a function calls itself. It is typically used for problems that can be
broken down into similar subproblems. However, recursion requires a base case to stop the
function from calling itself indefinitely.

Example: Factorial Calculation

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

print(factorial(5)) # Output: 120

In this example, the factorial function calls itself until it reaches the base case (n == 1). The
recursive calls continue until the final result is computed. The factorial of 5 is calculated as:

factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 (base case)

Putting It All Together:

def person_info(name, age, *hobbies, city="Unknown", **other_info):


print(f"Name: {name}")
print(f"Age: {age}")
print(f"Hobbies: {', '.join(hobbies)}")
print(f"City: {city}")
for key, value in other_info.items():
print(f"{key}: {value}")

person_info("Alice", 30, "Reading", "Traveling", city="Paris", profession="Engineer")


# Output:
# Name: Alice
# Age: 30
# Hobbies: Reading, Traveling
# City: Paris
# profession: Engineer

In this example, we use a combination of required, default, variable-length arguments (*args and
**kwargs).

Python Strings

A string in Python is a sequence of characters enclosed in either single, double, or triple quotes.
Strings are widely used for storing text, and they are immutable, meaning once a string is
created, it cannot be changed.

String Operations:

 Concatenation: You can join two or more strings using the + operator.

s1 = "Hello"
s2 = "World"
result = s1 + " " + s2 # Output: "Hello World"

 Repetition: Multiply a string by a number to repeat it.

result = "Hello" * 3 # Output: "HelloHelloHello"

 Slicing: Extracting a substring from a string using indices.

s = "Hello World"
result = s[0:5] # Output: "Hello"
result = s[-5:] # Output: "World"

 Membership Operator: Checking if a substring exists using in.

result = "Hello" in "Hello World" # Output: True


Immutable Strings:

Strings in Python are immutable, meaning their contents cannot be changed after creation. Any
operation that seems to modify a string will return a new string instead.

Example:

s = "Hello"
s[0] = "h" # This will raise an error because strings are immutable.

To "change" a string, you can create a new one:

s = "Hello"
new_s = "h" + s[1:] # Output: "hello"

Built-in String Methods and Functions:

 len(): Returns the length of the string.

len("Hello") # Output: 5

 str(): Converts an object to a string.

str(123) # Output: "123"

 upper(): Converts all characters to uppercase.

"hello".upper() # Output: "HELLO"

 lower(): Converts all characters to lowercase.

"HELLO".lower() # Output: "hello"

 capitalize(): Capitalizes the first character.

"hello world".capitalize() # Output: "Hello world"

 find(sub): Finds the first occurrence of a substring.

"hello world".find("world") # Output: 6

 replace(old, new): Replaces a substring with another.

"hello world".replace("world", "Python") # Output: "hello Python"

 split(sep): Splits the string into a list of substrings based on a separator.


"apple,banana,grape".split(",") # Output: ['apple', 'banana', 'grape']

 join(iterable): Joins elements of an iterable into a string.

",".join(["apple", "banana", "grape"]) # Output: "apple,banana,grape"

String Comparison:

String comparison is done lexicographically in Python, meaning the ASCII values of characters
are compared.

 Equality (==):

"apple" == "apple" # Output: True


"apple" == "banana" # Output: False

 Inequality (!=):

"apple" != "banana" # Output: True

 Greater Than/Less Than (>, <):

"apple" > "banana" # Output: False


"apple" < "banana" # Output: True

Example of String Comparison:


str1 = "apple"
str2 = "banana"

if str1 < str2:


print(f"{str1} comes before {str2}")
else:
print(f"{str2} comes before {str1}")

# Output: "apple comes before banana"

Summary:

1. String operations allow manipulation through concatenation, repetition, slicing, and


membership checks.
2. Immutable Strings mean that strings can't be changed in place.
3. Built-in Methods such as upper(), split(), and replace() offer powerful ways to work with
strings.
4. String Comparison is based on lexicographical order and can be done using comparison
operators like ==, !=, <, and >.
Python Modules

A module in Python is a file containing Python definitions and statements. It allows you to
logically organize your Python code by breaking it down into smaller, manageable, reusable
pieces. These modules can define functions, classes, and variables and can also include runnable
code.

1. import Statement

The import statement is used to bring in a module or specific attributes from a module into your
current program.

Example:
# Importing an entire module
import math

# Using a function from the math module


result = math.sqrt(16)
print(result) # Output: 4.0

# Importing specific functions from a module


from math import pi, sqrt

print(pi) # Output: 3.141592653589793


print(sqrt(25)) # Output: 5.0

# Importing a module with an alias


import math as m

print(m.factorial(5)) # Output: 120

2. dir() Function

The dir() function returns a sorted list of the names defined in a module. Without arguments, it
returns the list of names in the current local scope.

Example:
import math

# Listing all attributes and functions in the math module


print(dir(math))

# Listing all names in the current local scope


print(dir())

3. Modules and Namespace


 Namespace refers to the mapping of names to objects. In Python, the namespace can be
classified into three types:
o Global Namespace: Names defined at the level of the main program.
o Local Namespace: Names defined inside a function or method.
o Built-in Namespace: Names predefined in the built-in Python libraries.

When you import a module, the names defined in the module's namespace can be accessed.

Example:
x = 10 # Global namespace

def func():
y = 20 # Local namespace
print(y)

func()

print(x) # Accessing global variable


# print(y) # This would cause an error as y is local to the function

4. Defining Our Own Modules

To create your own module, simply create a Python file with functions, classes, and variables.
You can then import and use this module in other scripts.

Steps to Create a Custom Module:

1. Create a Python file, for example, mymodule.py:

# mymodule.py

def greet(name):
return f"Hello, {name}!"

def add(a, b):


return a + b

2. Importing the custom module in another script:

# main.py

# Importing the custom module


import mymodule

# Using functions from the module


message = mymodule.greet("Alice")
print(message) # Output: Hello, Alice!

result = mymodule.add(10, 5)
print(result) # Output: 15

You can also import specific functions or classes from your custom module like this:

from mymodule import greet

message = greet("Bob")
print(message) # Output: Hello, Bob!

Conclusion

 Python modules help you organize code into reusable parts.


 The import statement loads modules into the program.
 The dir() function lists the names defined in a module or current scope.
 Python has a hierarchical namespace structure to manage variable scope.
 You can create your own modules to break your code into modular pieces and reuse them
easily.

1. Creating a List in Python

In Python, lists are created by placing elements inside square brackets [], separated by
commas. Lists can contain elements of different data types.

# Example: Creating a list


my_list = [1, 2, 3, 'Python', 5.5]
print(my_list) # Output: [1, 2, 3, 'Python', 5.5]

2. Accessing Values in a List

You can access values using indexing. Python uses zero-based indexing, so the first element has
an index of 0.

# Example: Accessing list elements


my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 50 (negative indexing starts from the end)

3. Updating Values in a List

Lists are mutable, meaning you can change their values by assigning new values at specific
positions.

# Example: Updating list elements


my_list = [10, 20, 30, 40]
my_list[2] = 35 # Updating the 3rd element
print(my_list) # Output: [10, 20, 35, 40]

4. Nested Lists

Lists can contain other lists as elements, creating a nested structure.

# Example: Nested list


nested_list = [[1, 2, 3], ['a', 'b', 'c'], [True, False]]
print(nested_list[0]) # Output: [1, 2, 3]
print(nested_list[1][2]) # Output: 'c'

5. Basic List Operations

Here are some basic operations you can perform on lists:

 Concatenation: Combine two lists using the + operator.


 Repetition: Repeat elements of a list using the * operator.
 Membership: Check if an element is present in a list using the in operator.

# Example: Basic list operations


list1 = [1, 2, 3]
list2 = ['a', 'b']

# Concatenation
print(list1 + list2) # Output: [1, 2, 3, 'a', 'b']

# Repetition
print(list1 * 2) # Output: [1, 2, 3, 1, 2, 3]

# Membership
print(2 in list1) # Output: True
print('z' in list2) # Output: False

6. List Methods

Python lists come with a variety of built-in methods for common tasks. Here are some important
list methods:

Method Description Example


append() Adds an item to the end of the list my_list.append(5)
extend() Adds all items of another list to the end my_list.extend([6, 7])
insert() Inserts an item at a given position my_list.insert(2, 'new')
remove() Removes the first item that matches the value my_list.remove('Python')
Method Description Example
pop() Removes and returns the item at the given index my_list.pop(0)
clear() Removes all elements from the list my_list.clear()
index() Returns the index of the first matched item my_list.index('Python')
count() Returns the number of occurrences of a given value my_list.count(2)
sort() Sorts the list in ascending order my_list.sort()
reverse() Reverses the order of the list my_list.reverse()

# Example: Using list methods


my_list = [10, 20, 30, 40, 50]

# Append an element
my_list.append(60)
print(my_list) # Output: [10, 20, 30, 40, 50, 60]

# Insert an element at index 1


my_list.insert(1, 15)
print(my_list) # Output: [10, 15, 20, 30, 40, 50, 60]

# Remove an element
my_list.remove(30)
print(my_list) # Output: [10, 15, 20, 40, 50, 60]

# Pop an element
popped_item = my_list.pop()
print(popped_item) # Output: 60
print(my_list) # Output: [10, 15, 20, 40, 50]

# Sort the list


my_list.sort()
print(my_list) # Output: [10, 15, 20, 40, 50]

# Reverse the list


my_list.reverse()
print(my_list) # Output: [50, 40, 20, 15, 10]

7. Conclusion

Python lists are versatile and powerful, allowing you to perform a wide range of operations. With
methods like append(), remove(), sort(), and more, they are a fundamental tool in Python
programming.
UNIT : IV

QLists in Python

In Python, a list is a built-in data structure that allows you to store multiple
items in a single variable. Lists are ordered, mutable, and allow duplicate elements.
You can store different data types like integers, strings, and even other lists inside a
list.

Let’s go through each of the topics you mentioned with explanations and
example programs.

1. Creating a List

Lists in Python are created by placing all the elements (items) inside square
brackets [ ], separated by commas.

Example:

# Creating a list
my_list = [10, 20, 30, 40, 50]print("List:", my_list)

Output:

List: [10, 20, 30, 40, 50]

2. Accessing Values in a List

You can access the values in a list by referring to their index. Indexing starts
from 0 in Python.

Example:

my_list = [10, 20, 30, 40, 50]print("First element:", my_list[0])print("Third element:",


my_list[2])

Output:

First element: 10Third element: 30

You can also use negative indexing to access elements from the end of the list.

print("Last element:", my_list[-1])

Output:

Last element: 50
3. Updating Values in a List

Since lists are mutable, you can change the elements in a list by assigning new values
to a particular index.

Example:

my_list = [10, 20, 30, 40, 50]print("Original List:", my_list)


# Updating the second element
my_list[1] = 25print("Updated List:", my_list)

Output:

Original List: [10, 20, 30, 40, 50]Updated List: [10, 25, 30, 40, 50]

4. Nested Lists

A list inside another list is called a nested list. You can access nested list
elements using multiple indexes.

Example:

# Creating a nested list


nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements from nested listsprint("First list:", nested_list[0])print("Element
from second list:", nested_list[1][1])

Output:

First list: [1, 2, 3]


Element from second list: 5

5. Basic List Operations

Here are some common list operations:

 Concatenation (+): Join two lists.


 Repetition (*): Repeat the list elements.
 Membership (in): Check if an element is in the list.
 Length (len()): Find the length of the list.

Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenationprint("Concatenated List:", list1 + list2)
# Repetitionprint("Repetition of List1:", list1 * 2)
# Membershipprint("Is 3 in list1?", 3 in list1)
# Length of list1print("Length of list1:", len(list1))

Output:

Concatenated List: [1, 2, 3, 4, 5, 6]Repetition of List1: [1, 2, 3, 1, 2, 3]Is 3 in list1?


TrueLength of list1: 3

6. List Methods

Python provides several built-in list methods that perform different operations on the
list. Some of the commonly used methods are:

1. append(): Adds an element at the end of the list.


2. insert(): Adds an element at a specific position.
3. remove(): Removes a specified element.
4. pop(): Removes the element at a specific index (or the last element if no index
is specified).
5. sort(): Sorts the list.
6. reverse(): Reverses the order of elements in the list.

Example:

my_list = [3, 1, 4, 2]
# Append 5 to the list
my_list.append(5)print("After appending:", my_list)
# Insert 0 at index 1
my_list.insert(1, 0)print("After inserting:", my_list)
# Remove the element 4
my_list.remove(4)print("After removing 4:", my_list)
# Pop the last element
my_list.pop()print("After popping:", my_list)
# Sort the list
my_list.sort()print("After sorting:", my_list)
# Reverse the list
my_list.reverse()print("After reversing:", my_list)

Output:

After appending: [3, 1, 4, 2, 5]After inserting: [3, 0, 1, 4, 2, 5]After removing 4: [3, 0,


1, 2, 5]After popping: [3, 0, 1, 2]After sorting: [0, 1, 2, 3]After reversing: [3, 2, 1, 0]

Tuples in Python
A tuple is a collection of ordered, immutable (unchangeable) elements. Tuples
are similar to lists but with a key difference: once a tuple is created, its elements
cannot be modified. Tuples are used to group related data.

Creating a Tuple

A tuple is created by placing items inside parentheses (), separated by commas.

# Creating a tuple
my_tuple = (1, 2, 3, "apple", "banana")print(my_tuple)

Output:

(1, 2, 3, 'apple', 'banana')

You can also create an empty tuple or a single-element tuple:

# Empty tuple
empty_tuple = ()
# Single-element tuple (note the comma)
single_tuple = (5,)print(single_tuple)

Accessing Elements in a Tuple

You can access elements of a tuple using indexing, where the index starts at 0.

# Accessing elements in a tupleprint(my_tuple[0]) # Output: 1print(my_tuple[3]) #


Output: 'apple'

Updating a Tuple

Tuples are immutable, meaning elements cannot be modified once they are assigned.
However, you can concatenate two tuples or create a new tuple by adding elements.

# Updating a tuple by creating a new one


new_tuple = my_tuple + (6, 7)print(new_tuple)

Output:

(1, 2, 3, 'apple', 'banana', 6, 7)

Deleting a Tuple

You cannot delete individual elements from a tuple, but you can delete the entire tuple
using the del keyword.

# Deleting a tupledel my_tuple# Now, trying to access it will cause an error#


print(my_tuple) # This will raise a NameError
Nested Tuples

Tuples can contain other tuples as elements, which creates nested tuples.

# Nested tuple
nested_tuple = (1, (2, 3, 4), (5, 6))print(nested_tuple)print(nested_tuple[1]) # Output:
(2, 3, 4)print(nested_tuple[1][2]) # Output: 4

Difference Between Lists and Tuples

Lists Tuples
Lists are mutable. Tuples are immutable.
Created using square brackets []. Created using parentheses ().
Elements can be changed, added, or Elements cannot be changed once
removed. assigned.
Lists have more built-in functions. Tuples are more memory-efficient.

Example Program Showing the Difference Between Lists and Tuples

# List example (mutable)


my_list = [1, 2, 3, "apple", "banana"]print("Original List:", my_list)
# Modifying the list
my_list[0] = 10
my_list.append("orange")print("Modified List:", my_list)
# Tuple example (immutable)
my_tuple = (1, 2, 3, "apple", "banana")print("Original Tuple:", my_tuple)
# Trying to modify the tuple will raise an error# Uncommenting the line below will
raise a TypeError# my_tuple[0] = 10

Output:

Original List: [1, 2, 3, 'apple', 'banana']Modified List: [10, 2, 3, 'apple', 'banana',


'orange']Original Tuple: (1, 2, 3, 'apple', 'banana')

Dictionaries in Python

A dictionary in Python is a collection of key-value pairs. Each key is unique,


and it is used to retrieve the corresponding value. The syntax for dictionaries is {}
where elements are defined as key: value pairs. Dictionaries are mutable, meaning
you can modify them after creation.

1. Creating a Dictionary

You can create a dictionary by enclosing key-value pairs inside curly braces {}. The
key-value pairs are separated by commas.

# Example of creating a dictionary


student = {
"name": "John",
"age": 21,
"major": "Computer Science"
}print(student)

Output:

{'name': 'John', 'age': 21, 'major': 'Computer Science'}

2. Accessing Dictionary Elements

You can access values in a dictionary by referencing the key inside square brackets []
or using the .get() method.

# Accessing elementsprint(student["name"]) # Output:


Johnprint(student.get("age")) # Output: 21

3. Updating a Dictionary

Dictionaries are mutable, meaning you can update or add new key-value pairs.

# Updating elements
student["age"] = 22 # Update existing value
student["graduation_year"] = 2024 # Add new key-value pairprint(student)

Output:

{'name': 'John', 'age': 22, 'major': 'Computer Science', 'graduation_year': 2024}

4. Deleting Elements from a Dictionary

You can remove elements from a dictionary using del keyword or the .pop() method.

 del will remove the key-value pair completely.


 .pop() removes the element and returns the value associated with the key.

python
Copy code
# Deleting elementsdel student["major"]
# Deletes the 'major' keygraduation_year = student.pop("graduation_year")
# Removes and returns 'graduation_year'print(student)print("Graduation Year:",
graduation_year)

Output:

{'name': 'John', 'age': 22}


Graduation Year: 2024
5. Dictionary Functions and Methods

Here are some common dictionary functions and methods:

 len(dictionary): Returns the number of key-value pairs.


 .keys(): Returns a list of all keys.
 .values(): Returns a list of all values.
 .items(): Returns a list of key-value tuples.
 .update(): Updates the dictionary with key-value pairs from another dictionary.

# Dictionary Methods Exampleprint(student.keys())


# Output: dict_keys(['name', 'age'])print(student.values())
# Output: dict_values(['John', 22])print(student.items())
# Output: dict_items([('name', 'John'), ('age', 22)])

6. Difference Between Lists and Dictionaries

 Lists are ordered collections of items, where the items are accessed by their
position (index).
 Dictionaries are unordered collections where data is stored in key-value pairs,
and elements are accessed by keys.

List Example:

# List example
fruits = ['apple', 'banana', 'cherry']print(fruits[1]) # Output: banana

Dictionary Example:

# Dictionary example
fruit_prices = {'apple': 100, 'banana': 50, 'cherry': 75}print(fruit_prices['banana']) #
Output: 50

Key Differences:

Feature List Dictionary


Access By index (e.g., list[0]) By key (e.g., dict['key'])
Order Ordered Unordered (since Python 3.7, ordered)
Duplicates Allows duplicate elements Keys must be unique
Mutability Mutable Mutable

Example Program with Output

# Example: List vs Dictionary


# List
fruits = ['apple', 'banana', 'cherry']print("List of fruits:", fruits)print("Accessing second
fruit:", fruits[1])
# Dictionary
fruit_prices = {'apple': 100, 'banana': 50, 'cherry': 75}print("\nDictionary of fruit
prices:", fruit_prices)print("Price of banana:", fruit_prices['banana'])
# Update Dictionary
fruit_prices['banana'] = 55print("\nUpdated price of banana:", fruit_prices['banana'])
# Adding new fruit to dictionary
fruit_prices['orange'] = 80print("Added new fruit:", fruit_prices)

Output:

List of fruits: ['apple', 'banana', 'cherry']Accessing second fruit: banana


Dictionary of fruit prices: {'apple': 100, 'banana': 50, 'cherry': 75}Price of banana: 50
Updated price of banana: 55Added new fruit: {'apple': 100, 'banana': 55, 'cherry': 75,
'orange': 80}

UNIT : V

Python File Handling

Python provides numerous built-in functions to work with files, enabling us to


perform a wide variety of file operations, such as reading, writing, and appending data.
File handling in Python is simple and efficient.

Types of Files in Python

1. Text Files:
1. Contain human-readable characters. Examples: .txt, .py, etc.
2. The default mode for reading and writing is text mode.
2. Binary Files:

1. Contain non-human-readable data. Examples: .jpg, .png, .exe, etc.


2. The binary mode is used for reading and writing binary files.

Opening and Closing Files

Files can be opened using the open() function, and closed using the close()
method.

Syntax:

file_object = open(filename, mode)


file_object.close()

 filename: Name of the file.


 mode: Specifies the purpose of opening the file:

o "r": Read (default mode).


o "w": Write (overwrites the file if it exists).
o "a": Append (adds data at the end of the file).
o "b": Binary mode.
o "t": Text mode (default mode).
o "x": Create a new file (fails if the file exists).

Example:

file = open("example.txt", "w") # Open for writing


file.write("Hello, World!") # Write to the file
file.close() # Close the file

Reading and Writing Files

write() Method

This method writes a string to the file.

Syntax:

file.write(string)

Example:

file = open("example.txt", "w")


file.write("This is a test.")
file.close()

writelines() Method

This method writes a list of strings to the file.

Syntax:

file.writelines(list_of_strings)

Example:

file = open("example.txt", "w")


file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
file.close()

append() Method

The append mode ("a") is used to add data to the end of the file without overwriting it.

Example:

file = open("example.txt", "a")


file.write("This will be appended.")
file.close()

read() Method

The read() method reads the contents of the file.

Syntax:

file.read([n])

 n: Number of bytes to read (optional). If not provided, it reads the entire file.

Example:

file = open("example.txt", "r")


content = file.read()print(content)
file.close()

readlines() Method

This method reads all lines from the file and returns them as a list of strings.

Example:

file = open("example.txt", "r")


lines = file.readlines()for line in lines:
print(line)
file.close()

The with Keyword

The with statement is used for file handling to ensure the file is automatically
closed after the block of code inside with is executed.

Example:

with open("example.txt", "r") as file:


content = file.read()
print(content)# No need to explicitly close the file

Splitting Words

To split words from the contents of a file:

Example:

with open("example.txt", "r") as file:


content = file.read()
words = content.split() # Split by whitespace
print(words)

File Methods

 file.tell(): Returns the current position of the file pointer.


 file.seek(offset): Moves the file pointer to the specified location.

Example:

with open("example.txt", "r") as file:


file.seek(10) # Move file pointer to 10th byte
content = file.read()
print(content)

Renaming and Deleting Files


The os module provides functions to rename and delete files.
Renaming a file:
import os
os.rename("old_name.txt", "new_name.txt")

Deleting a file:

import os
os.remove("filename.txt")

Example Program

import os
# Create and write to a filewith open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python file handling is easy.\n")
# Read and print the contentswith open("example.txt", "r") as file:
print("File contents before appending:")
print(file.read())
# Append to the filewith open("example.txt", "a") as file:
file.write("This is the appended line.\n")
# Read and print the updated file contentswith open("example.txt", "r") as file:
print("File contents after appending:")
print(file.read())
# Rename the file
os.rename("example.txt", "new_example.txt")
# Delete the renamed file
os.remove("new_example.txt")
Output:

File contents before appending:


Hello, World!
Python file handling is easy.
File contents after appending:
Hello, World!
Python file handling is easy.
This is the appended line.

This covers the basics of Python file handling, along with methods for reading,
writing, appending, and managing files.

You might also like