Python Notes (BCA_MCA_BTech)
Python Notes (BCA_MCA_BTech)
Python Notes (BCA_MCA_BTech)
● High-Level Language: Python is a high-level language, meaning it's closer to human language,
making it easier to learn and understand.
● Interpreted Language: Python code is executed line by line, making it more flexible and easier to
debug.
● Dynamic Typing: Python automatically determines the data type of variables at runtime, reducing the
9
need for explicit type declarations.
● Object-Oriented Programming (OOP): Python supports OOP principles like inheritance,
64
polymorphism, and encapsulation.
● Large Standard Library: Python comes with a vast standard library, providing modules for various
tasks, such as file I/O, network programming, and web development.
17
● Cross-Platform Compatibility: Python code can run on different operating systems (Windows,
macOS, Linux).
● Readability: Python's syntax is clean and easy to read, promoting code maintainability.
77
● Community and Support: Python has a large and active community, offering extensive
documentation, tutorials, and forums for support.
Installing Python
61
/8
1. Visit the official Python website (https://www.python.org/).
2. Download the latest version of Python for your operating system.
3. Run the installer and follow the on-screen instructions.
4. After installation, verify the installation by opening a terminal or command prompt and typing python. If
du
Interactive Shell
en
● You'll be in the interactive shell, where you can type Python code directly.
● The shell will execute each line of code immediately and display the result.
Su
Input: The input() function gets user input from the console.
name = input("Enter your name: ")
print("Hello, " + name)
9
Processing: Perform operations on the input data using Python's operators and functions.
num1 = int(input("Enter the first number: "))
64
num2 = int(input("Enter the second number: "))
result = num1 + num2
print("The sum is:", result)
17
Output: Use the print() function to display the results to the console.
77
message = "This is a message"
print(message)
Additional Functions
61
● id(): Returns the unique memory address of an object.
int(): Converts a value to an integer.
/8
●
● str(): Converts a value to a string.
● float(): Converts a value to a floating-point number.
du
PIP
en
● Purpose: A package manager for Python that simplifies the installation and management of third-party
packages.
● Functionality: Handles downloading, installing, and upgrading packages.
ry
● Usage:
○ pip install package_name: Installs a specific package.
○ pip list: Lists all installed packages.
Su
Packages
● Definition: A collection of Python modules and resources organized into a single unit.
● Purpose: Provides reusable code and functionality.
● Examples:
○ numpy: Numerical computing
○ pandas: Data analysis
○ matplotlib: Data visualization
Libraries
● Definition: A collection of related modules that provide specific functionality.
● Purpose: Offers specialized tools and functions.
● Examples:
○ requests: Making HTTP requests
○ Beautiful Soup: Parsing HTML and XML
○ scikit-learn: Machine learning
Frameworks
9
● Definition: A reusable software architecture that provides a foundation for building applications.
64
● Purpose: Offers pre-built components and conventions.
● Examples:
○ Django: Full-stack web framework
○ Flask: Lightweight web framework
17
○ TensorFlow: Deep learning framework
77
● PIP is used to install and manage packages, libraries, and frameworks.
● A package can contain multiple modules or libraries.
● A library is a collection of related modules within a package.
●
61
A framework provides a structure for building applications, often utilizing packages and libraries.
Debugging
ry
Syntax Errors
Su
Runtime Errors
Semantic Errors
● Errors occur when the code executes correctly but produces incorrect results.
● Logical errors in the algorithm or implementation.
● Can be difficult to detect and fix.
Debugging Techniques:
● Print Statements: Insert print() statements to check the values of variables at different points in the
code.
● Debugger: Use a debugger tool (e.g., Python's built-in debugger) to step through the code line by line
9
and inspect variables.
● Code Review: Carefully examine the code for logical errors and inconsistencies.
64
Operators
17
Arithmetic Operators
77
Arithmetic operators are used to perform mathematical calculations on numbers. Here are the common ones:
● Addition: + (e.g., 5 + 3) 61
● Subtraction: - (e.g., 8 - 2)
● Multiplication: * (e.g., 4 * 6)
● Division: / (e.g., 10 / 2)
/8
x = 10
y = 5
en
result = x + y # Addition
print("Addition:", result) # Output - ‘Addition: 15’
ry
result = x - y # Subtraction
print("Subtraction:", result) # Output - ‘Subtraction: 5’
Su
result = x * y # Multiplication
print("Multiplication:", result) # Output - ‘Multiplication: 50’
result = x / y # Division
print("Division:", result) # Output - ‘Division: 2.0’
result = x // y # Floor Division
print("Floor Division:", result) # Output - ‘Addition: 15’
result = x % y # Modulus
print("Modulus:", result) # Output - ‘Floor Division: 2’
result = x ** y # Exponentiation
print("Exponentiation:", result) # Output - ‘Exponentiation: 100000’
Comparison Operators
Comparison operators are used to compare two values and return a Boolean result (True or False).
9
● Greater than: > (e.g., 8 > 4)
● Less than: < (e.g., 2 < 6)
64
● Greater than or equal to: >= (e.g., 10 >= 10)
● Less than or equal to: <= (e.g., 7 <= 9)
● Syntax implementation through Python :
17
a = 15
b = 20
77
# Equal to
if a == b:
print("a is equal to b")
else:
61
print("a is not equal to b")
/8
# Not equal to
if a != b:
print("a is not equal to b")
else:
du
Assignment Operators
Assignment operators in Python assign values to variables. They are typically represented by the equal sign
(=). However, Python also provides augmented assignment operators that combine an arithmetic operation
9
with an assignment.
64
● =: Simple assignment
● +=: Add and assign
● -=: Subtract and assign
17
● *=: Multiply and assign
● /=: Divide and assign
● %=: Modulus and assign
77
● **=: Exponentiate and assign
● //=: Floor divide and assign
● Syntax implementation through Python :
61
x = 10 # Simple assignment
y = x
/8
print("y =", y)
y += 5 # Add and assign
print("y += 5:", y)
du
print("y *= 2:", y)
y /= 4 # Divide and assign
ry
print("y /= 4:", y)
y %= 3 # Modulus and assign
Su
print("y %= 3:", y)
y **= 2 # Exponentiate and assign
print("y **= 2:", y)
y //= 2 # Floor divide and assign
print("y //= 2:", y)
Logical Operators
a = True
b = False
9
result = a and b # Logical AND
64
print("a and b:", result)
result = a or b # Logical OR
print("a or b:", result)
17
result = not a # Logical NOT
print("not a:", result)
77
Bitwise Operators
Bitwise operators are operators that work at the individual bit level of integers. They perform operations on
61
each bit of the operands, rather than the entire number. In Python, there are several bitwise operators:
a = 10 # Binary: 1010
en
b = 5 # Binary: 0101
result = a & b # Bitwise AND (&)
print("Bitwise AND:", result) # Output: 2 (Binary: 0010)
ry
Membership Operators
Membership operators in Python are used to test if a value is present within a sequence (such as a list, tuple,
string, or dictionary). There are two membership operators:
9
my_list = [1, 2, 3, 4, 5]
64
my_string = "hello"
if 3 in my_list: # `in` operator
print("3 is in the list.")
17
else:
print("3 is not in the list.")
77
if "world" not in my_string: # `not in` operator
print("world is not in the string.")
61
else:
print("world is in the string.")
/8
Identity Operators
Identity operators in Python are used to compare the identity of two objects. They check if two variables refer
to the same object in memory. There are two identity operators:
du
x = 5
y = 5
ry
z = 6
if x is y: # Using the 'is' operator
Su
Order of operations:
1. Parentheses,
2. Exponents,
3. Multiplication and Division (from left to right),
4. Addition and Subtraction (from left to right).
Arithmetic Expressions
9
● Combinations of variables, constants, and operators to perform calculations.
64
● Examples:
○ x = 2 * (3 + 4)
○ result = (a + b) / c
17
Mixed-Mode Arithmetic and Type Conversion
77
● Python automatically converts operands to a common data type during arithmetic operations.
● The result type is usually wider (e.g., integer + float = float).
● Explicit type conversion functions: 61
○ int()
○ float()
○ str()
/8
Data Types
● Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
en
● Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive
or negative integer may be appended to specify scientific notation.
ry
a = 5
print("Type of a: ", type(a)) #Type of a: <class 'int'>
b = 5.0
print("\nType of b: ", type(b)) #Type of b: <class 'float'>
c = 2 + 4j
print("\nType of c: ", type(c)) #Type of c: <class 'complex'>
2. Boolean Data Type in Python
● Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class
bool.
● True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
● Example: The first two lines will print the type of the boolean values True and False, which is <class
‘bool’>. The third line will cause an error, because true is not a valid keyword in Python. Python is
9
case-sensitive, which means it distinguishes between uppercase and lowercase letters. You need to
capitalize the first letter of true to make it a boolean value.
64
print(type(True)) #<class 'bool'>
17
3. Sequence Data Types in Python
77
The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several sequence
data types of Python: 61
● Python String
● Python List
● Python Tuple
/8
● Python Dictionaries
Conditional Statements
du
1. If
● Syntax: if condition:
● Example:
2. If-Else
Su
● Executes one block of code if a condition is true, and another block if it's false.
● Syntax:
if condition:
# code to execute if the condition is true
else:
# code to execute if the condition is false
● Example:
x = 10
if x > 0:
print("x is positive.")
else:
print("x is negative or zero.")
9
3. If-Elif-Else
64
● Provides multiple conditions to check, executing the first true one.
● Syntax:
if condition1:
17
# code to execute if condition1 is true
elif condition2:
77
# code to execute if condition2 is true
else: 61
# code to execute if none of the conditions are true
● Example:
grade = 85
/8
print("B")
else:
en
print("C or below")
ry
4. Nested If-Else
● An if-else statement within another if-else statement.
Su
● Example:
if age > 18:
if weight > 45:
print("You are eligible for Blood donation")
else:
print("You are underweight, Not eligible")
else:
print("You are underage, Not eligible")
5. match-case Statement
● Purpose: Provides a concise and readable way to match a value against multiple patterns.
● The match-case statement is a powerful alternative to if-elif-else chains, especially for more
complex pattern-matching scenarios.
● Syntax:
match value:
9
case pattern1:
# Code to execute if the value matches pattern1
64
case pattern2:
# Code to execute if the value matches pattern2
17
case _:
# Default code to execute if no other pattern matches
77
● Example:
fruit = "apple" 61
match fruit:
case "apple":
/8
print("You like apples!")
case "banana":
print("You like bananas!")
du
case _:
print("I don't know what fruit you like.")
en
1. for Loop:
● Iterates over each element in an iterable (e.g., list, tuple, string, range).
Su
● The variable takes the value of the current element in each iteration.
● The code within the loop is executed for each element.
● Syntax: for variable in iterable:
● Example:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
2. for-else Loop:
● Similar to the for loop, but includes an else block.
● The else block is executed only if the loop completes without a break statement.
● Useful for tasks that need to be performed after the loop finishes successfully.
9
numbers = [1, 2, 3, 4, 5]
64
found = False
for number in numbers:
17
if number == 3:
found = True
77
break
if found:
print("Number 3 found!")
61
else:
print("Number 3 not found.")
/8
3. while Loop:
● Executes the code within the loop as long as the condition is True.
du
count = 0
en
count += 1
4. Nested Loops
● Nested loops occur when one loop is placed inside another loop. The inner loop runs entirely for each
iteration of the outer loop.
● The outer loop runs first, and for each iteration of the outer loop, the inner loop runs completely.
● Example:
for i in range(3):
for j in range(2):
print(i, j)
5. range() Function
9
●
● Syntax: range(start=0, stop, step=1)
64
○ start: The starting value (default is 0).
○ stop: The ending value (exclusive).
○ step: The step size (default is 1).
17
● Returns: A generator object that produces numbers in the specified range.
● Example:
77
print(number) # Output: 0 1 2 3 4
Functions
61
/8
● A function in Python is a block of reusable code that performs a specific task. Functions help to
organize code, make it more modular, and avoid repetition.
● Types of Functions:
1. Built-in Functions: Predefined in Python (e.g., print(), len()).
du
Built-in functions are functions that are pre-defined in the Python language and can be used directly without
needing to import any modules. They provide a variety of functionalities, from mathematical operations to string
manipulation and more.
9
64
Mathematical Functions
17
2. max(): Returns the maximum value in a sequence.
3. min(): Returns the minimum value in a sequence.
77
4. sum(): Calculates the sum of a sequence.
5. pow(): Calculates the power of a number.
61
6. round(): Rounds a number to a specified number of decimal places.
/8
Type Conversion Functions
Other Functions
Syntax:
9
return value # Optional: Returns a value
64
function_name (actual parameters) #function call
Components:
17
● def keyword: Indicates the start of a function definition.
● function_name: The name you choose for the function.
● parameters: Optional arguments that the function can accept.
77
● docstring: A triple-quoted string that provides a brief description of the function's purpose.
● function body: The code that the function will execute.
61
● return statement: Optionally returns a value from the function.
Example:
/8
def greet(name):
"""Greets the user with a personalized message."""
print("Hello, " + name + "!")
du
NOTES:
en
Formal Parameters
Su
● Definition: These are the variables listed within the function definition that represent the values the
function expects to receive.
● Purpose: They act as placeholders for the actual values that will be passed to the function when it's
called.
Actual Parameters
● Definition: These are the values that are passed to the function when it's called.
● Purpose: They are substituted for the formal parameters within the function's body.
Example:
In this example:
9
● name is the formal parameter.
● "Alice" is the actual parameter.
64
● When the function is called with greet("Alice"), the actual parameter "Alice" is assigned to the
formal parameter name within the function's body. The function then prints the greeting message using
the value of the name.
17
NOTES:
77
● The number of actual parameters must match the number of formal parameters in the function
definition.
● Actual parameters can be literals, variables, or expressions.
61
● Formal parameters can be used within the function's body to perform calculations or manipulate data.
Call by Value
/8
● Definition: In call by value, a copy of the actual parameter is passed to the function. Any modifications
made to the parameter within the function do not affect the original value outside the function.
● Behavior: When a function is called with call-by-value, the original value of the argument remains
unchanged after the function returns.
du
● Example:
def square(x):
en
x = x * x
return x
num = 5
ry
result = square(num)
print(num) # Output: 5
Su
print(result) # Output: 25
● Explanation: In this example, num is passed to the square function by value. The function modifies
the value of x within its scope, but it doesn't affect the original value of num.
Call by Reference
● Definition: In call-by reference, a reference to the actual parameter is passed to the function. Any
modifications made to the parameter within the function directly affect the original value outside the
function.
● Behavior: When a function is called with call-by reference, changes made to the parameter within the
function are reflected in the original variable.
● Example:
def append_element(list):
list.append(10)
9
my_list = [1, 2, 3]
64
append_element(my_list)
print(my_list) # Output: [1, 2, 3, 10]
● Explanation: In this example, my_list is passed to the append_element function by reference. The
17
function appends element 10 to the list, and the change is reflected in the original my_list variable.
Notes:
77
● Python primarily uses call-by-value for passing immutable objects (like numbers, strings, and tuples).
● Python uses call-by-reference for passing mutable objects (like lists, dictionaries, and sets).
●
61
Understanding the difference between call-by-value and call-by-reference is essential for writing correct
and efficient Python code.
● Python doesn't have a direct equivalent to call-by-reference in other languages, the concept of passing
/8
mutable objects by reference provides a similar behavior.
● When passing mutable objects to functions, be aware that any modifications made within the function
will affect the original object. This can be both a benefit and a potential pitfall, depending on the desired
outcome.
du
Recursion
● Definition: Recursion is a programming technique where a function calls itself directly or indirectly. It's
en
often used to solve problems that can be broken down into smaller subproblems of the same type.
● Examples of Recursion:
1. Factorial Calculations
ry
2. Fibonacci sequence
3. Tower of Hanoi
4. Depth-first search
Su
5. Merge sort
6. Quick sort
● Example: Factorial Calculation
def factorial(n):
"""Calculates the factorial of a non-negative integer."""
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # Output: 120
● Explanation:
1. Base Case: The function checks if n is 0. If it is, it returns 1 (factorial of 0 is 1). This is the base
case that prevents the recursion from going on indefinitely.
2. Recursive Case: If n is not 0, the function calls itself with (n - 1). This creates a chain of
recursive calls until the base case is reached.
9
3. Calculation: The function multiplies n by the result of the recursive call. This process continues
64
until the base case is reached, and then the results are multiplied back up the chain.
NOTES:
17
● Base Case: A condition that stops the recursion.
● Recursive Case: The part of the function that calls itself.
● Stack Overflow: If the base case is not reached or is incorrect, the recursion can lead to a stack
77
overflow error.
● Tail Recursion: A special type of recursion where the recursive call is the last operation in the function.
In some languages, tail recursion can be optimized to avoid stack overflow.
61
Python STRING
/8
A Python string is a sequence of characters enclosed in either single or double quotes. It's a fundamental data
type used to represent text in Python.
● 'Hello, world!'
● "This is a string with double quotes"
● '12345'
en
● Formatting: You can format strings using various methods like f-strings, format() method, or the %
operator.
● Methods: Python strings have many built-in methods for various operations, such as:
1. Concatenation: Joining strings together.
2. Formatting: Creating formatted strings using placeholders.
3. Case conversion: Converting strings to uppercase or lowercase.
4. Searching and replacing: Finding substrings and replacing them.
5. Splitting and joining: Breaking strings into lists or joining lists into strings.
9
5. string.count(substring): Returns the number of occurrences of a substring within the string.
○ Syntax: count = string.count(substring)
64
6. string.find(substring): Returns the index of the first occurrence of a substring within the string.
○ Syntax: index = string.find(substring)
7. string.replace(old, new): Replaces all occurrences of an old substring with a new substring.
17
○ Syntax: new_string = string.replace(old, new)
8. string.split(): Splits the string into a list of substrings based on whitespace.
77
○ Syntax: list_of_strings = string.split()
9. string.join(list): Joins elements of a list into a string, separated by the specified separator.
○ Syntax: joined_string = separator.join(list)
61
10. string.strip(): Removes leading and trailing whitespace from the string.
● Syntax: stripped_string = string.strip()
11. string.startswith(prefix): Checks if the string starts with a specified prefix.
/8
9
of a separator.
● Syntax: parts = string.rpartition(separator)
64
26. string.encode(): Encodes the string into a bytes object.
● Syntax: encoded_bytes = string.encode(encoding='utf-8')
27. string.decode(): Decodes a bytes object into a string.
17
● Syntax: decoded_string = encoded_bytes.decode(encoding='utf-8')
28. string.zfill(width): Pads the string with zeros on the left to a specified width.
● Syntax: padded_string = string.zfill(width)
77
29. string.expandtabs(tabsize=8): Expands tabs in the string to a specified number of spaces.
● Syntax: expanded_string = string.expandtabs(tabsize)
61
30. string.splitlines(): Splits the string into a list of lines.
● Syntax: lines = string.splitlines()
/8
Python LIST
A Python list is an ordered collection of items. Unlike strings, which are immutable sequences of
du
characters, lists can contain elements of any data type, including other lists. Lists are mutable, meaning their
elements can be changed, added, or removed after creation.
● Ordered: Elements in a list have a specific order, and their position can be accessed using an index.
● Mutable: Elements can be modified, added, or removed.
ry
Creating a list:
Accessing elements:
first_element = my_list[0] # 1
second_element = my_list[1] # 2.5
Slicing:
sublist = my_list[1:3] #[2.5, "hello"]
Modifying elements:
my_list[2] = "world"
Adding elements:
9
Removing elements:
64
my_list.remove("hello") # Remove by value
del my_list[0] # Remove by index
17
Other list operations:
77
● list.sort(): Sorts the elements in ascending order.
● list.reverse(): Reverses the order of the elements.
61
● list.copy(): Creates a copy of the list.
● list.clear(): Removes all elements from the list.
/8
Python TUPLE
A Python tuple is an ordered, immutable sequence of elements. Similar to lists, tuples can contain
du
elements of any data type. However, unlike lists, tuples cannot be modified once created.
● Ordered: Elements in a tuple have a specific order, and their position can be accessed using an index.
● Immutable: Elements cannot be changed, added, or removed after creation.
● Heterogeneous: Tuples can contain elements of different data types.
ry
● Read-only data: Tuples are useful for representing data that should not be changed, such as
coordinates or configuration settings.
● Faster than lists: Tuples are generally faster than lists because they are immutable.
● Hashing: Tuples can be used as keys in dictionaries because they are hashable (their hash value
remains constant).
Creating a tuple:
my_tuple = (1, 2.5, "hello", [3, 4])
Accessing elements:
first_element = my_tuple[0] # 1
second_element = my_tuple[1] # 2.5
Slicing:
9
64
Concatenation: Tuples can be concatenated using the + operator.
17
Membership testing: You can check if an element is in a tuple using the in operator.
if element in tuple:
77
Other Methods
61
1. len(tuple): Returns the length of the tuple.
○ Syntax: length = len(tuple)
2. tuple.count(element): Returns the number of occurrences of a specific element in the tuple.
/8
Python DICTIONARIES
A Python dictionary is an unordered collection of key-value pairs. It's a mutable data structure where
en
each unique key is associated with a corresponding value. Dictionaries are often used to store and retrieve
data based on specific identifiers.
ry
Creating a dictionary:
Accessing values:
name = my_dict["name"] # Accessing the value using the key
Modifying values:
my_dict["age"] = 31
my_dict["occupation"] = "Engineer"
9
Deleting key-value pairs:
64
del my_dict["city"]
17
for key, value in my_dict.items():
print(key, value)
77
Common dictionary methods:
Math Module
en
The math module in Python provides a wide range of mathematical functions and constants. It's a valuable tool
ry
9
● Trigonometric functions: tan, asin, acos, atan, atan2
64
● Logarithmic functions: log, log10, log2
● Exponents and powers: pow, factorial
● Rounding and truncation: ceil, floor, trunc
17
● Hyperbolic functions: sinh, cosh, tanh, asinh, acosh, atanh
77
61
/8
du
en
ry
Su