0% found this document useful (0 votes)
3 views25 pages

Python Notes (BCA_MCA_BTech)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Python

● 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

Python is installed correctly, you'll see the Python version.

Interactive Shell
en

● Open a terminal or command prompt.


● Type python and press Enter.
ry

● 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

IDLE (Integrated Development Environment)

● IDLE is a graphical interface for Python.


● To start IDLE, search for "IDLE" in your start menu or application launcher.
● Create a new file and write your Python code.
● Save the file with a .py extension.
● To run the code, click "Run" in the menu or press F5.
Input, Processing, and Output

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, Packages, Libraries, and Frameworks in Python

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

○ pip uninstall package_name: Uninstalls a package.

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

Relationship between these terms:

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.

Editing, Saving, and Running a Script


/8

1. Create a new text file with a .py extension (e.g., my_script.py).


du

2. Write your Python code in the file.


3. Save the file.
4. Open a terminal or command prompt and navigate to the directory where the file is saved.
5. Run the script using the command python my_script.py.
en

Debugging
ry

Syntax Errors
Su

● Errors that violate Python's grammar rules.


● Detected by the Python interpreter during compilation.
● Examples: missing parentheses, incorrect indentation, misspelled keywords.

Runtime Errors

● Errors that occur while the code is running.


● Often caused by invalid operations or unexpected input.
● Examples: division by zero, accessing an index out of range.

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

● Floor division: // (returns the integer part of the division; e.g., 7 // 3 = 2)


● Modulo: % (returns the remainder of the division; e.g., 7 % 3 = 1)
● Exponentiation: ** (e.g., 2 ** 3 = 8)
● Syntax implementation through Python :
du

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).

● Equal to: == (e.g., 5 == 5)


● Not equal to: != (e.g., 3 != 7)

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

print("a is equal to b")


# Less than
if a < b:
en

print("a is less than b")


else:
ry

print("a is not less than b")


# Greater than
if a > b:
Su

print("a is greater than b")


else:
print("a is not greater than b")
# Less than or equal to
if a <= b:
print("a is less than or equal to b")
else:
print("a is not less than or equal to b")
# Greater than or equal to
if a >= b:
print("a is greater than or equal to b")
else:
print("a is not greater than or equal to b")

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

y -= 3 # Subtract and assign


print("y -= 3:", y)
y *= 2 # Multiply and assign
en

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

● and: Logical AND


● or: Logical OR
● not: Logical NOT
● Syntax implementation through Python :

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:

● &: Bitwise AND


/8
● |: Bitwise OR
● ^: Bitwise XOR
● ~: Bitwise NOT
● <<: Left shift
du

● >>: Right shift


● Syntax implementation through Python :

a = 10 # Binary: 1010
en

b = 5 # Binary: 0101
result = a & b # Bitwise AND (&)
print("Bitwise AND:", result) # Output: 2 (Binary: 0010)
ry

result = a | b # Bitwise OR (|)


print("Bitwise OR:", result) # Output: 15 (Binary: 1111)
Su

result = a ^ b # Bitwise XOR (^)


print("Bitwise XOR:", result) # Output: 13 (Binary: 1101)
result = ~a # Bitwise NOT (~)
print("Bitwise NOT:", result) # Output: -11 (Binary: 10101)
result = a << 2 # Left shift (<<)
print("Left shift:", result) # Output: 40 (Binary: 101000))
result = a >> 2 # Right shift (>>
print("Right shift:", result) # Output: 2 (Binary: 0010)

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:

● in: Checks if a value is in a sequence


● not in: Checks if a value is not in a sequence
● Syntax implementation through Python :

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

● is: Checks if two variables refer to the same object


● is not: Checks if two variables refer to different objects
● Syntax implementation through Python :
en

x = 5
y = 5
ry

z = 6
if x is y: # Using the 'is' operator
Su

print("x and y are the same object.")


else:
print("x and y are different objects.")
if x is not z: # Using the 'is not' operator
print("x and z are different objects.")
else:
print("x and z are the same object.")
PEMDAS:

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

1. Numeric Data Types


du

● 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

● Complex Numbers – A complex number is represented by a complex class. It is specified as (real


part) + (imaginary part)j. For example – 2+3j
Su

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'>

print(type(False)) #<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

● Executes a block of code if a condition is true.


en

● Syntax: if condition:
● Example:

age = 18 if age >= 18:


ry

print("You are an adult.")

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

