PYTHON PROGRAMMING. PDF
PYTHON PROGRAMMING. PDF
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
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.")
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
Example
print(10 + 5)
= 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
== Equal x == y
!= Not equal x != y
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
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
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
Value: 124.23
Data Type: <class 'float'>
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.
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']
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
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:
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")
Summary:
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
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
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}!")
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.
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}")
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.
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.
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.
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.
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.
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
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}")
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}")
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.
def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
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)
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"
s = "Hello World"
result = s[0:5] # Output: "Hello"
result = s[-5:] # Output: "World"
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.
s = "Hello"
new_s = "h" + s[1:] # Output: "hello"
len("Hello") # Output: 5
String Comparison:
String comparison is done lexicographically in Python, meaning the ASCII values of characters
are compared.
Equality (==):
Inequality (!=):
Summary:
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
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
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()
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.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
result = mymodule.add(10, 5)
print(result) # Output: 15
You can also import specific functions or classes from your custom module like this:
message = greet("Bob")
print(message) # Output: Hello, Bob!
Conclusion
In Python, lists are created by placing elements inside square brackets [], separated by
commas. Lists can contain elements of different data types.
You can access values using indexing. Python uses zero-based indexing, so the first element has
an index of 0.
Lists are mutable, meaning you can change their values by assigning new values at specific
positions.
4. Nested Lists
# 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:
# Append an element
my_list.append(60)
print(my_list) # Output: [10, 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]
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:
You can access the values in a list by referring to their index. Indexing starts
from 0 in Python.
Example:
Output:
You can also use negative indexing to access elements from the end of the list.
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:
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:
Output:
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:
6. List Methods
Python provides several built-in list methods that perform different operations on the
list. Some of the commonly used methods are:
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:
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
# Creating a tuple
my_tuple = (1, 2, 3, "apple", "banana")print(my_tuple)
Output:
# Empty tuple
empty_tuple = ()
# Single-element tuple (note the comma)
single_tuple = (5,)print(single_tuple)
You can access elements of a tuple using indexing, where the index starts at 0.
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.
Output:
Deleting a Tuple
You cannot delete individual elements from a tuple, but you can delete the entire tuple
using the del keyword.
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
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.
Output:
Dictionaries in Python
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.
Output:
You can access values in a dictionary by referencing the key inside square brackets []
or using the .get() method.
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:
You can remove elements from a dictionary using del keyword or the .pop() method.
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:
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:
Output:
UNIT : V
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:
Files can be opened using the open() function, and closed using the close()
method.
Syntax:
Example:
write() Method
Syntax:
file.write(string)
Example:
writelines() Method
Syntax:
file.writelines(list_of_strings)
Example:
append() Method
The append mode ("a") is used to add data to the end of the file without overwriting it.
Example:
read() Method
Syntax:
file.read([n])
n: Number of bytes to read (optional). If not provided, it reads the entire file.
Example:
readlines() Method
This method reads all lines from the file and returns them as a list of strings.
Example:
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:
Splitting Words
Example:
File Methods
Example:
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:
This covers the basics of Python file handling, along with methods for reading,
writing, appending, and managing files.