Programming in Python
Programming in Python
Unit-I
Introduction to Python Programming
Additional Points:
Python Basics: Entering Expressions into the Interactive Shell, The Integer, Floating-Point,
and String Data Types
Entering Expressions into the Interactive Shell:
The Integer Data Type ( int ):
The Floating-Point Data Type ( float ):
The String Data Type ( str ):
Additional Points:
String Concatenation
Concatenation:
String Replication
Replication:
Storing Values in Variables
Variables:
Dissecting Your Program
Understanding Your Program:
Flow Control
Boolean Values:
Comparison Operators:
Boolean Operators:
Mixing Boolean and Comparison Operators
Elements of Flow Control
Program Execution
Definition:
Steps in Program Execution:
Flow Control Statements
Types of Flow Control Statements:
Importing Modules
Ways to Import Modules:
Standard Library vs. Third-Party Modules:
Ending a Program Early with sys.exit()
Unit - II
Functions
Programming in Python 1
Syntax of defining a function with parameters:
Example 1: Function without Parameters
Example 2: Function with Parameters
Example 3: Function with Multiple Parameters
Example 4: Function with Default Parameters
Example 5: Function with Keyword Arguments
Example 6: Function with Variable Number of Arguments
Example 7: Function with Keyword Arguments and Variable Number of Arguments
Return Values and Return Statements
The None Value
Keyword Arguments
print() Function
Local and Global Scope
Local Scope:
Global Scope:
The global Statement
Exception Handling
try-except Blocks
Handling Specific Exceptions
Raising Exceptions
Custom Exception Classes
Exception Propagation
Handling Exceptions in File Operations
Lists
The List Data Type
Working with Lists
Accessing Elements:
Slicing:
List Methods:
Adding Elements:
Removing Elements:
Searching and Counting:
Sorting and Reversing:
Augmented Assignment Operators:
Dictionaries and Structuring Data: The Dictionary Data Type
Pretty Printing
Using Data Structures to Model Real-World Things
Real-World Application:
Programming in Python 2
Manipulating Strings
Working with Strings:
String Concatenation:
String Slicing:
Useful String Methods:
Unit-I
Introduction to Python Programming
Python is a high-level, interpreted programming language known for its simplicity
and readability. It was created by Guido van Rossum and first released in 1991.
Python supports multiple programming paradigms, including procedural, object-
oriented, and functional programming. It has a large and comprehensive standard
library, making it suitable for various applications, including web development,
data analysis, artificial intelligence, and scientific computing.
1. Introduction to Python:
2. Installing Python:
3. Python Interpreter:
Programming in Python 3
Online platforms: Google Colab, Jupyter Online, etc.
6. Python Syntax:
Programming in Python 4
Additional Points:
Python Versions: Python has two major versions in use today: Python 2.x and
Python 3.x. Python 3.x is the current version and recommended for new
development due to its many improvements over Python 2.x.
Community and Resources: Python has a vast and active community with
abundant resources, including documentation, tutorials, forums, and libraries.
To launch the interactive shell, open the command prompt or terminal and
type python .
Once in the shell, you can enter expressions like mathematical operations ( + ,
, , / ), assignments ( = ), etc.
The interactive shell is a great way to experiment with Python syntax and test
small code snippets.
Programming in Python 5
The Integer Data Type ( int ):
Integers represent whole numbers without any fractional part.
Examples of integers: 5 , 10 , 0 .
Integers in Python can be of arbitrary size, allowing you to work with very
large numbers without overflow errors.
Python provides many operations and methods for working with strings,
including concatenation ( + ), slicing, indexing, and formatting.
Python also supports raw strings ( r'raw string' ) and multi-line strings
( '''multi-line string''' ).
Example:
Programming in Python 6
# Integer
x = 5
print(x) # Output: 5
print(type(x)) # Output: <class 'int'>
# Floating-point
y = 3.14
print(y) # Output: 3.14
print(type(y)) # Output: <class 'float'>
# String
s = 'hello'
print(s) # Output: hello
print(type(s)) # Output: <class 'str'>
Additional Points:
Python supports other numeric types such as complex numbers ( complex ) for
working with complex arithmetic.
String literals can also be enclosed within triple quotes ( ''' or """ ) to create
multi-line strings.
Understanding these fundamental data types is crucial for building more complex
Python programs and applications. They form the building blocks upon which
more advanced concepts and techniques are built.
String Concatenation
Concatenation:
Programming in Python 7
Definition: Concatenation is the process of combining two or more strings into
a single string.
Example:
str1 = "Hello"
str2 = "World"
result_concatenation = str1 + str2
print("Concatenation:", result_concatenation) # Output: H
elloWorld
String Replication
Replication:
Definition: Replication is the process of repeating a string multiple times.
Example:
str1 = "Python"
result_replication = str1 * 3
print("Replication:", result_replication) # Output: P
ythonPythonPython
Programming in Python 8
Definition: Variables are named containers used to store data in memory.
Example:
x = 10
name = "John"
print("Value of x:", x) # Output: 10
print("Value of name:", name) # Output: John
Example:
Programming in Python 9
Flow Control
Boolean Values:
Definition: Boolean values represent truth values - True or False .
Example:
is_student = True
is_working = False
print("Is student?", is_student) # Output: True
print("Is working?", is_working) # Output: False
Boolean values are fundamental in Python for making decisions and controlling
the flow of execution in programs.
Comparison Operators:
Definition: Comparison operators are used to compare values and return a
Boolean result.
Examples:
x = 10
y = 20
print("x == y:", x == y) # Output: False (Equal)
print("x != y:", x != y) # Output: True (Not Equal)
print("x < y:", x < y) # Output: True (Less Than)
print("x > y:", x > y) # Output: False (Greater Than)
print("x <= y:", x <= y) # Output: True (Less Than or Equ
al)
print("x >= y:", x >= y) # Output: False (Greater Than or
Equal)
Comparison operators allow you to compare values and make decisions based on
the results in your Python programs.
Programming in Python 10
Boolean Operators:
Definition: Boolean operators ( and , or , not ) are used to combine or
manipulate Boolean values.
Examples:
a = True
b = False
print("a and b:", a and b) # Output: False (Logical AND)
print("a or b:", a or b) # Output: True (Logical OR)
print("not a:", not a) # Output: False (Logical NOT)
Boolean operators are crucial for combining multiple conditions and controlling
the flow of execution based on Boolean expressions in Python programs.
Understanding boolean values, comparison operators, and boolean operators is
essential for building logical and efficient flow control mechanisms in Python
programs.
num = 12
is_even_and_greater_than_10 = (num % 2 == 0) and (num > 10)
print("Is num even and greater than 10?", is_even_and_greater
_than_10) # Output: True
In this example, we use the modulus operator % to check if the number is even
( num % 2 == 0 ) and the greater than operator > to check if the number is greater
than 10. We combine these conditions using the logical and operator to determine
if the number satisfies both conditions simultaneously.
Example 2: Checking if a Number is Odd or Less than 5
num = 3
is_odd_or_less_than_5 = (num % 2 != 0) or (num < 5)
Programming in Python 11
print("Is num odd or less than 5?", is_odd_or_less_than_5) #
Output: True
Here, we use the inequality operator != to check if the number is odd ( num % 2 !=
0 ) and the less than operator < to check if the number is less than 5. We combine
these conditions using the logical or operator to determine if the number satisfies
either of the conditions.
Example 3: Checking if a Number is not Equal to 0 and not Greater than 100
num = 75
not_equal_to_0_and_not_greater_than_100 = (num != 0) and not
(num > 100)
print("Is num not equal to 0 and not greater than 100?", not_
equal_to_0_and_not_greater_than_100) # Output: True
In this example, we first check if the number is not equal to 0 ( num != 0 ) and then
use the greater than operator > combined with the logical not operator to check
if the number is not greater than 100. We use the logical and operator to combine
these conditions to determine if the number satisfies both conditions
simultaneously.
Mixing boolean and comparison operators allows for more complex condition
checking in Python programs, enabling you to build robust and flexible logic for
controlling the flow of execution based on various conditions.
1. Sequence:
Example:
Programming in Python 12
print("Statement 1")
print("Statement 2")
print("Statement 3")
2. Selection:
Example:
x = 10
if x > 5:
print("x is greater than 5")
3. Iteration:
Description: Repeating code blocks using loops like while and for loops.
i = 0
while i < 5:
print(i)
i += 1
for i in range(5):
print(i)
4. Jump:
Description: Altering the flow of control using break, continue, and return
statements.
Example (break):
Programming in Python 13
for i in range(10):
if i == 5:
break
print(i)
Example (continue):
for i in range(10):
if i == 5:
continue
print(i)
Example (return):
result = add(5, 3)
print("Result:", result)
Program Execution
Definition:
Program execution refers to the process of running a program's code and
producing the desired output.
Description: The interpreter reads the source code and checks for syntax
errors.
Programming in Python 14
2. Compilation:
Description: The interpreter converts the source code into bytecode (for
Python).
3. Execution:
Example:
greet("John")
Example:
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
Programming in Python 15
else:
print("x is less than 5")
2. while:
Example:
i = 0
while i < 5:
print(i)
i += 1
3. for:
Example:
for i in range(5):
print(i)
4. break:
Example:
for i in range(10):
if i == 5:
break
print(i)
5. continue:
Programming in Python 16
Description: Skips the current iteration of the loop and continues with the
next iteration.
Example:
for i in range(10):
if i == 5:
continue
print(i)
6. pass:
Example:
x = 10
if x > 5:
pass # Placeholder for future code implementation
Importing Modules
In Python, modules are files containing Python code that can be imported and
used in other Python programs. Importing modules allows you to access
functions, classes, and variables defined in those modules.
Programming in Python 17
Syntax: import module_name
Example:
import math
print(math.sqrt(25)) # Output: 5.0
Example:
Example:
import math as m
print(m.sqrt(25)) # Output: 5.0
import datetime
current_date = datetime.datetime.now()
print("Current date and time:", current_date)
Programming in Python 18
import requests
response = requests.get("<https://www.example.com>")
print("Response status code:", response.status_code)
Importing modules allows you to leverage existing code and extend the
functionality of your Python programs by integrating additional features and
capabilities.
import sys
sys.exit(exit_code)
Example:
import sys
def validate_input(input_value):
if not input_value.isdigit():
print("Invalid input. Please enter a valid integer.")
sys.exit(1) # Exit with status code 1 (indicating er
ror)
Programming in Python 19
In this example, if the user enters a non-integer value, the program exits early with
a status code of 1 , indicating an error condition. This allows you to handle
exceptional cases gracefully and provide appropriate feedback to the user.
Using sys.exit() enables you to control the termination of your Python programs
effectively and handle various scenarios where premature termination is
necessary.
Unit - II
Functions
Functions in Python are blocks of reusable code that perform a specific task. They
allow you to break down your code into smaller, manageable parts and promote
code reuse and modularity. Parameters are variables that are passed to a function
to customize its behavior.
def greet():
print("Hello, World!")
Programming in Python 20
def greet(name):
print("Hello,", name)
def greet(name="Guest"):
print("Hello,", name)
Programming in Python 21
greet(message="Have a nice day.", name="Alice") # Output: He
llo, Alice! Have a nice day.
def calculate_sum(*args):
total = sum(args)
return total
def calculate_total(**kwargs):
total = sum(kwargs.values())
return total
Functions with parameters allow you to create flexible and reusable code that can
be customized to suit different needs by accepting inputs and producing outputs
based on those inputs.
Programming in Python 22
def function_name(parameter1, parameter2, ...):
# Function body
# Code to perform a specific task
return value
def absolute_value(x):
if x >= 0:
return x
else:
return -x
def greet(name):
print("Hello,", name)
Programming in Python 23
# Calling the function and storing the returned value
result = greet("John")
print("Result:", result) # Output: Result: None
x = None
print("Value of x:", x) # Output: Value of x: None
def greet(name):
print("Hello,", name)
my_list = [1, 2, 3, 4, 5]
result = find_element(my_list, 6)
if result is None:
print("Element not found.")
Programming in Python 24
else:
print("Element found:", result)
Understanding return values and the None value allows you to write functions that
can return meaningful results and handle cases where no value is returned or
when a value is explicitly set to None .
Keyword Arguments
Keyword arguments are arguments passed to a function using the parameter
names along with their corresponding values. This allows for more explicit and
readable function calls, especially when dealing with functions that have multiple
parameters.
Programming in Python 25
# Calling the function with keyword arguments
greet(message="Goodbye!", name="Alice") # Output: Hello, Ali
ce! Goodbye!
Using keyword arguments allows for clearer function calls and improves the
readability of your code, especially when dealing with functions that have many
parameters.
print() Function
The print() function in Python is used to display text or variables to the standard
output device, typically the console. It allows you to output strings, numbers,
variables, and expressions.
Syntax of the print() function:
file : File object where the output will be printed. Default is sys.stdout
(standard output).
Programming in Python 26
Example 1: Printing a String
x = 10
y = 20
print("x =", x, "and y =", y) # Output: x = 10 and y = 20
The print() function is a versatile tool for outputting information in Python, and
understanding its various parameters allows for more flexible and customized
output formatting.
Local Scope:
Programming in Python 27
Variables defined inside a function have local scope.
They can only be accessed within the function where they are defined.
Example:
def my_function():
local_var = 10
print(local_var) # Accessing local_var within the functi
on
my_function() # Output: 10
# print(local_var) # This will raise a NameError because loc
al_var is not defined outside the function
Global Scope:
Variables defined outside any function or in the global scope have global
scope.
They can be accessed and modified from anywhere in the program, including
inside functions.
Accessing a global variable inside a function does not require any special
declaration.
Example:
def my_function():
print(global_var) # Accessing global_var within the func
tion
my_function() # Output: 20
print(global_var) # Output: 20
Programming in Python 28
The global Statement
The global statement in Python is used to declare that a variable inside a function
is referring to a global variable defined outside the function. It allows you to
modify global variables from within functions.
Syntax:
global variable_name
Example:
x = 10 # Global variable
def my_function():
global x # Declare x as global within the function
x = 20 # Modify the global variable x
print("Inside the function:", x)
Without the global statement, modifying a variable inside a function creates a new
local variable with the same name, leaving the global variable unchanged.
Example without global statement:
x = 10 # Global variable
def my_function():
x = 20 # This creates a new local variable x
print("Inside the function:", x)
Programming in Python 29
Understanding local and global scope, as well as using the global statement when
necessary, is essential for writing modular and maintainable code in Python.
Exception Handling
Exception handling in Python allows you to gracefully manage and respond to
errors and exceptional situations that may occur during the execution of your
program. By handling exceptions, you can prevent your program from crashing
and provide meaningful error messages or alternative behaviors.
try-except Blocks
The primary mechanism for handling exceptions in Python is the try-except block.
Syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType1:
# Code to handle ExceptionType1
# ...
except ExceptionType2 as variable:
# Code to handle ExceptionType2
# Use variable to access information about the exception
# ...
except (ExceptionType3, ExceptionType4):
# Code to handle multiple exceptions
# ...
except:
# Code to handle any other exceptions
# ...
else:
# Code to execute if no exceptions occur in the try block
# ...
finally:
# Optional block of code that always executes, regardless
Programming in Python 30
of whether an exception occurred or not
# Useful for cleanup or resource releasing tasks
# ...
Example:
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print("Error:", e)
else:
print("Division successful.")
finally:
print("Cleanup code.")
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ValueError:
print("Invalid input. Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Raising Exceptions
You can use the raise statement to explicitly raise exceptions in your code.
x = -1
if x < 0:
Programming in Python 31
raise ValueError("x should be a non-negative number.")
class MyCustomError(Exception):
pass
try:
raise MyCustomError("This is a custom error message.")
except MyCustomError as e:
print("Custom error caught:", e)
Exception Propagation
If an exception is not caught within a function, it propagates up the call stack until
it is caught or the program terminates.
try:
with open("example.txt", "r") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("File not found.")
except IOError:
print("Error reading the file.")
Programming in Python 32
you can gracefully handle errors and ensure that your programs behave
predictably even in the face of unexpected situations.
Lists
In Python, a list is a versatile data structure that can store a collection of items.
Lists are mutable, meaning their elements can be changed after the list is created.
Lists are ordered, meaning the elements have a specific order, and they can
contain duplicate elements.
Lists in Python are defined using square brackets [ ] and can contain elements
separated by commas.
my_list = [1, 2, 3, 4, 5]
You can also access a subset of elements from a list using slicing.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
my_list.extend([5, 6, 7])
print(my_list) # Output: [1, 2, 3, 4, 5, 6, 7]
Programming in Python 33
my_list.insert(2, 8)
print(my_list) # Output: [1, 2, 8, 3, 4, 5, 6, 7]
my_list.remove(3)
print(my_list) # Output: [1, 2, 8, 4, 5, 6, 7]
popped_item = my_list.pop()
print(popped_item) # Output: 7
print(my_list) # Output: [1, 2, 8, 4, 5, 6]
print(my_list.index(4)) # Output: 3
print(my_list.count(5)) # Output: 1
my_list.sort()
print(my_list) # Output: [1, 2, 4, 5, 6, 8]
my_list.reverse()
print(my_list) # Output: [8, 6, 5, 4, 2, 1]
Lists are fundamental data structures in Python, widely used for storing and
manipulating collections of data. Understanding how to create, access, and
manipulate lists is essential for effective Python programming.
Programming in Python 34
Lists are defined using square brackets [ ] and can contain elements separated
by commas.
my_list = [1, 2, 3, 4, 5]
Accessing Elements:
You can access individual elements of a list using indexing. Python uses zero-
based indexing, where the first element has an index of 0, the second element has
an index of 1, and so on.
Slicing:
You can also access a subset of elements from a list using slicing.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
List Methods:
Python provides a variety of built-in methods for working with lists. These
methods allow you to manipulate the contents of a list in various ways.
Adding Elements:
append() : Adds an element to the end of the list.
Programming in Python 35
insert() : Inserts an element at a specified position.
Removing Elements:
remove() : Removes the first occurrence of a specified value.
pop() : Removes the element at the specified position and returns it.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
my_list.extend([5, 6, 7])
print(my_list) # Output: [1, 2, 3, 4, 5, 6, 7]
my_list.insert(2, 8)
print(my_list) # Output: [1, 2, 8, 3, 4, 5, 6, 7]
my_list.remove(3)
print(my_list) # Output: [1, 2, 8, 4, 5, 6, 7]
popped_item = my_list.pop()
print(popped_item) # Output: 7
print(my_list) # Output: [1, 2, 8, 4, 5, 6]
print(my_list.index(4)) # Output: 3
print(my_list.count(5)) # Output: 1
Programming in Python 36
my_list.sort()
print(my_list) # Output: [1, 2, 4, 5, 6, 8]
my_list.reverse()
print(my_list) # Output: [8, 6, 5, 4, 2, 1]
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
Subtraction:
x = 10
x -= 4 # Equivalent to x = x - 4
print(x) # Output: 6
Multiplication:
x = 3
x *= 2 # Equivalent to x = x * 2
print(x) # Output: 6
Programming in Python 37
Division:
x = 12
x /= 3 # Equivalent to x = x / 3
print(x) # Output: 4.0
Modulus:
x = 15
x %= 4 # Equivalent to x = x % 4
print(x) # Output: 3
Exponentiation:
x = 2
x **= 3 # Equivalent to x = x ** 3
print(x) # Output: 8
Floor Division:
x = 17
x //= 5 # Equivalent to x = x // 5
print(x) # Output: 3
Example of a Method:
append() Method:
The
append() method is used to add an element to the end of a list.
Programming in Python 38
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
pop() : Removes the element at the specified position and returns it.
Example:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort() # Sort the list in ascending order
print(my_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
Programming in Python 39
unique within one dictionary). Dictionaries are commonly used for representing
structured data, such as records, mappings, or configurations.
Definition:
A dictionary in Python is defined using curly braces {} and consists of key-value
pairs separated by commas. Each key is separated from its corresponding value
by a colon : .
Example:
Accessing Elements:
You can access the value associated with a specific key in a dictionary using
square bracket notation or the get() method.
Example:
print(my_dict.get("age")) # Output: 30
Programming in Python 40
print(my_dict) # Output: {'name': 'John', 'age': 35, 'city':
'New York', 'gender': 'Male'}
Removing Elements:
You can remove key-value pairs from a dictionary using the del keyword or the
pop() method.
Example:
Pretty Printing
Pretty printing in Python refers to formatting complex data structures, such as
dictionaries or lists, in a visually appealing and readable way. It helps improve the
readability of output for humans, especially when dealing with nested or large
data structures.
Python provides the pprint module (pretty print) for this purpose. The pprint
module offers a pprint() function that formats the output of data structures in a
more readable and structured manner compared to the standard print() function.
config = {
'server': {
Programming in Python 41
'host': 'localhost',
'port': 8080
},
'database': {
'name': 'mydb',
'user': 'admin',
'password': 'password123'
},
'debug': True
}
Printing this dictionary using the print() function may result in a less readable
output due to its nested structure:
print(config)
Output:
Using the pprint() function from the pprint module provides a more organized
and visually appealing output:
import pprint
pprint.pprint(config)
Output:
Programming in Python 42
As you can see, pprint() formats the dictionary with indentation and line breaks,
making it easier to read, especially for nested data structures.
Pretty printing is particularly useful when dealing with large or complex data
structures, such as configuration files, JSON data, or deeply nested dictionaries
and lists. It helps developers and users understand the structure of the data more
easily, leading to improved code readability and maintainability.
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
In this example:
Programming in Python 43
Each student object encapsulates data about a specific student, such as their
name, age, and grade.
Real-World Application:
In real-world applications, data structures are used to model various entities and
scenarios:
3. Social Media Networks: Modeling users and their relationships (e.g., friends,
followers) using graphs or dictionaries, with each user storing profile
information and connections to other users.
Manipulating Strings
Strings are fundamental data types in Python used to represent sequences of
characters. Python provides a rich set of built-in functions and methods for
manipulating strings, allowing developers to perform various operations such as
concatenation, slicing, searching, and formatting.
String Concatenation:
Programming in Python 44
Concatenation is the process of combining two or more strings into a single string.
Example:
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result) # Output: Hello, World
String Slicing:
Slicing allows you to extract a substring from a string by specifying a range of
indices.
Example:
Programming in Python 45
text = "Hello, World!"
print(text.lower()) # Output: hello, world!
print(text.upper()) # Output: HELLO, WORLD!
strip() :
Removes leading and trailing whitespace characters from the string.
Example:
split() :
Splits the string into a list of substrings based on a delimiter.
Example:
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'orange']
join() :
Concatenates elements of an iterable (e.g., list) into a single string, using the
specified separator.
Example:
find() : Searches for a substring within the string and returns its index. Returns
-1 if the substring is not found.
Programming in Python 46
replace() : Replaces occurrences of a substring with another substring.
Example:
Programming in Python 47