if grade >= 90:


print("A")
elif grade >= 80:
du

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

Control Flow Statements


ry

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.

for <variable> in <range()/sequence>:


# code to be executed
else:
# code to be executed if the loop completes normally

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

● The condition is evaluated before each iteration.


● Useful for loops where the number of iterations is unknown beforehand.

count = 0
en

while count < 5:


print(count)
ry

count += 1

Comparison points of three loops:


Su

● The for loop is ideal for iterating over elements in an iterable.


● The for-else loop is useful when you need to perform actions after the loop completes normally.
● The while loop is suitable for loops where the number of iterations depends on a condition.

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

● Purpose: Generates a sequence of numbers within a specified range.


The range function is often used in loops to iterate over a specific number of times.

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:

for number in range(5):

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

2. User-defined Functions: Created by the user using the def keyword.


● Benefits of Using Functions:
1. Code Reusability: Write once, and use multiple times.
en

2. Modularity: Break complex problems into smaller, manageable parts.


3. Maintainability: Easier to update and debug code.
ry

1. Built-in Functions in Python


Su

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.

General Purpose Functions

1. print(): Prints values to the console.


2. input(): Prompts the user for input and returns it as a string.
3. len(): Returns the length of a sequence (string, list, tuple, dictionary).
4. type(): Returns the type of an object.
5. range(): Creates a sequence of numbers.
6. enumerate(): Returns an iterator of tuples, containing the index and value of each item in a
sequence.
7. zip(): Combines elements from multiple sequences into tuples.
8. sorted(): Returns a sorted version of a sequence.
9. reversed(): Returns a reversed iterator of a sequence.

9
64
Mathematical Functions

1. abs(): Returns the absolute value of a number.

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

1. int(): Converts a value to an integer.


2. float(): Converts a value to a floating-point number.
du

3. str(): Converts a value to a string.


4. bool(): Converts a value to a Boolean (True or False).
en

Other Functions

1. open(): Opens a file.


ry

2. close(): Closes a file.


Su

3. dir(): Returns a list of valid attributes of an object.


4. help(): Provides help on a function or module.
5. id(): Returns the unique identifier of an object.

2. User-Defined Functions in Python


User-defined functions are functions that you create yourself to perform specific tasks within your Python code.
They allow you to break down complex problems into smaller, more manageable components, making your
code more organized, reusable, and easier to understand.

Syntax:

def function_name(formal parameters):


"""Docstring: Brief description of the function"""
# Function body (statements to be executed)

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

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

NOTES:
en

● Functions can take input parameters and return output values.


● Functions can be called multiple times within your code.
● Functions can be nested within other functions.
ry

● Functions can be used to modularize your code and improve readability.

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:

def greet(name): # 'name' is a formal parameter


print("Hello, " + name + "!")
greet("Alice") # 'Alice' is an actual parameter

In this example:

● greet is the function name.

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.

Examples of Python strings:


du

● 'Hello, world!'
● "This is a string with double quotes"
● '12345'
en

Key characteristics of Python strings:


ry

● Immutable: Once created, the contents of a string cannot be changed.


● Slicing: You can extract substrings using slicing notation (e.g., string[start:end]).
● Concatenation: Strings can be joined together using the + operator.
Su

● 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.

Essential String Methods


1. len(string): Returns the length of the string.
○ Syntax: length = len(string)
2. string.upper(): Converts all characters to uppercase.
○ Syntax: uppercase_string = string.upper()
3. string.lower(): Converts all characters to lowercase.
○ Syntax: lowercase_string = string.lower()
4. string.capitalize(): Capitalizes the first character of the string.
○ Syntax: capitalized_string = string.capitalize()

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

● Syntax: is_start = string.startswith(prefix)


12. string.endswith(suffix): Checks if the string ends with a specified suffix.
● Syntax: is_end = string.endswith(suffix)
13. string.isalpha(): Checks if all characters in the string are alphabetic.
du

● Syntax: is_alpha = string.isalpha()


14. string.isdigit(): Checks if all characters in the string are digits.
● Syntax: is_digit = string.isdigit()
en

15. string.isalnum(): Checks if all characters in the string are alphanumeric.


● Syntax: is_alnum = string.isalnum()
16. string.isspace(): Checks if all characters in the string are whitespace.
ry

● Syntax: is_space = string.isspace()


17. string.islower(): Checks if all characters in the string are lowercase.
Su

● Syntax: is_lower = string.islower()


18. string.isupper(): Checks if all characters in the string are uppercase.
● Syntax: is_upper = string.isupper()
19. string.istitle(): Checks if the string is in title case (first character of each word is uppercase).
● Syntax: is_title = string.istitle()
20. string.swapcase(): Swaps the case of all characters in the string.
● Syntax: swapped_string = string.swapcase()
21. string.center(width): Centers the string within a field of specified width.
● Syntax: centered_string = string.center(width)
22. string.ljust(width): Justifies the string to the left within a field of specified width.
● Syntax: left_justified_string = string.ljust(width)
23. string.rjust(width): Justifies the string to the right within a field of specified width.
● Syntax: right_justified_string = string.rjust(width)
24. string.partition(separator): Divides the string into three parts based on the first occurrence of
a separator.
● Syntax: parts = string.partition(separator)
25. string.rpartition(separator): Divides the string into three parts based on the last occurrence

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.

Key characteristics of Python lists:


en

● 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

● Heterogeneous: Lists can contain elements of different data types.


● Dynamically sized: The size of a list can change as elements are added or removed.
Su

Creating a list:

my_list = [1, 2.5, "hello", [3, 4]]

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:

my_list.append(5) # Add to the end


my_list.insert(2, "new_element") # Insert at a specific index

9
Removing elements:

64
my_list.remove("hello") # Remove by value
del my_list[0] # Remove by index

17
Other list operations:

● len(list): Returns the length of the list.

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.

Key characteristics of Python tuples:


en

● 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

● Dynamically sized: The size of a tuple is fixed and cannot be changed.

Why use tuples?


Su

● 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:

subtuple = my_tuple[1:3] # (2.5, "hello")

9
64
Concatenation: Tuples can be concatenated using the + operator.

my_tuple = tuple1 + tuple2

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

○ Syntax: count = tuple.count(element)


3. tuple.index(element): Returns the index of the first occurrence of a specific element in the tuple.
○ Syntax: index = tuple.index(element)
du

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

Key characteristics of Python dictionaries:

● Unordered: The order of elements in a dictionary is not guaranteed.


Su

● Mutable: Elements can be added, modified, or removed after creation.


● Key-value pairs: Each element in a dictionary consists of a key and its corresponding value.
● Unique keys: Keys within a dictionary must be unique.
● Versatile: Dictionaries are a versatile data structure in Python, often used to represent structured data,
such as configurations, mappings, or objects.

Creating a dictionary:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

Accessing values:
name = my_dict["name"] # Accessing the value using the key

Modifying values:

my_dict["age"] = 31

Adding new key-value pairs:

my_dict["occupation"] = "Engineer"

9
Deleting key-value pairs:

64
del my_dict["city"]

Iterating over key-value pairs:

17
for key, value in my_dict.items():
print(key, value)

77
Common dictionary methods:

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




61
dictionary.keys(): Returns a list of keys.
● dictionary.values(): Returns a list of values.
/8
● dictionary.items(): Returns a list of key-value tuples.
● dictionary.get(key, default_value): Returns the value for a key, or a default value if the key
doesn't exist.
● dictionary.update(other_dictionary): Merges another dictionary into the current one.
du

● dictionary.pop(key, default_value): Removes a key-value pair and returns its value.


● dictionary.setdefault(key, default_value): Sets a default value for a key if it doesn't exist.

Math Module
en

The math module in Python provides a wide range of mathematical functions and constants. It's a valuable tool
ry

for performing various calculations in your Python programs.


Su

Common Mathematical Functions

1. math.sin(x): Calculates the sine of the angle x (in radians).


○ Example: import math; result = math.sin(math.pi / 2)
2. math.cos(x): Calculates the cosine of the angle x (in radians).
○ Example: import math; result = math.cos(math.pi)
3. math.exp(x): Calculates the exponential of x (e raised to the power of x).
○ Example: import math; result = math.exp(2)
4. math.sqrt(x): Calculates the square root of x.
○ Example: import math; result = math.sqrt(16)
Important Mathematical Constants

1. math.pi: Represents the mathematical constant pi (approximately 3.14159).


○ Example: import math; circumference = 2 * math.pi * radius
2. math.e: Represents the mathematical constant e (the base of the natural logarithm, approximately
2.71828).
○ Example: import math; result = math.exp(1)

Additional Functions (Brief Overview)

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

You might also like