0% found this document useful (0 votes)
1 views134 pages

Python O'Level

Python is a high-level, interpreted programming language developed by Guido van Rossum in 1991, known for its simple syntax and wide usage in various fields like web development and data analysis. The document outlines Python's data types, differences between assemblers, compilers, and interpreters, as well as the roles of linkers and loaders in program execution. Additionally, it covers Python string manipulation, operators, and provides exam tips for understanding these concepts.

Uploaded by

vinayakbcktd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views134 pages

Python O'Level

Python is a high-level, interpreted programming language developed by Guido van Rossum in 1991, known for its simple syntax and wide usage in various fields like web development and data analysis. The document outlines Python's data types, differences between assemblers, compilers, and interpreters, as well as the roles of linkers and loaders in program execution. Additionally, it covers Python string manipulation, operators, and provides exam tips for understanding these concepts.

Uploaded by

vinayakbcktd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python:

Python एक high-level, interpreted programming language है जिसे Guido van Rossum ने 1991 में
develop किया था। यह अपने simple and readable syntax के लिए जाना जाता है , जो इसे beginners
औरexperienced programmers दोनों के लिएideal बनाता है।Python का use web development, data
analysis, artificial intelligence, machine learning, automation, औरscientific computing जैसे fields में
व्यापक(widely) used जाताहै। this is Fourth generation language.

Python Data Types


Python has several built-in data types, which can be categorized as follows:

1. Numeric Types
• int → Integer numbers (e.g., 10, -5, 1000)
• float → Floating-point numbers (e.g., 3.14, -0.5, 2.7e3)
• complex → Complex numbers (e.g., 3 + 4j, 2 - 7j)

2. Sequence Types
• str → String (e.g., 'Hello', "Python", "123")
• list → List (ordered, mutable collection) (e.g., [1, 2, 3], ['a', 'b', 'c'])
• tuple → Tuple (ordered, immutable collection) (e.g., (1, 2, 3), ('x', 'y',
'z'))
• range → Range of numbers (e.g., range(10), range(1, 5, 2))

3. Set Types
• set → Unordered collection of unique elements (e.g., {1, 2, 3}, {'apple',
'banana'})
• frozenset → Immutable version of a set (e.g., frozenset({1, 2, 3}))

4. Mapping Type
• dict → Dictionary (key-value pairs) (e.g., {'name': 'Alice', 'age': 25})

5. Boolean Type
• bool → Boolean values (True, False)

6. Binary Types
• bytes → Immutable sequence of bytes (e.g., b'hello')
• bytearray → Mutable sequence of bytes (e.g., bytearray(5))
• memoryview → A memory view object (e.g., memoryview(b'abc'))

7. None Type
• NoneType → Represents a null value (None)
Assembler, Compiler, and Interpreter: Differences & Explanation
These are three types of language processors used in programming to convert high-level or low-
level code into machine-readable instructions.

1️⃣ Assembler
🔹
🔹 Converts Assembly Language to Machine Code (Binary).
Assembly language is a human-readable version of machine code, using mnemonics like MOV,

🔹
ADD, SUB, etc.


The assembler translates this into binary instructions that the CPU can execute directly.



Operating System Development
Microcontroller Programming


Hardware Interfacing



Low-Level Language – Directly interacts with hardware.
Fast Execution – Runs faster than high-level languages.

✅ Efficient Memory Usage – Optimized for resource-limited systems.


Platform Dependent – Works only for a specific processor architecture.
Example:

Assembly Code (x86 NASM Syntax)


assembly

MOV AX, 5
ADD AX, 3

🔄 Assembler Converts to Machine Code (Binary)


sql

10111000 00000101 ; MOV AX, 5


00000101 00000011 ; ADD AX, 3
2️⃣ Compiler
🔹
🔹 Converts Entire High-Level Code to Machine Code Before Execution.

🔹
🔹
Creates an independent executable (.exe/.out) file.
Faster execution but requires compilation before running.
Examples: C, C++, Java (partially), Rust

✅ Example (C Language)

#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}

🔄 Compiler Converts This to Machine Code → Executable File

3️⃣ Interpreter
🔹
🔹 Executes Code Line-by-Line Without Creating an Executable File.

🔹
🔹
Slower than compiled languages but easier for debugging.
Used in scripting and interactive environments.
Examples: Python, JavaScript, PHP, Ruby

Types of Python Interpreters


1. CPython – The default and most widely used interpreter.
2. PyPy – A Just-In-Time (JIT) compiled version of Python for better performance.
3. Jython – Python interpreter written in Java.
4. IronPython – Python interpreter for .NET applications.
5. MicroPython – A lightweight Python interpreter for microcontrollers.
✅ Example (Python Code)
print("Hello, World!")

🔄 Interpreter Executes Each Line Immediately

🔍 Key Differences Between Assembler, Compiler, and Interpreter


Feature Assembler Compiler Interpreter
Input Language Assembly High-Level High-Level
Output Machine Code Machine Code (Executable) Executes Directly
Execution Speed Fast Fast (after compilation) Slower
Error Detection Difficult After full compilation Line-by-line
Python, JavaScript, PHP,
Examples NASM, MASM C, C++,c#, Java, COBOL
BASIC, Perl, Ruby

What is Linker and Loader?


1. Linker
A linker is a program that combines multiple object files into a single executable file. It resolves


symbol references and links external libraries.
Key Functions of a Linker:
• Combines different object files (.o or .obj) into a single executable.
• Resolves function and variable references.
• Links standard and user-defined libraries.
• Removes duplicate code (if needed).

📌 Types of Linkers:
• Static Linker – Links all required libraries into the executable at compile time.
• Dynamic Linker – Links external libraries at runtime (e.g., .dll in Windows, .so in
Linux).

2. Loader
A loader is a system program that loads the executable file into memory and prepares it for


execution. It is part of the operating system.
Key Functions of a Loader:
• Loads the executable file from disk to RAM.
• Allocates memory for program execution.
• Resolves dynamic library dependencies (if needed).
📌
• Starts the program execution.
Types of Loaders:
• Absolute Loader – Loads the program at a fixed memory location.
• Relocating Loader – Adjusts memory addresses dynamically.
• Dynamic Loading – Loads modules only when needed (saves memory).

Difference Between Linker and Loader


Feature Linker Loader
Combines object files into a single Loads the executable into RAM for
Function
executable. execution.
Execution
Works during compilation. Works during program execution.
Time
Handles Symbol resolution and library linking. Memory allocation and execution.
gcc file1.o file2.o -o ./program runs the loaded
Example program executable.

🔹
Conclusion

🔹
🔹
Linker combines object files and libraries into a single executable.
Loader loads the executable into RAM and runs the program.
Both are crucial in converting source code into a running program

*Comment in python:
In Python, comments are used to explain code and are ignored by the interpreter. Here's
how to use them:

1. Single-line comments

•Use the # symbol. Everything after # on that line is a comment.

# This is a single-line comment


print("Hello, World!") # This comment is after code

2. Multi-line comments

•Python doesn’t have a dedicated syntax for multi-line comments, but you can use triple
quotes (''' or """). These are technically strings but work as comments if not assigned to a
variable.
'''
This is a multi-line "comment".
It spans multiple lines.
'''
print("Hello, World!")

3. Docstrings (for documentation)

•Triple quotes are also used for docstrings to document functions, classes, or modules.
They are placed immediately after the definition.

def add(a, b):


"""This function returns the sum of a and b."""
return a + b

Strings in Python:
Strings are sequences of characters enclosed in quotes. They are immutable (cannot be
modified after creation) and support various operations. Here’s a breakdown of key
concepts

1. Creating Strings

•Use single quotes ('Hello'), double quotes ("Python"), or triple quotes for multi-line
strings:
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = '''This is a
multi-line string'''

2. Escape Characters

Use \ to include special characters:


escaped_str = "He said, \"Hello!\"\nNew line"
Common escape sequences:
\n (newline), \t (tab), \\ (backslash), \" (double quote), \' (single quote).
Raw Strings (ignore escape characters):
raw_str = r"C:\Users\Documents" # Output: C:\Users\Documents

3. String Operations

Concatenation: Combine with +:


name = "Alice" + " " + "Smith" # "Alice Smith"

Repetition: Repeat with *:


stars = "*" * 5 # "*****"

Indexing & Slicing:


s = "Python"
print(s[0]) # 'P' (indexing)
print(s[2:5]) # 'tho' (slicing)

4. String Methods

Commonly used methods (strings are immutable, so methods return new strings):

Case Conversion:
s = "Hello"
print([Link]()) # "hello"
print([Link]()) # "HELLO"

Trimming Whitespace:
s = " Python "
print([Link]()) # "Python"

Splitting & Joining:


s = "apple,banana,cherry"
print([Link](",")) # ['apple', 'banana', 'cherry']
print("-".join(["a", "b"])) # "a-b"

Replacing Substrings:
s = "I like Java"
print([Link]("Java", "Python")) # "I like Python"
5. String Formatting

f-strings (Python 3.6+, most modern and preferred):


name = "Bob"
age = 25
print(f"{name} is {age} years old.") # "Bob is 25 years old."

format() Method:
print("{} + {} = {}".format(2, 3, 5)) # "2 + 3 = 5"

Old-style (% operator):
print("Value: %d, Text: %s" % (10, "Hi")) # "Value: 10, Text: Hi"

6. String Immutability

Strings cannot be modified in place:


s = "hello"
s[0] = "H" # Error: 'str' object does not support item assignment
Operations like [Link]() or [Link]() return new strings.

7. Common Functions & Checks

len(): Get the length:


print(len("Python")) # 6

Membership Check (in):


print("th" in "Python") # True

Iteration:
for char in "Python":
print(char)
Exam Tips

•Syntax: Remember quotes (', ", '''), escape characters (\n, \t), and raw strings (r"...").
•Immutability: Operations return new strings; original remains unchanged.
•Formatting: Focus on f-strings and format() for exams.
•Common Errors: Mixing quote types (e.g., 'He's here' is invalid; use "He's here").

Example Code
# Multi-line string with triple quotes
poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''

# Raw string for file paths


path = r"C:\Users\BCA\[Link]"

# f-string with expressions


x = 10
y = 20
print(f"{x} + {y} = {x + y}") # "10 + 20 = 30"

*Key Differences:

Feature Interactive Mode Script Mode


Execution Line-by-line Entire file at once
Use Case Testing, debugging, learning Building applications, automation
Persistence Commands not saved automatically Code saved in a .py file
Output Immediate After the script finishes running
Complexity Simple for short code Better for large/complex programs
*Operators in Python:
Operators are symbols used to perform operations on variables and values. Here’s a
structured breakdown of Python operators
1. Arithmetic Operators
Used for mathematical calculations:

Operator Description Example Result


+ Addition 5+3 8
- Subtraction 10 - 2 8
* Multiplication 4*3 12
/ Division 10 / 2 5.0
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
// Floor Division 10 // 3 3

2. Comparison (Relational) Operators

Compare values and return True or False:

Operator Description Example Result


== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>5 True
< Less than 7<5 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 5 <= 3 False

3. Logical/ Boolean Operators

Combine conditional statements:

Operator Description Example Result


and True if both are true (5 > 3) and (5 < 10) True
or True if at least one is true (5 < 3) or (5 < 10) True
not Inverts the result not (5 < 3) True
4. Assignment Operators

Assign values to variables:

Operator Example Equivalent to


= x=5 x=5
+= x += 3 x=x+3
-= x -= 2 x=x-2
*= x *= 4 x=x*4
/= x /= 2 x=x/2
%= x %= 3 x=x%3
**= x **= 2 x = x ** 2
//= x //= 3 x = x // 3

5. Bitwise Operators

Operate on binary representations of integers:

Operator Description Example Result (Binary)


& AND 5&3 0b0001 (1)
| OR 5|3 0b0111 (7)
^ XOR 5^3 0b0110 (6)
~ NOT (1's complement) ~5 -6
<< Left shift 5 << 1 10 (0b1010)
>> Right shift 5 >> 1 2 (0b0010)

6. Identity Operators

Check if two objects are the same in memory:

Operator Description Example Result


is True if same object x is y Depends
is not True if not same x is not y Depends
Note: == checks value equality, while is checks memory identity.
7. Membership Operators

Check if a value exists in a sequence (list, string, tuple, etc.):

Operator Description Example Result


in True if value exists "a" in ["a", "b"] True
not in True if value absent 3 not in [1, 2] True

8. Ternary Operator

Short-hand for if-else statements:


x = 10
y = 20
max_val = x if x > y else y # Returns 20

9. Increment/Decrement Operators

Python does NOT have ++ or -- operators. Use:

No ++/--: Use x += 1 instead of x++.

x += 1 # Increment by 1 (equivalent to x = x + 1)
x -= 1 # Decrement by 1
Example:

count = 5
count += 1 # 6
count -= 1 # 5
*Operator Precedence:

Order of evaluation (highest to lowest):

[Link] ()
[Link] **
[Link] NOT ~, Unary +, -
[Link] *, Division /, Floor //, Modulus %
[Link] +, Subtraction -
[Link] shifts <<, >>
[Link] AND &
[Link] XOR ^
[Link] OR |
[Link] (==, !=, >, <, etc.)
[Link] NOT not
[Link] AND and
[Link] OR or

Example:
result = 5 + 3 * 2 ** 2 # Evaluates to 5 + (3 * 4) = 17

Exam Tips

[Link] vs ==: is checks memory address; == checks value equality.


[Link]-Circuiting: Logical operators (and/or) stop evaluation as soon as the result is
known.
[Link] Tricks: Memorize XOR (^) for toggling bits and shifts (<<, >>) for
multiplication/division by powers of 2.
[Link] Precedence: Use parentheses () to control evaluation order.
•Example: 5 + 3 * 2 = 11 (not 16).
[Link] Short-Circuiting:
•and stops if the first condition is False.
•or stops if the first condition is True.
[Link] vs Logical:
•& and | are bitwise operators (work on bits).
•and and or are logical operators (work on conditions).
[Link]: Operations on strings/numbers create new objects.
[Link] ++/--: Use x += 1 instead of x++.
Example Code
# Ternary operator
age = 18
status = "Adult" if age >= 18 else "Minor" # "Adult"

# Membership check
s = "Python"
print("th" in s) # True

# Bitwise operations
a = 5 # 0b101
b = 3 # 0b011
*Exchanging values of two variables:
a=5
b = 10
# Swap values
a, b = b, a

print(a) # Output: 10
print(b) # Output: 5

or

Using a temporary variable (valid but less Pythonic):


temp = a
a=b
b = temp
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5

*To calculate the summation of a set of numbers in Python, you can use the
built-in sum() function:

Example:

numbers = [1, 2, 3, 4, 5] # List of numbers


total = sum(numbers)

print("Sum =", total) # Output: Sum = 15

Alternative Methods:
1. Using a for loop:

numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num

print("Sum =", total)

2. Using [Link]() (for functional programming style):

from functools import reduce

numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)

print("Sum =", total)


**In Python, converting a decimal (base-10) number to binary (base-2), octal
(base-8), or hexadecimal (base-16) is straightforward using built-in functions. Here's
how to do it:

1. Built-in Functions

Python provides direct methods for these conversions:

Conversion Function Example Output (as string)


Binary bin() bin(10) '0b1010'
Octal oct() oct(64) '0o100'
Hexadecimal hex() hex(255) '0xff'
Removing the Prefix:
To exclude the 0b, 0o, or 0x prefix, slice the string:
decimal = 255
binary = bin(decimal)[2:] # '11111111'
octal = oct(decimal)[2:] # '377'
hexadecimal = hex(decimal)[2:] # 'ff'
print(binary)
print(octal)
print(hexadecimal)

2. Using format() for Cleaner Output

The format() function allows flexible formatting (no prefixes, uppercase hex, padding,
etc.):

Syntax:

format(decimal_number, format_specifier)

Conversion Format Specifier Example Output


Binary 'b' format(10, 'b') '1010'
Octal 'o' format(64, 'o') '100'
Hexadecimal 'x' (lowercase) format(255, 'x') 'ff'
Hexadecimal 'X' (uppercase) format(255, 'X') 'FF'
**To find the Greatest Common Divisor (GCD) of two numbers in Python, you can use
either the built-in [Link] function (recommended) or implement the Euclidean
algorithm. Here’s how to do both:

1. Using the Built-in [Link] Function

Ideal for simplicity and efficiency (Python 3.5+):

import math

a = 48
b = 18
gcd_value = [Link](a, b)
print(gcd_value) # Output: 6

Features:
•Handles negative inputs by taking absolute values.
•Returns 0 if both inputs are 0.
Example with Edge Cases:
print([Link](-12, 18)) # Output: 6 (ignores negatives)
print([Link](0, 5)) # Output: 5
print([Link](0, 0)) # Output: 0

2. Manual Implementation (Euclidean Algorithm)

Useful for understanding the logic or if using older Python versions:

Iterative Approach:

def gcd(a, b):


a, b = abs(a), abs(b) # Handle negatives
while b != 0:
a, b = b, a % b # Repeatedly replace (a, b) with (b, a % b)
return a

print(gcd(48, 18)) # Output: 6


print(gcd(0, 5)) # Output: 5
print(gcd(0, 0)) # Output: 0 (by definition)

Recursive Approach:

def gcd(a, b):


a, b = abs(a), abs(b)
return a if b == 0 else gcd(b, a % b)
print(gcd(48, 18)) # Output: 6

How the Euclidean Algorithm Works:

[Link] 1: Take absolute values of inputs.


[Link] 2: Replace a with b and b with a % b until b becomes 0.
[Link] 3: The last non-zero value of a is the GCD.
Example:

•gcd(48, 18):
•48 % 18 = 12 → gcd(18, 12)
•18 % 12 = 6 → gcd(12, 6)
•12 % 6 = 0 → GCD is 6.

Key Takeaways:

•Use [Link] for simplicity and speed.


•Implement manually for educational purposes or backward compatibility.
•Both methods handle negative numbers and zeros.

Test whether a number is prime:


n=int(input("enter a number"))
i=2
while i<=(n-1):
if n%i==0:
print(n,"is not prime number;")
exit()
else:
i=i+1
print(n,"is prime number;")
Debugging in Python

Debugging is the process of finding and fixing errors (bugs) in code.

Common Types of Errors


[Link] Errors:
Code violates Python rules (e.g., missing :).
Example:
if x == 5 # Missing colon (:)
[Link] Errors:
Errors during execution (e.g., division by zero).

Common runtime errors include:


• ZeroDivisionError: Dividing by zero.
• TypeError: Performing an operation on incompatible data types.
• NameError: Using a variable that hasn't been defined.
• IndexError: Accessing an index that is out of range in a list.
• KeyError: Trying to access a dictionary key that doesn't exist.
• ValueError: Passing the wrong type of argument to a function.
• IndentationError: Use spaces or tabs, but not both at the beginning of lines.

Example:
1) print(10 / 0) # ZeroDivisionError

2) num=10
text=”hello”
print(num+text) #TypeError unsupported operand

3) name = "Alice"
print(nam) # NameError: name 'nam' is not defined

4) my_list = [1, 2, 3]
print(my_list[3]) # IndexError: list index out of range

5) my_dict = {"name": "Alice", "age": 25}


print(my_dict["city"]) # KeyError: 'city'
6) num = int("hello") # Raises ValueError because "hello"
can't be converted to an integer.

7) print("Hello")
print("World") # This line is indented unnecessarily
or
for i in range(10):
print(i) #IndentationError: expected an indented block
after 'for' statement on line 1

[Link] Errors :
Code runs but gives wrong results.
Example:
1) def multiply(a, b):
return a + b # Logical error (should be a * b)

2) def calculate_area(radius):
return 2 * 3.14 * radius # This is actually the formula for
circumference, not area.

Debugging Techniques
[Link] Print Statements:
Track variable values and flow.
Example:
print("Current value of x:", x)
[Link] Debugger (pdb):
Step through code line-by-line.
Example:
import pdb; pdb.set_trace() # Set a breakpoint
[Link] Tools :
Use debuggers in VS(Visual Studio) Code, PyCharm, IDLE, Spyder,
Jupyter Notebook, Thonny etc.
[Link] Error Trace backs :
Read error messages to locate issues.

[Link] Handling Error:


Python provides a way to handle exceptions using try, except, else, and
finally blocks.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print(result)
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution complete.")

Example: Debugging a Division Error

Buggy Code:
a = 10
b=0
result = a / b # ZeroDivisionError
print(result)

Debugged Code:
a = 10
b=0
try:
result = a / b
except ZeroDivisionError:
result = "Undefined (Division by zero)"
print("Result:", result)

Exception Handling in Python


Exception Handling is a mechanism to handle runtime errors (exceptions) in Python so that the
program does not crash unexpectedly. It allows the program to respond to errors gracefully instead
of stopping execution.

1. What is an Exception?
An exception is an error that occurs during the execution of a program that disrupts the normal

🔹
flow.
Common Exception Types in Python

Exception Description
ZeroDivisionError Dividing by zero (10 / 0)
ValueError Invalid value for a function (int("abc"))
TypeError Unsupported operation between data types ("hello" + 5)
Exception Description
IndexError Accessing an invalid list index (list[10])
KeyError Accessing a non-existent dictionary key (dict['key'])
FileNotFoundError Trying to open a non-existing file
AttributeError Calling a non-existent attribute or method

2. Exception Handling using try-except


🔹
🔹
The try block contains the code that may cause an exception.
The except block handles the error and prevents the program from crashing.

Basic Example: Handling Division by Zero

try:
result = 10 / 0 # This will cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")

✅ Output: Error: Cannot divide by zero!

3. Handling Multiple Exceptions


🔹 Use multiple except blocks to catch different types of errors.

try:
num = int(input("Enter a number: ")) # Might cause ValueError
result = 10 / num # Might cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")



Input: abc → Output: Error: Invalid input! Please enter a number.
Input: 0 → Output: Error: Cannot divide by zero!

4. Using except Exception as e (Catching Any Error)


🔹 This method catches all possible exceptions and prints the error message.

try:
x = int("hello") # This will cause ValueError
except Exception as e:
print(f"An error occurred: {e}")

✅ Output: An error occurred: invalid literal for int() with base 10:
'hello'
5. Using else and finally
🔹
🔹
else executes if no exception occurs.
finally executes always (whether an error occurs or not).

try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input!")
else:
print("Success! The result is:", result) # Runs if no error
finally:
print("Execution finished.") # Always runs



Input: 2 → Output: Success! The result is: 5.0
Input: 0 → Output: Error: Cannot divide by zero!

6. Raising Exceptions using raise


🔹 We can manually raise exceptions using raise.

def check_age(age):
if age < 18:
raise ValueError("Error: Age must be 18 or above!")
print("Access granted.")

try:
check_age(16) # This will cause an error
except ValueError as e:
print(e)

✅ Output: Error: Age must be 18 or above!

7. Creating Custom Exceptions


🔹 We can define our own exception classes by inheriting from Exception.

class NegativeNumberError(Exception):
pass # Custom exception class

def check_positive(num):
if num < 0:
raise NegativeNumberError("Error: Negative numbers are not allowed!")

try:
check_positive(-5)
except NegativeNumberError as e:
print(e)

✅ Output: Error: Negative numbers are not allowed!

8. Exception Handling in File Handling


🔹 Handling errors while reading files.

try:
file = open("non_existing_file.txt", "r")
content = [Link]()
[Link]()
except FileNotFoundError:
print("Error: File not found!")

✅ Output: Error: File not found!

Conclusion
✔ Exception Handling makes programs more reliable and user-friendly by preventing crashes.
✔ Always use try-except to handle errors gracefully.
✔ Use finally to ensure important cleanup (like closing a file).
✔ Custom exceptions improve error readability in complex programs.
Python की तकनीकी ताकत | Technical Strength of Python
Python एक शक्तिशाली और लोकप्रिय प्रोग्रामिंग भाषा है, जिसकी कई तकनीकी खूबियाँ (Technical
Strengths) हैं।

1. पठनीयता और सरलता | Readability & Simplicity


✔ Python की सिंटैक्स (Syntax) बहुत सरल और साफ-सुथरी होती है, जिससे इसे पढ़ना और लिखना
आसान होता है।
✔ इंडेंटेशन (Indentation) आधारित संरचना बेहतर कोडिंग प्रैक्टिस को बढ़ावा देती है।

2. विशाल पुस्तकालय और फ्रे मवर्क | Extensive Libraries &


Frameworks
✔ Python में इन-बिल्ट (Built-in) मॉड्यूल और तृतीय-पक्ष (Third-Party) लाइब्रेरीज़ उपलब्ध हैं।
✔ विभिन्न क्षेत्रों के लिए उपयोगी पुस्तकालय:
🔹
🔹 डेटा साइंस और एआई (Data Science & AI): NumPy, Pandas, TensorFlow, PyTorch

🔹
🔹
वेब डेवलपमेंट (Web Development): Django, Flask, FastAPI
स्क्रिप्टिंग और ऑटोमेशन (Scripting & Automation): Selenium, BeautifulSoup
नेटवर्किं ग (Networking): Scapy, Paramiko

3. क्रॉस-प्लेटफ़ॉर्म संगतता | Cross-Platform Compatibility


✔ Windows, Linux, macOS, और एम्बेडेड सिस्टम (Embedded Systems) पर चलता है।

4. मजबूत समुदाय और समर्थन | Strong Community & Support


✔ Python का बड़ा डेवलपर समुदाय (Large Developer Community) और अच्छा दस्तावेज़ीकरण
(Extensive Documentation) है।
✔ नए अपडेट्स और समाधान लगातार मिलते रहते हैं।

5. डायनामिक टाइपिंग और हाई-लेवल लैंग्वेज | Dynamic Typing


& High-Level Language
✔ डेटा टाइप (Data Type) को घोषित करने की आवश्यकता नहीं होती (int, float, etc.)।
✔ स्वचालित मेमोरी प्रबंधन (Automatic Memory Management) और गार्बेज कलेक्शन (Garbage
Collection) समर्थित है।
6. ऑब्जेक्ट-ओरिएं टेड और फं क्शनल प्रोग्रामिंग | Object-
Oriented & Functional Programming
✔ Python में OOP (Classes, Inheritance) और Functional Paradigm (Lambda, Map, Reduce)
दोनों का समर्थन है।

7. मल्टी-पैराडाइम सपोर्ट | Multi-Paradigm Support


✔ प्रोसीजरल (Procedural), ऑब्जेक्ट-ओरिएं टेड (OOP), और फं क्शनल (Functional) प्रोग्रामिंग
स्टाइल को सपोर्ट करता है।

8. इंटीग्रेशन और एक्स्टेंसिबिलिटी | Integration & Extensibility


✔ Python को C, C++, Java, .NET, और JavaScript के साथ एकीकृ त किया जा सकता है।
✔ अन्य एप्लिके शन में एम्बेड (Embed) किया जा सकता है।

9. मल्टी-थ्रेडिंग और एसिंक्रोनस सपोर्ट | Multi-Threading &


Asynchronous Support
✔ थ्रेडिंग (Threading) और मल्टीप्रोसेसिंग (Multiprocessing) को सपोर्ट करता है।
✔ उच्च-प्रदर्शन नेटवर्क एप्लिके शन के लिए Async I/O (asyncio)।

10. स्के लेबिलिटी और परफॉर्मेंस ऑप्टिमाइज़ेशन | Scalability &


Performance Optimization
✔ Python को Cython, Numba, और JIT (Just-in-Time) कम्पाइलर के साथ तेज़ किया जा सकता है।
✔ वितरित कं प्यूटिंग (Distributed Computing) के लिए Dask, Ray, और PySpark का उपयोग किया
जाता है।

11. सुरक्षा विशेषताएँ | Security Features


✔ एन्क्रिप्शन (Encryption) और ऑथेंटिके शन (Authentication) के लिए इन-बिल्ट मॉड्यूल उपलब्ध
हैं।
✔ साइबर सुरक्षा (Cybersecurity) में Scapy और Metasploit जैसे टू ल्स का उपयोग किया जाता है।
12. उभरती हुई तकनीकों में लोकप्रिय | Popular in Emerging
Technologies
✔ Python का उपयोग AI, ML, डेटा साइंस, ब्लॉकचेन, IoT और साइबर सुरक्षा में बड़े पैमाने पर किया
जाता है।
✔ आधुनिक स्वचालन और स्क्रिप्टिंग (Automation & Scripting) के लिए भी यह अत्यधिक उपयोगी है।

निष्कर्ष | Conclusion
Python एक बहु-उद्दे श्यीय (Versatile), शक्तिशाली (Powerful), और सरल (Easy-to-Use) प्रोग्रामिंग
भाषा है, जो वेब डेवलपमेंट से लेकर आर्टिफिशियल इंटेलिजेंस तक कई क्षेत्रों में उपयोग की जाती है।
Literals in Python
What are Literals?
A literal in Python is a fixed value assigned to a variable or used directly in expressions. These
values do not change and represent constant values in the program.

Types of Literals in Python


Python has several types of literals:

1. String Literals
String literals are sequences of characters enclosed in single ('), double ("), or triple quotes ('''


or """ """).
Examples:
single_quote = 'Hello, Python!'
double_quote = "Welcome to Python"
triple_single = '''This is
a multi-line string.'''
triple_double = """Another
multi-line string."""

2. Numeric Literals


Numeric literals include integers, floating-point numbers, and complex numbers.
Examples:
# Integer Literal
integer_num = 100

# Floating-Point Literal
float_num = 10.5

# Complex Number Literal


complex_num = 3 + 5j

3. Boolean Literals


Boolean literals represent True or False values.
Examples:
is_python_fun = True
is_java_hard = False
🔹 Boolean literals internally store True as 1 and False as 0.
Example:
print(True + False) # Output: 1 (1 + 0)

4. Special Literal (None)


The None literal represents the absence of a value or a null value.

Example:
empty_value = None
print(empty_value) # Output: None

5. List, Tuple, Dictionary, and Set Literals


Python supports collection literals:
Examples:
# List Literal
fruits = ["Apple", "Banana", "Cherry"]

# Tuple Literal
numbers = (1, 2, 3, 4, 5)

# Dictionary Literal
student = {"name": "Alice", "age": 20}

# Set Literal
unique_values = {1, 2, 3, 4, 5}

6. Special Character Literals (Escape Sequences)


Python provides escape sequences to represent special characters.
Common Escape Sequences:

Escape Sequence Description


\n Newline
\t Tab space
\' Single quote
\" Double quote
\\ Backslash
Example:
print("Hello\nWorld") # Newline
print("Python\tRocks") # Tab space
print('It\'s a great day!') # Escape single quote
7. Binary, Octal, and Hexadecimal Literals


Python supports number literals in different bases:
Examples:
binary_num = 0b1010 # Binary (10 in decimal)
octal_num = 0o12 # Octal (10 in decimal)
hex_num = 0xA # Hexadecimal (10 in decimal)

Summary
Literal Type Example
String "Hello" 'Python' '''Multiline'''
Integer 100, -50
Float 10.5, -2.7
Complex 3 + 4j
Boolean True, False
None None
List [1, 2, 3]
Tuple (1, 2, 3)
Dictionary {"key": "value"}
Set {1, 2, 3}
Binary 0b1010 (Binary 10)
Octal 0o12 (Octal 10)

🔹
Hexadecimal 0xA (Hex 10)
Literals are fundamental building blocks of Python programming!

What are Constants?


A constant in Python is a variable whose value should not be changed after its initial assignment.
Python does not have built-in support for constants like some other languages (e.g., const in C or
Java), but by convention, we use uppercase variable names to indicate constants.
Numbers in Python (Integers, Floats, Complex
Numbers, Real, Sets)
Python provides several built-in numeric data types to work with numbers. These include integers
(int), floating-point numbers (float), complex numbers (complex), real numbers
(float), and sets (set).

1. Integer (int)


An integer is a whole number, either positive, negative, or zero, without a decimal point.
Example:
x = 10 # Positive Integer
y = -5 # Negative Integer
z = 0 # Zero

print(type(x)) # Output: <class 'int'>

✅ Operations with Integers:


a = 10
b = 3

print(a + b) # Addition (10 + 3 = 13)


print(a - b) # Subtraction (10 - 3 = 7)
print(a * b) # Multiplication (10 * 3 = 30)
print(a // b) # Floor Division (10 // 3 = 3)
print(a % b) # Modulus (10 % 3 = 1)
print(a ** b) # Exponentiation (10^3 = 1000)

✅ Integer Type Conversion:


num = "50"
int_num = int(num) # Convert string to integer
print(int_num) # Output: 50

2. Floating-Point Numbers (float)


A floating-point number (real number) contains a decimal point or is written in scientific notation.
Example:
x = 10.5 # Float number
y = -3.14 # Negative float
z = 2.0 # Float, even though it's a whole number

print(type(x)) # Output: <class 'float'>

✅ Scientific Notation:
a = 1.2e3 # 1.2 × 10³ = 1200.0
b = 2.5e-4 # 2.5 × 10⁻⁴ = 0.00025

print(a, b) # Output: 1200.0 0.00025

✅ Operations with Floats:


a = 5.5
b = 2.2

print(a + b) # Output: 7.7


print(a * b) # Output: 12.1
print(a / b) # Output: 2.5

✅ Rounding Float Values:


num = 3.14159
rounded_num = round(num, 2) # Round to 2 decimal places

print(rounded_num) # Output: 3.14

✅ Convert Float to Integer:


x = 10.7
int_x = int(x) # Converts 10.7 to 10 (removes decimal part)

print(int_x) # Output: 10

3. Complex Numbers (complex)


Python supports complex numbers, which consist of a real and an imaginary part.
Example:
c1 = 3 + 4j
c2 = 5 - 2j

print(type(c1)) # Output: <class 'complex'>

# Access real and imaginary parts


print([Link]) # Output: 3.0
print([Link]) # Output: 4.0

✅ Operations with Complex Numbers:


c1 = 2 + 3j
c2 = 1 - 4j

print(c1 + c2) # Addition (3 - 1j)


print(c1 * c2) # Multiplication (-10 - 5j)
print(c1 / c2) # Division (-0.647 + 0.706j)

✅ Convert Integer/Float to Complex:


num = 10
complex_num = complex(num) # Convert int to complex
print(complex_num) # Output: (10+0j)
4. Real Numbers in Python


In Python, real numbers are represented using the float type.

Example:
x = 3.14159 # Real number (float)
y = -2.71828 # Real number (negative)

print(type(x)) # Output: <class 'float'>

✅ Operations on Real Numbers:


a = 5.75
b = 2.5

print(a + b) # Output: 8.25


print(a - b) # Output: 3.25
print(a * b) # Output: 14.375
print(a / b) # Output: 2.3

✅ Checking if a Value is a Real Number:


import numbers

x = 4.5
print(isinstance(x, [Link])) # Output: True

5. Sets (set)


A set is an unordered collection of unique elements.
Example:
s = {1, 2, 3, 3, 2, 1} # Duplicates are removed automatically

print(s) # Output: {1, 2, 3}


print(type(s)) # Output: <class 'set'>

✅ Set Operations:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B) # Union: {1, 2, 3, 4, 5, 6}


print(A & B) # Intersection: {3, 4}
print(A - B) # Difference: {1, 2}
print(A ^ B) # Symmetric Difference: {1, 2, 5, 6}

✅ Modifying Sets:
numbers = {1, 2, 3}
[Link](4) # Add element
[Link](2) # Remove element

print(numbers) # Output: {1, 3, 4}


✅ Frozen Sets (Immutable Set):
fs = frozenset([1, 2, 3, 4])
print(fs) # Output: frozenset({1, 2, 3, 4})

Summary Table
Data Type Example Description
Integer (int) x = 10 Whole numbers
Float (float) x = 3.14 Real numbers (decimal values)
Complex (complex) c = 2 + 3j Numbers with real and imaginary parts
Real Numbers (float) x = 5.75 Subset of floats
Set (set) {1, 2, 3} Unordered collection of unique elements
Accepting Input from Console in Python
Python provides the input() function to take user input from the console. The input received is
always a string by default, but it can be converted into other data types like integers, floats, or lists.

1. Basic Input Using input()


The input() function allows users to enter data during program execution.

Example:
name = input("Enter your name: ")
print("Hello,", name)

Output:
Enter your name: Alice
Hello, Alice

✅ Explanation:
• The input() function takes user input.

• The input is stored in the variable name.

• The entered name is displayed using print().

2. Accepting Integer Input


Since input() always returns a string, we use int() to convert it into an integer.

Example:
age = int(input("Enter your age: "))
print("Your age is:", age)

Output:
Enter your age: 25
Your age is: 25

🚨 Note: If the user enters a non-numeric value, Python will raise an error.

3. Accepting Float (Decimal) Input


For decimal numbers, use float().

Example:
price = float(input("Enter the product price: "))
print("Price:", price)

Output:
Enter the product price: 99.99
Price: 99.99

4. Accepting Multiple Inputs


Python allows multiple inputs in one line using split().

Example:
x, y = input("Enter two numbers separated by space: ").split()
print("First Number:", x)
print("Second Number:", y)

Output:
Enter two numbers separated by space: 10 20
First Number: 10
Second Number: 20

🚀 Converting to Integers:
x, y = map(int, input("Enter two numbers: ").split())
print("Sum:", x + y)

Output:
Enter two numbers: 5 10
Sum: 15

5. Accepting a List as Input


We can take multiple values and store them in a list.
Example:
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print("List of Numbers:", numbers)

Output:
Enter numbers separated by space: 1 2 3 4 5
List of Numbers: [1, 2, 3, 4, 5]
6. Accepting a String Input Without a Prompt


If you don’t pass a prompt message in input(), it will still work.

Example:
data = input()
print("You entered:", data)

7. Handling Errors in Input


If the user enters an invalid input (e.g., a letter instead of a number), the program may crash. We can


use try-except to handle errors.

Example:
try:
num = int(input("Enter an integer: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid integer.")

Output:
Enter an integer: abc
Invalid input! Please enter a valid integer.

8. Accepting Input for Complex Numbers


To take a complex number as input, convert it using complex().

Example:
c = complex(input("Enter a complex number (e.g., 3+4j): "))
print("Complex Number:", c)

9. Accepting Boolean Input


Since input() always returns a string, we can manually convert "True"/"False" to a Boolean.

Example:
bool_value = input("Enter True or False: ").strip().lower() == "true"
print("Boolean Value:", bool_value)

Output:
Enter True or False: True
Boolean Value: True
10. Accepting Input Without Pressing Enter (Advanced)
If you want to accept input without pressing Enter, use getch() from the msvcrt module


(Windows).
Example (Windows only):
import msvcrt
print("Press any key: ")
key = [Link]()
print("You pressed:", [Link]())

Summary Table
Input Type Example Code Conversion
String Input name = input("Enter name: ") No conversion needed
num = int(input("Enter number:
Integer Input ")) int()
price = float(input("Enter
Float Input float()
price: "))
Multiple x, y = map(int, input().split()) map(int, input().split())
Inputs
nums = list(map(int, list(map(int,
List Input input().split())) input().split()))
Complex c = complex(input()) complex()
Number
bool_value =
Boolean Input input().strip().lower() == Custom conversion
"true"

Key Takeaways
✔ input() takes input as a string by default.
✔ Convert input to int (int()), float (float()), or other types as needed.
✔ Use split() and map() for multiple inputs.
✔ Handle errors using try-except.
Printing Statements in Python
Python provides the print() function to display output on the screen. It can print strings,
numbers, variables, multiple values, formatted text, and even special characters.

1. Basic print() Statement


The simplest way to print something in Python.
Example:
print("Hello, World!")

Output:
Hello, World!

2. Printing Variables


We can print variables by passing them inside print().

Example:
name = "Alice"
age = 25

print(name)
print(age)

Output:
Alice
25

3. Printing Multiple Values


We can print multiple values using commas , or string concatenation (+).

Using commas (automatic spaces):


name = "Alice"
age = 25

print("Name:", name, "Age:", age)

Output:
Name: Alice Age: 25
✅ Using string concatenation (+):
print("Name: " + name + ", Age: " + str(age))

Output:
Name: Alice, Age: 25

🚨 Note: If you use +, all values must be strings (str()). Otherwise, it will cause an error.

4. Printing with sep (Separator)


The sep parameter controls how values are separated.

Example:
print("Apple", "Banana", "Cherry", sep=" - ")

Output:
Apple - Banana - Cherry

✅ Example (No space separator):


print("Python", "Programming", sep="")

Output:
PythonProgramming

5. Printing with end (End Character)


The end parameter changes the default newline (\n) behavior.

Example (No newline, add space instead):


print("Hello", end=" ")
print("World!")

Output:
Hello World!

✅ Example (Using end for custom ending):


print("Loading", end="... Done!")

Output:
Loading... Done!
6. Printing Using format()


The .format() method allows formatted printing.

Example:
name = "Alice"
age = 25

print("My name is {} and I am {} years old.".format(name, age))

Output:
My name is Alice and I am 25 years old.

✅ Example (Numbered Placeholders):


print("My name is {1} and I am {0} years old.".format(age, name))

Output:
My name is Alice and I am 25 years old.

7. Printing Using f-strings (Python 3.6+)


f-strings provide an easier way to format strings.

Example:
name = "Alice"
age = 25

print(f"My name is {name} and I am {age} years old.")

Output:
My name is Alice and I am 25 years old.

✅ Example (Math Operations in f-strings):


a, b = 5, 10
print(f"Sum of {a} and {b} is {a + b}")

Output:
Sum of 5 and 10 is 15

8. Printing Special Characters


✅ Newline (\n):
print("Hello\nWorld")
Output:
Hello
World

✅ Tab Space (\t):


print("Hello\tWorld")

Output:
Hello World

✅ Backslash (\\):
print("This is a backslash: \\")

Output:
This is a backslash: \

✅ Quotes in Strings:
print("He said, \"Python is awesome!\"")
print('It\'s a great day!')

Output:
He said, "Python is awesome!"
It's a great day!

9. Printing in a Loop
✅ Example:
for i in range(1, 6):
print(f"Number {i}")

Output:
Number 1
Number 2
Number 3
Number 4
Number 5
10. Printing a Dictionary in a Pretty Format


Python’s json module can print dictionaries in a structured format.

Example:
import json

data = {"name": "Alice", "age": 25, "city": "New York"}

print([Link](data, indent=4))

Output:
{
"name": "Alice",
"age": 25,
"city": "New York"
}

11. Printing Without a Newline (End Parameter)


By default, print() prints with a newline. We can avoid this using end="".

Example:
print("Hello", end=" ")
print("World!")

Output:
Hello World!

12. Writing Output to a File


Use the file parameter in print() to write output to a file.

Example:
with open("[Link]", "w") as file:
print("Hello, File!", file=file)

Output (saved in [Link] file):


Hello, File!

13. Printing Unicode Characters


Python supports Unicode symbols like emojis and special characters.
✅ Example (Emoji Printing):
print("Smile 😊
")
print("\U0001F600") # Unicode for 😀
Output:
Smile

😊

Summary Table
Feature Example Output
Basic Print print("Hello") Hello
Multiple Values print("A", "B", sep="-") A-B
No Newline print("Hello", end=" ") Hello
Format Strings print(f"My age is {age}") My age is 25
Escape Characters print("Line1\nLine2") Line1 Line2
Write to File print("Hello", file=file) (Saves to file)

Conclusion
🔹
🔹
print() is a powerful function for displaying output in Python.

🔹
You can customize it using sep (separator), end (end character), and file (file output).
Formatted printing is easier with f-strings, .format(), and escape characters (\n,

🔹
\t).
Python allows printing Unicode characters, writing to files, and structuring JSON data.
Assignment statement:
An assignment statement in Python is used to assign a value to a variable. It's one of the most
basic and important concepts in any programming language.

🔹 Syntax:
variable_name = value

• = is the assignment operator.

• The value on the right is assigned to the variable on the left.

🔹 Examples:
x = 10
name = "Ankit"
price = 19.99

🔹 Multiple Assignments:
We can assign values to multiple variables in a single line:
a, b, c = 1, 2, 3

We can also assign the same value to multiple variables:


x = y = z = 100

🔹 Compound Assignment:
Python supports compound assignment operators to modify and assign in one step:
x = 5
x += 3 # Same as: x = x + 3 → x becomes 8
x *= 2 # Same as: x = x * 2 → x becomes 16

Other compound operators: -=, /=, //=, %=, **=, etc.

🔹 Dynamic Typing:
In Python, you don't need to declare a variable type. The type is determined automatically when you
assign a value:
x = 10 # x is an integer
x = "hello" # now x is a string
Conditional Statements:
Conditional statements let a program choose what to do based on certain conditions. Think of it
like giving the computer a choice:
“If this happens, do that. Otherwise, do something else.”

🔹 1. if Statement
It checks one condition. If it's true, it runs the code.

👉 Syntax:
if condition:
# code to run if condition is true

✅ Example:
age = 18

if age >= 18:


print("You are an adult.")

🔹 2. if-else Statement
Checks a condition. If it’s true, it runs one block of code.
If false, it runs a different block.

👉 Syntax:
if condition:
# code if true
else:
# code if false

✅ Example:
marks = 40

if marks >= 50:


print("You passed!")
else:
print("You failed.")
🔹 3. if-elif-else Statement
Used when you have multiple conditions to check.

👉 Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none are true

✅ Example:
score = 75

if score >= 90:


print("Grade A")
elif score >= 70:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Fail")

🔹 Common Comparison Operators


Operator Meaning Example
== Equal to x == 5
!= Not equal to x != 3
> Greater than x > 10
< Less than x<7
>= Greater or equal x >= 5
<= Less or equal x <= 8

Think of a traffic light:


if light == "green":
print("Go")
elif light == "red":
print("Stop")
elif light == "yellow":
print("Get ready")
else:
print("No Traffic")
range() Function:
The range() function is used to generate a sequence of numbers.

It is most commonly used in loops, especially in for loops.

Why use range()


To tell the computer:
"Repeat something from this number to that number."

🔹 Basic Syntax of range()


range(start, stop, step)

• start → the number to start from (optional, default is 0)

• stop → the number to stop before

• step → how much to increase each time (optional, default is 1)

🔸 Examples:
Example 1: range(5)
for i in range(5):
print(i)

Output:
0
1
2
3
4

Starts at 0, stops before 5 (default step is 1)

Example 2: range(1, 6)
for i in range(1, 6):
print(i)

Output:
1
2
3
4
5

Starts at 1, stops before 6

Example 3: range(1, 10, 2)


for i in range(1, 10, 2):
print(i)

Output:
1
3
5
7
9

Starts at 1, stops before 10, goes up by 2 each time

Example 4: range(10, 0, -1) – Countdown!


for i in range(10, 0, -1):
print(i)

Output:
10
9
8
7
6
5
4
3
2
1

Counts backward from 10 to 1

Key Points to Remember:


• range(5) gives: 0, 1, 2, 3, 4

• range(1, 6) gives: 1, 2, 3, 4, 5

• range(1, 10, 2) gives: 1, 3, 5, 7, 9


What is a String Slice:
A slice is a way to extract a part of a string using its index positions.
The basic syntax:
string[start:stop]

• start → where the slice begins (inclusive)

• stop → where the slice ends (exclusive)

Example:
text = "Python Programming"

print(text[0:6]) # Python
print(text[7:18]) # Programming

• text[0:6] gets characters at index 0 to 5

• text[7:18] gets from index 7 to 17

Shortcut Slices
Slice Meaning Example Output
text[:6] From start to index 5 'Python'
text[7:] From index 7 to the end 'Programming'
text[:] The whole string (copy) 'Python Programming'

🔙 Negative Index Slicing


Negative indexes count from the end of the string.
text = "Python"

print(text[-3:]) # 'hon' (last 3 letters)


print(text[:-3]) # 'Pyt' (everything except last 3)

🪜 Adding a Step (Optional)


Syntax:
string[start:stop:step]

Example:
text = "abcdefg"

print(text[::2]) # 'aceg' (every 2nd character)


print(text[::-1]) # 'gfedcba' (reverses the string)
✅ Summary
Syntax What it does
s[start:stop] Slice from start to stop-1
s[:stop] From beginning to stop-1
s[start:] From start to end
s[::-1] Reverses the string
s[::step] Every step character
*Looping in Python:
Looping is a fundamental concept in programming that allows code to be executed repeatedly.
Python provides two main types of loops:
1. for Loop (Used for iterating over sequences like lists, tuples, and strings)
2. while Loop (Repeats execution as long as a condition is True)

Additionally, Python provides loop control statements such as break, continue, and pass to
manage loop execution.

1. for Loop
The for loop is primarily used to iterate over sequences like lists, tuples, dictionaries, sets, and
strings.

Basic Syntax:
for variable in sequence:
# Code to execute

Example: Iterating Over a List


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

Using for Loop with range()


The range() function generates a sequence of numbers.
for i in range(5): # Loops from 0 to 4
print(i)

Output:
0
1
2
3
4

Using for Loop with Strings


word = "Python"
for letter in word:
print(letter, end=” “)
Output:
P y t h o n

Using for Loop with Dictionaries


student_scores = {"Ankit": 85, "Pankaj": 90, "Kanchan": 88}
for name, score in student_scores.items():
print(f"{name} scored {score}")

Output:
Ankit scored 85
Pankaj scored 90
Kanchan scored 88

2. while Loop
The while loop is used when the number of iterations is unknown and depends on a condition.

Basic Syntax:
while condition:
# Code to execute

Example: Using while Loop


x = 0
while x < 5:
print(x)
x += 1

Output:
0
1
2
3
4

Using while Loop for User Input


password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")

(This will keep asking for input until the correct password is entered.)
3. Loop Control Statements
Python provides special statements to control loops:

a) break Statement (Exit the Loop Early)


for i in range(10):
if i == 5:
break # Stops loop when i is 5
print(i)

Output:
0
1
2
3
4

b) continue Statement (Skip the Current Iteration)


for i in range(5):
if i == 2:
continue # Skips when i is 2
print(i)

Output:
0
1
3
4

c) pass Statement (Placeholder for Future Code)


for i in range(5):
if i == 3:
pass # Does nothing, just a placeholder
print(i)

Output:
0
1
2
3
4
4. Nested Loops (Loop Inside Another Loop)
Python allows loops to be nested.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")

Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

tables from 1 to 10:

for i in range(1,11):
for j in range(1,11):
print(i*j,end=" ")
print("\n")

5. else Clause in Loops


Python allows an else clause in loops, which executes when the loop finishes without being
interrupted by break.

Example with for Loop


for i in range(3):
print(i)
else:
print("Loop completed successfully!")

Output:
0
1
2
Loop completed successfully!

Example with while Loop


x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop ended normally!")

Output:
0
1
2
Loop ended normally!

If the loop is interrupted using break, the else block will not execute.

What is assert
The assert statement is used to test if a condition is true.

• If the condition is true, nothing happens.


• If the condition is false, it shows an error and stops the program.
It's mostly used for debugging or checking that a program is working as expected.

🔹 Syntax:
assert condition

OR
assert condition, "Error message"

✅ Example 1:
x = 10
assert x > 0 # This will pass because x is 10
print("x is positive")

✔️Output:
x is positive

❌ Example 2:
x = -5
assert x > 0, "x is not positive"
print("x is positive")

❌ Output:
AssertionError: x is not positive

The program stops because the condition x > 0 is false.


Why use assert?
• To make sure something is true during program execution
• To catch bugs early
• Like saying: “This must be true — or something is wrong!”

Real-life Example:
You're checking if a student has passed:

marks = 45
assert marks >= 40, "Student has failed"
print("Student has passed")


✔️This works if marks are 40 or more.
If marks are less than 40, it will show an error.
String Slice:
A slice is a way to extract a part of a string using its index positions.
The basic syntax:
string[start:stop]

• start → where the slice begins (inclusive)

• stop → where the slice ends (exclusive)

Example:
text = "Python Programming"

print(text[0:6]) # Python
print(text[7:18]) # Programming

• text[0:6] gets characters at index 0 to 5

• text[7:18] gets from index 7 to 17

Shortcut Slices
Slice Meaning Example Output
text[:6] From start to index 5 'Python'
text[7:] From index 7 to the end 'Programming'
text[:] The whole string (copy) 'Python Programming'

🔙 Negative Index Slicing


Negative indexes count from the end of the string.
text = "Python"

print(text[-3:]) # 'hon' (last 3 letters)


print(text[:-3]) # 'Pyt' (everything except last 3)

🪜 Adding a Step (Optional)


Syntax:
string[start:stop:step]

Example:
text = "abcdefg"

print(text[::2]) # 'aceg' (every 2nd character)


print(text[::-1]) # 'gfedcba' (reverses the string)
✅ Summary
Syntax What it does
s[start:stop] Slice from start to stop-1
s[:stop] From beginning to stop-1
s[start:] From start to end
s[::-1] Reverses the string
s[::step] Every step character
🔹 List:
A list is a built-in data structure in Python that is used to store multiple items in a single variable.
Lists are ordered, changeable (mutable), and allow duplicate values.

Syntax:
my_list = [1, 2, 3, 4, 5]

🔹 Key Characteristics of Lists


Feature Description
Items have a defined order and that order will not change unless you explicitly
Ordered
do it.
Mutable You can add, remove, or change elements.
Allows Duplicates Lists can contain the same value more than once.
Heterogeneous Lists can contain different types (int, str, float, list, etc.)

🔹 Creating a List
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "Hello", 3.14, True]
nested = [1, 2, [3, 4], 5]
empty = []

🔹 Accessing List Elements


Using Indexing (starts from 0):
names = ["Alice", "Bob", "Charlie"]
print(names[0]) # Alice
print(names[2]) # Charlie

Negative Indexing (starts from -1):


print(names[-1]) # Charlie
print(names[-2]) # Bob

🔹 List Operations
1. Slicing
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[2:]) # [30, 40, 50]
print(numbers[-3:-1]) # [30, 40]
print(numbers[::2] # [10,30,50]

2. Modifying Elements
numbers[1] = 25
print(numbers) # [10, 25, 30, 40, 50]

🔹 List Methods
Here are some commonly used list methods:

Method Description
append() Adds an item to the end of the list
insert() Inserts an item at a specific index
remove() Removes the first occurrence of the specified item
pop() Removes the item at the specified index (or last item)
clear() Removes all items from the list
index() Returns the index of the first occurrence of an item
count() Returns the number of times an item appears
sort() Sorts the list in ascending order
reverse() Reverses the list
copy() Returns a shallow copy of the list
extend() Adds elements of another list to the end

Examples:
fruits = ["apple", "banana", "cherry"]

[Link]("orange") # ['apple', 'banana', 'cherry', 'orange']


[Link](1, "kiwi") # ['apple', 'kiwi', 'banana', 'cherry', 'orange']
[Link]("banana") # ['apple', 'kiwi', 'cherry', 'orange']
[Link]() # ['apple', 'kiwi', 'cherry']
print([Link]("kiwi")) # 1
print([Link]("apple")) # 1
[Link]() # ['apple', 'cherry', 'kiwi']
[Link]() # ['kiwi', 'cherry', 'apple']

🔹 Looping Through a List


for fruit in fruits:
print(fruit)

Or with index:
for i in range(len(fruits)):
print(i, fruits[i])
🔹 List Comprehension (Advanced but powerful)
Quick way to create a new list using a loop.
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]

With condition:
even = [x for x in range(10) if x % 2 == 0]
print(even) # [0, 2, 4, 6, 8]

🔹 Nested Lists
Lists within lists:
matrix = [
[1, 2],
[3, 4],
[5, 6]
]

print(matrix[1][0]) # 3

🔹 Copying Lists
Do not do this:
a = [1, 2, 3]
b = a # both point to same list

Do this instead:
b = [Link]() # or b = list(a)

🔹 Common Use Cases


• Storing a collection of items (numbers, strings, etc.)
• Implementing stacks and queues
• Working with matrices (as 2D lists)
• Building custom data structures
🔹 Tuple:
A tuple is an ordered, immutable collection of items. Tuples are used to store multiple items in a
single variable, just like lists, but you cannot change (add, remove, or modify) the elements once
the tuple is created.

✅ Syntax
my_tuple = (1, 2, 3)

Important:
For a single-element tuple, you must include a comma:
t = (5,) # This is a tuple
not_tuple = (5) # This is just an integer

🔹 Key Characteristics of Tuples


Feature Description
Ordered Items have a defined order
Immutable Cannot be changed after creation
Allow duplicates Can have the same value multiple times
Heterogeneous Can contain different data types

🔹 Creating Tuples
# With parentheses
t1 = (1, 2, 3)

# Without parentheses (tuple packing)


t2 = 4, 5, 6

# Empty tuple
empty = ()

# Single element tuple


single = ("apple",)

# Mixed data types


mixed = (1, "hello", 3.14, True)

# Nested tuple
nested = (1, 2, (3, 4), 5)
🔹 Accessing Tuple Elements
Same as with lists:
t = (10, 20, 30, 40)

print(t[0]) # 10
print(t[-1]) # 40

🔹 Slicing Tuples
t = (1, 2, 3, 4, 5)

print(t[1:4]) # (2, 3, 4)
print(t[:3]) # (1, 2, 3)
print(t[2:]) # (3, 4, 5)

🔹 Tuple Unpacking
You can assign each element of a tuple to a variable:
person = ("Alice", 25, "India")

name, age, country = person

print(name) # Alice
print(age) # 25
print(country) # India

You can also use * for unpacking:


numbers = (1, 2, 3, 4, 5)

a, *b, c = numbers

print(a) # 1
print(b) # [2, 3, 4]

🔹
print(c) # 5

Tuple Methods
Tuples have only two built-in methods:

Method Description
count() Returns number of times a value appears
index() Returns the index of the first occurrence of a value

Example:
t = (1, 2, 2, 3, 4, 2)

print([Link](2)) # 3
print([Link](3)) # 3
🔹 Why Use Tuples?
• Faster than lists (better performance for fixed data)
• Immutable, so safer from unintended changes
• Can be used as dictionary keys
• Good for representing fixed collections like coordinates, RGB values, etc.

🔹 Tuple vs List
Feature List ([]) Tuple (())
Mutability Mutable (can change) Immutable (cannot change)
Syntax [] ()
Speed Slower Faster
Methods Many methods available Only count() & index()
Use Cases Dynamic data Fixed data

🔹 Nested and Complex Tuples


Tuples can contain other tuples or lists:
nested = ((1, 2), (3, 4), [5, 6])
print(nested[2][0]) # 5

🔹 Tuple with for Loop


colors = ("red", "green", "blue")

for color in colors:


print(color)

🔹 Practical Use Cases


• Returning multiple values from a function
• Fixed data records (e.g., coordinates, settings)
• As keys in dictionaries
• Faster iteration when data doesn't need to change

🔸 Example: Returning Multiple Values from a Function


def calc(a, b):
return a + b, a * b

sum_, product = calc(3, 4)


print(sum_) # 7
print(product) # 12

🔹 Dictionary:
A dictionary is an unordered, mutable collection of key-value pairs. Each value is accessed using
its key (not an index like in lists or tuples).

✅ Syntax
my_dict = {
"name": "Alice",
"age": 25,
"city": "Mumbai"
}

• Keys are unique


• Keys must be immutable (like strings, numbers, tuples)
• Values can be of any type (even another dictionary)

🔹 Key Characteristics
Feature Description
Key-Value Pairs Items are stored as key: value
Unordered (Python <3.7) Order of elements not guaranteed
Mutable Can be changed (add/update/delete)
Keys are unique No duplicate keys allowed
Keys are immutable Strings, numbers, tuples (not lists/dicts)
🔹 Creating Dictionaries
# Empty dictionary
empty = {}

# With values
student = {
"name": "John",
"age": 21,
"grades": [85, 90, 92]
}

# Using dict() constructor


info = dict(name="Emma", age=22, country="India")

🔹 Accessing Values
✅ Using the key
print(student["name"]) # John
print(student["grades"]) # [85, 90, 92]

✅ Using get() method (safer)


print([Link]("age")) # 21
print([Link]("email", "N/A")) # N/A (default value)

🔹 Modifying Dictionary
✅ Changing existing value
student["age"] = 22

✅ Adding new key-value pair


student["email"] = "john@[Link]"

🔹 Removing Items
Method Description
pop(key) Removes item with the given key
popitem() Removes last inserted item
del Deletes item by key or entire dict
clear() Removes all items

Examples:
[Link]("age")
[Link]()
del student["name"]
[Link]()

🔹 Dictionary Methods
Method Description
keys() Returns a view of all keys
values() Returns a view of all values
items() Returns key-value pairs as tuples
update() Adds items from another dictionary
copy() Returns a shallow copy

Example:
person = {
"name": "Sam",
"age": 30
}

print([Link]()) # dict_keys(['name', 'age'])


print([Link]()) # dict_values(['Sam', 30])
print([Link]()) # dict_items([('name', 'Sam'), ('age', 30)])

🔹 Looping Through a Dictionary


✅ Loop through keys:
for key in person:
print(key, person[key])

✅ Loop through items:


for key, value in [Link]():
print(f"{key} -> {value}")

🔹 Nesting in Dictionaries
✅ Dictionary inside dictionary
students = {
"101": {"name": "Alice", "age": 21},
"102": {"name": "Bob", "age": 22}
}

print(students["101"]["name"]) # Alice
🔹 Dictionary Comprehension
A quick way to create a dictionary using loops:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

🔹 Common Use Cases


• Storing structured data (like user info, records)
• Counting items (word frequency, character count)
• Fast lookups (like hash maps)
• Converting data (like from JSON)

🔹 Dictionary vs List vs Tuple

✅ ✅ ✅
Feature List Tuple Dictionary

✅ ❌ ✅
Ordered? (since Python 3.7)
Mutable?


Access by Index Index Key
Duplicate keys? — —

🔹 Real-World Example
Counting word frequency in a sentence:
sentence = "hello world hello python"
words = [Link]()
count = {}

for word in words:


count[word] = [Link](word, 0) + 1

print(count)
# Output: {'hello': 2, 'world': 1, 'python': 1}
Sets:

A set in Python is an unordered collection of unique and immutable elements. Sets are mutable
(can be modified), but the elements they contain must be immutable (like integers, strings, or
tuples).

Key Features of Sets:


1. Unordered – Elements are not stored in any particular order.
2. Unique – No duplicate elements are allowed.
3. Mutable – You can add or remove elements.
4. Heterogeneous – Can contain different data types (e.g., `{1, "hello", 3.14}`).
5. Optimized for membership tests – Faster than lists for checking if an item exists (`x in set`).

How to Create a Set


1. Using Curly Braces { }
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}

2. Using set( ) Constructor

empty_set = set( ) # Empty set ({} creates an empty dictionary)


list_to_set = set([1, 2, 2, 3]) # Removes duplicates → {1, 2, 3}
string_to_set = set("hello") # {'h', 'e', 'l', 'o'} (unordered, no duplicates)

Basic Set Operations


1. Adding Elements

my_set.add(6) # Adds 6 → {1, 2, 3, 4, 5, 6}


my_set.update([7, 8]) # Adds multiple elements → {1, 2, 3, 4, 5, 6, 7, 8}
2. Removing Elements
my_set.remove(8) # Removes 8, raises KeyError if not found
my_set.discard(9) # Removes 9 if exists, no error otherwise
popped = my_set.pop() # Removes & returns a random element (since unordered)
my_set.clear() # Empties the set → set()

3. Checking Membership
if 3 in my_set:
print("3 is in the set")

4. Length of a Set
print(len(my_set)) # Returns number of elements

Set Operations (Mathematical):


Python sets support mathematical operations like union, intersection, difference, etc.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b) # Union: {1, 2, 3, 4, 5, 6}


print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric Difference: {1, 2, 5, 6}

---

Frozen Sets (Immutable Sets)


frozenset is an immutable version of a set.
- Cannot add or remove elements.
- Useful as dictionary keys (since normal sets are mutable and unhashable).
frozen = frozenset([1, 2, 3])
# [Link](4) → Error! (Immutable)

When to Use Sets?


Removing duplicates from a list:
unique_list = list(set([1, 2, 2, 3])) # [1, 2, 3]

Fast membership testing (faster than lists):

if x in my_set: # O(1) average time complexity


print("Found!")
🔹 bytes in Python
• Immutable sequence of bytes (you cannot change it after creation).
• Sequence of integers (0-255)
• Often used for binary data like images, files, or network communication.
• Similar to a string, but it contains bytes instead of Unicode characters.

✅ Syntax:
b = bytes([65, 66, 67])
print(b) # Output: b'ABC'
print(b[0]) # Output: 65

Here, 65, 66, and 67 are ASCII values for 'A', 'B', and 'C'.

❌ You cannot modify it:


b[0] = 100 # Error: 'bytes' object does not support item assignment

🔹 bytearray in Python
• Mutable version of bytes (you can modify it).
• Sequence of integers (0-255)
• Also stores a sequence of bytes.
• Useful when you need to change or manipulate binary data.

✅ Syntax:
ba = bytearray([65, 66, 67])
print(ba) # Output: bytearray(b'ABC')

# Modify a byte
ba[0] = 68
print(ba) # Output: bytearray(b'DBC')

🔄 Conversion Between bytes and bytearray


From bytes to bytearray:
b = bytes([1, 2, 3])
ba = bytearray(b)

From bytearray to bytes:


ba = bytearray([1, 2, 3])
b = bytes(ba)

🔍 Key Differences Table


Feature bytes bytearray
Mutability Immutable Mutable

❌ ✅
Syntax Example b = bytes([1,2]) ba = bytearray([1,2])


Can be modified? No Yes
Memory efficient Yes (slightly) Slightly more usage
🔷 1. Concatenation of Lists
Lists can be easily concatenated using the + operator.

✅ Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]

result = list1 + list2


print(result) # [1, 2, 3, 4, 5, 6]

🔁 We can also use .extend():


[Link](list2)
print(list1) # [1, 2, 3, 4, 5, 6]

+ creates a new list, while .extend() modifies the original list.

🔷 2. Concatenation of Tuples
Tuples are immutable, but you can concatenate them using + (which returns a new tuple).

✅ Example:
tuple1 = (10, 20)
tuple2 = (30, 40)

result = tuple1 + tuple2


print(result) # (10, 20, 30, 40)

⚠️We cannot use .extend() or .append() with tuples since they're


immutable.

🔷 3. Concatenation of Dictionaries
Dictionaries don’t use the + operator. Instead, you can use:

✅ update() method:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

[Link](dict2)
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

This modifies dict1 in-place.


✅ Using {**dict1, **dict2} (Python 3.5+):
combined = {**dict1, **dict2}
print(combined)

This creates a new dictionary.

✅ Python 3.9+ | operator:


combined = dict1 | dict2
print(combined)

Also creates a new merged dictionary.

🔔 What if keys overlap?


If the same key appears in both dictionaries, the last one wins:
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}

combined = {**d1, **d2}


print(combined) # {'a': 1, 'b': 3, 'c': 4}

✅ Summary Table
Type Operator / Method Notes
List +, .extend() Mutable, ordered
Tuple + Immutable
Dictionary .update(), {**d1, **d2}, ` `
🔷 Sequence data type:
In Python, a sequence is an ordered collection of items where each item is associated with an
index (position). You can access the items using their index.

✅ Built-in Sequence Types in Python:


Type Description
List Mutable sequence of items
Tuple Immutable sequence
String Immutable sequence of characters
Range Immutable sequence of numbers (used in loops)
Bytes Immutable sequence of bytes
Bytearray Mutable version of bytes

🔹 Common Features of Sequences


All sequences support the following features:

Feature Description
Indexing Access elements by position (starting at 0)
Slicing Extract part of the sequence
Iteration Loop through elements using for loop
Length Use len() to get number of elements
Membership test Use in or not in to check for values
Concatenation Combine sequences using +
Repetition Repeat sequence using *

🔸 Indexing Example:
name = "Python"
print(name[0]) # P
print(name[-1]) # n

🔸 Slicing Example:
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]

🔸 Length Example:
print(len(nums)) # 5
🔸 Membership Test:
print(30 in nums) # True
print("y" in "Python") # True

🔸 Concatenation:
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print("Py" + "thon") # Python
print((1, 2) + (3, 4)) # (1, 2, 3, 4)

🔸 Repetition:
print([1, 2] * 3) # [1, 2, 1, 2, 1, 2]
print("Hi! " * 2) # Hi! Hi!

🔹 Mutable vs Immutable Sequences


Property Mutable (can change) Immutable (cannot change)

✅ ❌
Examples list, bytearray tuple, str, range, bytes
Can be modified?

🔹 Types of Sequence Data


✅ 1. List:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"

✅ 2. Tuple:
point = (10, 20)
# point[0] = 15 ❌ Not allowed

✅ 3. String:
text = "hello"
# text[0] = "H" ❌ Not allowed

✅ 4. Range:
r = range(1, 6)
print(list(r)) # [1, 2, 3, 4, 5]
✅ 5. Bytes and Bytearray (Advanced):
b = bytes([65, 66, 67]) # Immutable
ba = bytearray([65, 66, 67]) # Mutable

✅ Summary Table

✅ ✅ ✅
Sequence Type Mutable Ordered Indexed Use Case

❌ ✅ ✅
list General-purpose

❌ ✅ ✅
tuple Fixed data

❌ ✅ ✅
str Text data

❌ ✅ ✅
range Efficient looping

✅ ✅ ✅
bytes Binary data
bytearray Mutable binary data
🔷 Mutability:
In Python, mutability refers to whether or not an object can be changed (modified) after it is
created.
• Mutable objects can be changed
• Immutable objects cannot be changed

🔹 Mutable vs Immutable (Quick Comparison)

✅ ❌
Property Mutable Immutable
Can be changed Yes No
list, dict, set, int, float, str, tuple, frozenset,
Examples
bytearray bytes

🔹 Mutable Objects
These can be modified in-place without changing their identity (memory location).

✅ Examples: list, dict, set


my_list = [1, 2, 3]
my_list[0] = 10
print(my_list)
# ✅ allowed
# [10, 2, 3]

my_dict = {"a": 1}
my_dict["b"] = 2
print(my_dict)
# ✅ allowed
# {'a': 1, 'b': 2}

my_set={1,2,3}
my_set.add(4)
print(my_set)
# ✅ allowed
#{1,2,3,4}

🔹 Immutable Objects
These cannot be changed once created. If you try to modify them, Python creates a new object.

❌ Examples: int, float, str, tuple


x = 10
x = x + 5 # Creates a new integer object

name = "Alice"
name[0] = "M" # ❌ Error: strings are immutable

t = (1, 2, 3)
t[0] = 10 # ❌ Error: tuples are immutable
Identity Check Using id()
a = [1, 2, 3]
print(id(a)) # e.g., 140209932548416
[Link](4)
print(id(a)) # Same ID → modified in-place

b = "hello"
print(id(b)) # e.g., 140209932548752
b += " world"
print(id(b)) # Different ID → new object created

Why is this important?


• Mutable objects can affect other variables if they refer to the same object (aliasing).
• Immutable objects are safer in functions and keys in dictionaries.

Example of Pitfall (Mutability Confusion)


list1 = [1, 2, 3]
list2 = list1 # Both point to same list
list2[0] = 100

print(list1) # [100, 2, 3] → list1 also changed!

How to avoid it?


Use .copy() or [Link]() to create a new object if needed.
list2 = [Link]() # Now changes to list2 won't affect list1

Summary
Term Meaning
Mutable Can change content after creation
Immutable Cannot change content once created
Why care? Prevent bugs, understand behavior
🔹 List of Numbers


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

1. Find Maximum
Use the built-in max() function:
maximum = max(numbers)
print("Maximum:", maximum)


# Output: Maximum: 50

2. Find Minimum
Use the built-in min() function:
minimum = min(numbers)
print("Minimum:", minimum)


# Output: Minimum: 10

3. Find Mean (Average)


Use the sum() function divided by len():
mean = sum(numbers) / len(numbers)
print("Mean:", mean)

🔹
# Output: Mean: 30.0

Full Code Together:


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

maximum = max(numbers)
minimum = min(numbers)
mean = sum(numbers) / len(numbers)

print("Maximum:", maximum)
print("Minimum:", minimum)

🔹
print("Mean:", mean)

Bonus: Handling User Input


user_input = input("Enter numbers separated by spaces: ")
numbers = list(map(int, user_input.split()))

print("Max:", max(numbers))
print("Min:", min(numbers))
print("Mean:", sum(numbers)/len(numbers))
Linear Search:
Linear search is a simple search algorithm that:
• Checks each element in the sequence one by one.
• Stops when the target value is found.
• Works for unsorted data.

Linear Search on a List


def linear_search_list(numbers, target):
for index, value in enumerate(numbers):
if value == target:
return index # return position if found
return -1 # not found

# Example usage:
nums = [5, 10, 15, 20, 25]
target = 15

result = linear_search_list(nums, target)


if result != -1:
print(f"Found at index {result}")
else:
print("Not found")

Linear Search on a Tuple


Same logic applies. Tuples are immutable, but you can still loop through them.
def linear_search_tuple(numbers, target):
for index, value in enumerate(numbers):
if value == target:
return index
return -1

# Example:
nums = (3, 6, 9, 12)
target = 9

result = linear_search_tuple(nums, target)


print("Found at index" if result != -1 else "Not found", result)

Output Example
If you search for 15 in [5, 10, 15, 20, 25], it prints:
Found at index 2

If you search for a number not in the list, like 30, it prints:
Not found

Bonus: Case-insensitive Search (for strings)


If you're searching in a list of strings:
names = ["Alice", "Bob", "Charlie"]
target = "bob"

for index, name in enumerate(names):


if [Link]() == [Link]():
print("Found at index", index)
break
else:
print("Not found")

Key points:

•Time Complexity: O(n) - Checks each element once in the worst case.
•Space Complexity: O(1)/O(k) - Uses constant extra space.
•Works for both lists and tuples since they are iterable and indexable.
•Returns the first occurrence's index if duplicates exist.
•Returns -1 if the target is not found.
Counting the frequency of elements in a list using a dictionary:

Given a list like:


data = [1, 2, 2, 3, 1, 4, 2]

We want to count how many times each element appears.

[Link] an empty dictionary to store element-frequency pairs.


[Link] through each element in the list.
[Link] the dictionary:

•If the element exists as a key, increment its count.


•If it doesn’t exist, add the element to the dictionary with a count of 1.

🔷 Using a for loop with a dictionary:


data = [1, 2, 2, 3, 1, 4, 2]

frequency = {} # Create an empty dictionary

for item in data:


if item in frequency:
frequency[item] += 1 # Increment if already exists
else:
frequency[item] = 1 # Add new item with count 1

print(frequency)

🧠 Output:
{1: 2, 2: 3, 3: 1, 4: 1}

🔸 Explanation:
• The key in the dictionary is the element from the list.
• The value is how many times that element appears.

✅ Alternate Method using .get():


A more concise version:
data = [1, 2, 2, 3, 1, 4, 2]
frequency = {}

for item in data:


frequency[item] = [Link](item, 0) + 1

print(frequency)

✅ Using [Link] (Shortcut method):


from collections import Counter

data = [1, 2, 2, 3, 1, 4, 2]

frequency = Counter(data)

print(frequency)

Output:
Counter({2: 3, 1: 2, 3: 1, 4: 1})

You can convert this to a normal dictionary using:


dict(frequency)
Defining Functions:
In Python, a function is a reusable block of code that performs a specific task. Functions help
organize code, improve readability, and reduce redundancy.

1. Defining a Function
A function in Python is defined using the def keyword.

Syntax:
def function_name(parameters):
# Function body (code block)
return value # (Optional)

• function_name – Name of the function.


• parameters – (Optional) Input values for the function.
• return – (Optional) Used to return a value.

2. Creating and Calling a Function


Example: A Simple Function
def greet():
print("Hello, welcome to Python!")

# Calling the function


greet()

Output:
Hello, welcome to Python!

3. Function with Parameters


Functions can take input parameters to make them more flexible.

Example: Function with One Parameter


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

greet("Ankit")
greet("Pankaj")

Output:
Hello, Ankit!
Hello, Pankaj!
Example: Function with Multiple Parameters
def add(a, b):
result = a + b
print("Sum:", result)

add(5, 10)
add(3, 7)

Output:
Sum: 15
Sum: 10

4. Function with Return Statement


A function can return a value using the return keyword.

Example: Returning a Value


def square(num):
return num * num

result = square(4)
print("Square:", result)

Output:
Square: 16

Example: Returning Multiple Values


def arithmetic_operations(a, b):
return a + b, a - b, a * b, a / b

add, sub, mul, div = arithmetic_operations(10, 2)


print(f"Addition: {add}, Subtraction: {sub}, Multiplication: {mul}, Division:
{div}")

Output:
Addition: 12, Subtraction: 8, Multiplication: 20, Division: 5.0

5. Default Parameter Values


Python allows functions to have default values for parameters.

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

greet() # Uses default value


greet("Ankit") # Overrides default value
Output:
Hello, Guest!
Hello, Ankit!

6. Keyword Arguments
Python allows passing arguments using keywords (named arguments).

Example:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")

student_info(age=20, name="Pankaj")

Output:
Name: Pankaj, Age: 20

7. Variable-Length Arguments (*args and **kwargs)


Python allows a function to accept arbitrary numbers of arguments using *args and
**kwargs.

Using *args (Non-Keyword Arguments)


Allows passing multiple values as a tuple.
def add_numbers(*args):
return sum(args)

print(add_numbers(2, 4, 6))
print(add_numbers(1, 3, 5, 7, 9))

Output:
12
25

Using **kwargs (Keyword Arguments)


Allows passing multiple key-value pairs.
def student_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

student_details(name="Ankit", age=22, course="Python")

Output:
name: Ankit
age: 22
course: Python

8. Lambda (Anonymous) Functions


A lambda function is a small, one-line function with no name.

Syntax:
lambda arguments: expression

Example:
square = lambda x: x * x
print(square(5))

Output:
25

Example: Lambda with Multiple Arguments


add = lambda a, b: a + b
print(add(3, 7))

Output:
10

9. Recursive Functions
A function can call itself, which is called recursion.

Example: Factorial Using Recursion


def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120

Output:
120

10. Function Scope and Lifetime


There are two types of variables in functions:
1. Local Variables (Defined inside a function, accessible only within it)
2. Global Variables (Defined outside a function, accessible throughout the program)

Example: Local Variable


def example():
x = 10 # Local variable
print("Inside function:", x)

example()
# print(x) # This would cause an error because x is local to the function.

Example: Global Variable


x = 10 # Global variable

def example():
print("Inside function:", x)

example()
print("Outside function:", x)

Output:
Inside function: 10
Outside function: 10

Modifying Global Variables Inside a Function


To modify a global variable inside a function, use the global keyword.
x = 10

def modify():
global x
x = 20

modify()
print(x) # Output: 20

Conclusion
Functions make Python programs modular, organized, and reusable.
• Use parameters for inputs.
• Use return for outputs.
• Use default arguments and keyword arguments for flexibility.
• Use *args and **kwargs for dynamic input.
• Use lambda functions for simple one-line functions.
• Use recursion for solving problems like factorials.
• Understand scope to manage variables properly.
**input(): is a built-in function

Syntax:
input(prompt)

• prompt (optional): A string that is displayed to the user before input is taken.

How it works:
• When input() is called, the program pauses and waits for the user to type something.

• After the user types input and presses Enter, the input is returned as a string.

Example:
name = input("Enter your name: ")
print("Hello,", name)

Output (if the user types "Ankit"):


Enter your name: Ankit
Hello, Ankit

Important Points:
1. Always returns a string
If you want a number, you need to convert it:
age = int(input("Enter your age: "))

2. Can be used for any kind of user input, such as strings, numbers, etc., depending on how
you process the result.

**Eval(): is a built-in function that takes a string and evaluates it as a Python expression, then
returns the result.

📘 Syntax:
eval(expression, globals=None, locals=None)

• expression: A string containing a valid Python expression.

• globals and locals (optional): Dictionaries used to define global and local variables.

🔹 Basic Example:
result = eval("3 + 4")
print(result) # Output: 7
The string "3 + 4" is evaluated as a real Python expression.

🔹 With Variables:
x = 10
y = 5
print(eval("x * y")) # Output: 50

🔹 Using with input():


You can combine input() and eval() to create a simple calculator:
expression = input("Enter an expression: ") # e.g., 2 + 3 * 4
print("Result:", eval(expression))

**print(): function in Python is a built-in function used to display output on the screen.

📘 Syntax:
print(*objects, sep=' ', end='\n', file=[Link], flush=False)

🔹 Most Common Use:


print("Hello, world!")

Output:
Hello, world!

🔹 Key Parameters:
Parameter Description
*objects One or more values to print
sep String inserted between values (default is a space)
end What to print at the end (default is newline \n)
file Where to send the output (default is the screen)
flush Whether to force the output to be written immediately
🔹 Examples:
Multiple values:
print("Name:", "Alice")
# Output: Name: Alice

Custom separator:
print("2025", "05", "24", sep="-")
# Output: 2025-05-24

No newline at the end:


print("Loading", end="...")
# Output: Loading...

🔹 Print Variables:
name = "Bob"
print("Hello,", name)
# Output: Hello, Bob

** count():
The count() method returns the number of non-overlapping times a substring appears in a
string.

📘 Syntax:
[Link](substring, start=0, end=len(string))

• substring: The text to search for.

• start (optional): The index to start searching from.

• end (optional): The index to stop searching.

✅ Example 1: Basic usage


text = "banana"
print([Link]("a")) # Output: 3
✅ Example 2: With start and end
text = "banana"
print([Link]("a", 2, 5)) # Output: 1 (only counts 'a' in "nan")

🔸 Case-sensitive:
text = "Hello hello"
print([Link]("hello")) # Output: 1 (does NOT count "Hello")

📌 Key Points:
• count() is case-sensitive.

• Returns 0 if the substring is not found.


• Works with any substring, not just single characters.

** find():
The find() method returns the index of the first occurrence of a substring in a string. If the
substring is not found, it returns -1.

📘 Syntax:
[Link](substring, start=0, end=len(string))

• substring: The string to search for.

• start (optional): Index to start the search.

• end (optional): Index to end the search.

✅ Example 1: Basic usage


text = "Hello world"
print([Link]("world")) # Output: 6

✅ Example 2: Not found


print([Link]("Python")) # Output: -1
✅ Example 3: With start and end
text = "banana"
print([Link]("a", 2)) # Output: 3 (starts searching from index 2)

🔸 Case-sensitive:
text = "Hello"
print([Link]("h")) # Output: -1 (because "h" ≠ "H")

🆚 find() vs index():
• find() returns -1 if not found.

• index() raises a ValueError if not found.

**rfind():
The rfind() method searches for a substring in a string from the right (end) and returns the
highest index where the substring is found.
If the substring is not found, it returns -1.

📘 Syntax:
[Link](substring, start=0, end=len(string))

• substring: The text to search for.

• start (optional): Starting index of the search.

• end (optional): Ending index of the search.

✅ Example 1: Basic usage


text = "banana"
print([Link]("a")) # Output: 5 (last 'a' is at index 5)

✅ Example 2: Substring not found


text = "banana"
print([Link]("z")) # Output: -1
✅ Example 3: With range
text = "banana"
print([Link]("a", 0, 4)) # Output: 3 (search only up to index 4)

🔸 Difference from find():


• find() searches from left to right (returns the first match).

• rfind() searches from right to left (returns the last match).

Example:
text = "hello hello"
print([Link]("l")) # Output: 2
print([Link]("l")) # Output: 9

**capitalize():
The capitalize() method returns a new string with the first character in uppercase and the
rest in lowercase.

📘 Syntax:
[Link]()

• It does not take any arguments.


• It does not change the original string (strings are immutable).

✅ Example 1: Basic usage


text = "hello world"
print([Link]()) # Output: "Hello world"

✅ Example 2: Already capitalized


text = "Python"
print([Link]()) # Output: "Python" (no change)

✅ Example 3: All uppercase


text = "WELCOME"
print([Link]()) # Output: "Welcome"
⚠️Important Notes:
• Only the first letter is made uppercase.
• All other letters become lowercase, even if they were uppercase before.
text = "hELLo PYTHON"
print([Link]()) # Output: "Hello python"

🔸 Compare with title():


• capitalize() affects only the first character of the string.

• title() capitalizes each word in the string.


text = "hello world"
print([Link]()) # Hello world
print([Link]()) # Hello World

**title():
The title() method returns a new string where the first letter of every word is capitalized,
and all other letters are lowercase.

📘 Syntax:
[Link]()

• No parameters.
• Returns a new string (does not change the original).

✅ Example 1: Basic usage


text = "hello world"
print([Link]()) # Output: "Hello World"

✅ Example 2: With mixed case


text = "pYthOn iS awEsoMe"
print([Link]()) # Output: "Python Is Awesome"

✅ Example 3: With punctuation


text = "welcome to cicst"
print([Link]()) # Output: "Welcome To Cicst"

🔸 Compare with capitalize():


text = "hello world"

print([Link]()) # Hello world


print([Link]()) # Hello World

**lower():
The lower() method returns a new string where all uppercase letters are converted to
lowercase.

📘 Syntax:
[Link]()

• No arguments.
• Does not modify the original string (strings are immutable).
• Returns a new string in all lowercase.

✅ Example 1: Basic usage


text = "HELLO WORLD"
print([Link]()) # Output: "hello world"

✅ Example 2: Mixed case


text = "PyThOn Is FuN"
print([Link]()) # Output: "python is fun"

✅ Example 3: No uppercase letters


text = "already lowercase"
print([Link]()) # Output: "already lowercase"

⚡ Use case:
• Useful for case-insensitive comparisons:
user_input = "YES"
if user_input.lower() == "yes":
print("User agreed!")

**upper():
The upper() method returns a new string with all characters converted to uppercase.

📘 Syntax:
[Link]()

• No arguments.
• Does not change the original string.
• Returns a new string with all uppercase letters.

✅ Example 1: Basic usage


text = "hello world"
print([Link]()) # Output: "HELLO WORLD"

✅ Example 2: Mixed case


text = "Python Is Fun"
print([Link]()) # Output: "PYTHON IS FUN"

✅ Example 3: Already uppercase


text = "ALREADY UPPER"
print([Link]()) # Output: "ALREADY UPPER"

⚡ Use Case:
• Helpful for case-insensitive comparison or formatting:
user_input = "yes"
if user_input.upper() == "YES":
print("User agreed!")
**swapcase():
The swapcase() method switches the case of each letter in a string:

• Uppercase letters become lowercase.


• Lowercase letters become uppercase.

📘 Syntax:
[Link]()

• No parameters.
• Returns a new string with cases swapped.
• Does not modify the original string.

✅ Example 1: Basic usage


text = "Hello World"
print([Link]()) # Output: "hELLO wORLD"

✅ Example 2: All uppercase


text = "PYTHON"
print([Link]()) # Output: "python"

✅ Example 3: Mixed characters


text = "123 Python!"
print([Link]()) # Output: "123 pYTHON!"

**islower():
The islower() method checks if all the alphabetic characters in the string are lowercase.

📘 Syntax:
[Link]()

• Returns True if all letters are lowercase.

• Returns False if there are any uppercase letters or no alphabetic characters at all.
✅ Example 1: All lowercase letters
text = "hello world"
print([Link]()) # Output: True

✅ Example 2: Contains uppercase letter


text = "Hello World"
print([Link]()) # Output: False

✅ Example 3: No letters (only numbers or symbols)


text = "12345!"
print([Link]()) # Output: False

**isupper():
The isupper() method checks if all the alphabetic characters in the string are uppercase.

📘 Syntax:
[Link]()

• Returns True if all letters are uppercase.

• Returns False if there are any lowercase letters or no alphabetic characters at all.

✅ Example 1: All uppercase letters


text = "HELLO WORLD"
print([Link]()) # Output: True

✅ Example 2: Contains lowercase letter


text = "Hello World"
print([Link]()) # Output: False

✅ Example 3: No letters (only numbers or symbols)


text = "12345!"
print([Link]()) # Output: False
**istitle():
The istitle() method checks if each word in the string starts with an uppercase letter
followed by all lowercase letters. In other words, it returns True if the string is in title case.

📘 Syntax:
[Link]()

• Returns True if the string is title-cased.

• Returns False otherwise.

✅ Example 1: Title case string


text = "Hello World"
print([Link]()) # Output: True

✅ Example 2: Not title case


text = "Hello world"
print([Link]()) # Output: False

✅ Example 3: Mixed case


text = "Hello World 123"
print([Link]()) # Output: True (numbers ignored)

⚠️Notes:
• Only alphabetic characters affect the result.
• Words are separated by spaces or non-letter characters.
• Words like "It's" become title case if "I" and "T" are uppercase, but "It's" is
considered title case by istitle() because of how Python treats apostrophes.
**replace():
The replace() method returns a new string where all occurrences of a specified substring are
replaced with another substring.

📘 Syntax:
[Link](old, new, count=-1)

• old: The substring you want to replace.

• new: The substring to replace with.

• count (optional): Maximum number of replacements. Default is -1 (replace all).

✅ Example 1: Replace all occurrences


text = "I like apples. Apples are sweet."
print([Link]("apples", "oranges"))
# Output: I like oranges. Apples are sweet.

Note: Case-sensitive — "apples" ≠ "Apples"

✅ Example 2: Replace with count limit


text = "one one one one"
print([Link]("one", "two", 2))
# Output: two two one one

✅ Example 3: Replace characters


text = "hello world"
print([Link]("l", "x"))
# Output: hexxo worxd

⚠️Important:
• replace() does not change the original string (strings are immutable).

• You must assign the result to a new variable or overwrite the original string if you want to
keep the changes.
text = "hello"
text = [Link]("l", "r")
print(text) # Output: herro
**strip():
The strip() method removes whitespace (spaces, tabs, newlines) from the beginning and end
of a string.

📘 Syntax:
[Link](chars=None)

• chars (optional): A string specifying the set of characters to remove from both ends. If
omitted, it removes whitespace by default.

✅ Example 1: Remove spaces from both ends


text = " hello world "
print([Link]()) # Output: "hello world"

✅ Example 2: Remove specific characters


text = "---hello---"
print([Link]("-")) # Output: "hello"

✅ Example 3: Remove multiple characters


text = "xyxzyHelloxy"
print([Link]("xy")) # Output: "zHello"

⚠️Notes:
• Only removes characters from start and end of the string, not inside.
• Does not modify the original string; returns a new one.

Related methods:
• lstrip() — removes from left/start only.

• rstrip() — removes from right/end only.


**lstrip():
The lstrip() method removes whitespace or specified characters from the left (start) of a
string.

📘 Syntax:
[Link](chars=None)

• chars (optional): A string of characters to remove from the start. If not provided, it
removes whitespace by default.

✅ Example 1: Remove spaces from the left


text = " hello world "
print([Link]()) # Output: "hello world "

✅ Example 2: Remove specific characters from the left


text = "---hello---"
print([Link]("-")) # Output: "hello---"

✅ Example 3: Remove multiple characters from the left


text = "xyxzyHelloxy"
print([Link]("xy")) # Output: "zzyHelloxy"

⚠️Notes:
• Only affects the start of the string.
• Characters inside or at the end remain unchanged.
• Returns a new string; original string is unchanged.
**rstrip():
The rstrip() method removes whitespace or specified characters from the right (end) of a
string.

📘 Syntax:
[Link](chars=None)

• chars (optional): A string of characters to remove from the end. If not provided, it removes
whitespace by default.

✅ Example 1: Remove spaces from the right


text = " hello world "
print([Link]()) # Output: " hello world"

✅ Example 2: Remove specific characters from the right


text = "---hello---"
print([Link]("-")) # Output: "---hello"

✅ Example 3: Remove multiple characters from the right


text = "xyxzyHelloxy"
print([Link]("xy")) # Output: "xyxzyHello"

⚠️Notes:
• Only removes characters from the end of the string.
• Characters at the start or inside the string stay the same.
• Returns a new string, original string stays unchanged.
**split():
The split() method splits a string into a list of substrings based on a separator (delimiter).

📘 Syntax:
[Link](separator=None, maxsplit=-1)

• separator (optional): The delimiter to split on. Default is any whitespace (spaces, tabs,
newlines).
• maxsplit (optional): Maximum number of splits to do. Default is -1 (no limit).

✅ Example 1: Split by space (default)


text = "Hello world, how are you?"
print([Link]())
# Output: ['Hello', 'world,', 'how', 'are', 'you?']

✅ Example 2: Split by comma


text = "apple,banana,cherry"
print([Link](","))
# Output: ['apple', 'banana', 'cherry']

✅ Example 3: Split with maxsplit


text = "one two three four"
print([Link](" ", 2))
# Output: ['one', 'two', 'three four']

**partition():
The partition() method splits a string into three parts based on the first occurrence of a
specified separator.

📘 Syntax:
[Link](separator)

• separator: The substring to search for (must be a string).

• Returns a tuple of three parts:


(part_before_separator, separator, part_after_separator)
✅ Example 1: Separator found
text = "apple,banana,cherry"
result = [Link](",")
print(result)
# Output: ('apple', ',', 'banana,cherry')

✅ Example 2: Separator not found


text = "apple banana cherry"
result = [Link](",")
print(result)
# Output: ('apple banana cherry', '', '')

✅ Example 3: Separator at the start


text = ",start with comma"
result = [Link](",")
print(result)
# Output: ('', ',', 'start with comma')

🔸 Difference from split():


• partition() splits only once at the first occurrence.

• Always returns a 3-tuple, even if separator is not found.


• Useful when you want to keep track of what’s before and after the separator.

**rpartition():
The rpartition() method splits a string into three parts based on the last occurrence of a
specified separator.

📘 Syntax:
[Link](separator)

• separator: The substring to search for (must be a string).

• Returns a tuple of three parts:


(part_before_separator, separator, part_after_separator)
✅ Example 1: Separator found at the end
text = "apple,banana,cherry"
result = [Link](",")
print(result)
# Output: ('apple,banana', ',', 'cherry')

✅ Example 2: Separator not found


text = "apple banana cherry"
result = [Link](",")
print(result)
# Output: ('', '', 'apple banana cherry')

✅ Example 3: Separator at the end


text = "end with comma,"
result = [Link](",")
print(result)
# Output: ('end with comma', ',', '')

🔸 Difference from partition():


• partition() splits at the first occurrence.

• rpartition() splits at the last occurrence.

• Both always return a 3-tuple.

**join():
The join() method combines (concatenates) elements of an iterable (like a list or tuple) into a
single string, with a specified separator between them.

📘 Syntax:
[Link](iterable)

• separator: The string that will be placed between the elements.

• iterable: A sequence like a list, tuple, or any iterable containing strings.

✅ Example 1: Join list of words with space


words = ["Hello", "world", "Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
# Output: "Hello world Python is fun"

✅ Example 2: Join with comma


fruits = ["apple", "banana", "cherry"]
result = ", ".join(fruits)
print(result)
# Output: "apple, banana, cherry"

✅ Example 3: Join characters with dash


chars = ['a', 'b', 'c']
print("-".join(chars))
# Output: "a-b-c"

⚠️Important:
• The iterable must contain only strings; otherwise, it raises a TypeError.

• You can convert non-strings using map(str, iterable) if needed.

Example with conversion:


numbers = [1, 2, 3]
print(", ".join(map(str, numbers)))
# Output: "1, 2, 3"

**isspace():
The isspace() method checks if all characters in the string are whitespace characters
(spaces, tabs, newlines, etc.).

📘 Syntax:
[Link]()

• Returns True if the string contains only whitespace characters and is not empty.

• Returns False otherwise.


✅ Example 1: Only spaces
text = " "
print([Link]()) # Output: True

✅ Example 2: Tabs and newlines


text = "\t\n"
print([Link]()) # Output: True

✅ Example 3: Contains non-whitespace characters


text = " hello "
print([Link]()) # Output: False

✅ Example 4: Empty string


text = ""
print([Link]()) # Output: False

⚡ Use case:
• Useful to check if a string is blank or contains only spaces/tabs/newlines before processing.

**isalpha():
The isalpha() method checks if all characters in the string are alphabetic letters (A-Z or a-z)
and the string is not empty.

📘 Syntax:
[Link]()

• Returns True if all characters are letters (no numbers, spaces, or symbols).

• Returns False if the string contains any non-letter characters or is empty.

✅ Example 1: Only letters


text = "Python"
print([Link]()) # Output: True
✅ Example 2: Letters and spaces
text = "Hello World"
print([Link]()) # Output: False (space is not a letter)

✅ Example 3: Letters and numbers


text = "Python3"
print([Link]()) # Output: False

✅ Example 4: Empty string


text = ""
print([Link]()) # Output: False

⚡ Use case:
• Useful to validate that a string contains only letters, like checking names or words.

**isdigit():
The isdigit() method checks if all characters in the string are digits (0–9) and the string is not
empty.

📘 Syntax:
[Link]()

• Returns True if every character is a digit (0 to 9).

• Returns False if there's anything else: letters, symbols, spaces, or the string is empty.

✅ Example 1: Only digits


text = "123456"
print([Link]()) # Output: True

✅ Example 2: Contains letters


text = "123abc"
print([Link]()) # Output: False
✅ Example 3: Contains space
text = "123 456"
print([Link]()) # Output: False

✅ Example 4: Empty string


text = ""
print([Link]()) # Output: False

🔸 Note:
• isdigit() checks only standard digits (0–9).

• If you want to handle numbers from other languages or numeral systems, you can use
isnumeric().

**isalnum():
The isalnum() method checks if all characters in a string are either letters (A–Z, a–z) or digits
(0–9), and the string is not empty.

📘 Syntax:
[Link]()

• Returns True if all characters are letters and/or digits.

• Returns False if the string contains spaces, symbols, or is empty.

✅ Example 1: Letters and digits


text = "Python123"
print([Link]()) # Output: True

✅ Example 2: Only letters


text = "Python"
print([Link]()) # Output: True
✅ Example 3: Only digits
text = "123456"
print([Link]()) # Output: True

❌ Example 4: Contains space or symbol


text = "Python 123"
print([Link]()) # Output: False

text = "Hello!"
print([Link]()) # Output: False

✅ Example 5: Empty string


text = ""
print([Link]()) # Output: False

🔎 Summary of Similar Methods:


Method Checks for
isalpha() Letters only (A–Z, a–z)
isdigit() Digits only (0–9)
isalnum() Letters or digits (no spaces/symbols)

**startswith():
The startswith() method checks if a string starts with a specified prefix (substring).

📘 Syntax:
[Link](prefix, start=0, end=len(string))

• prefix: The substring (or tuple of strings) to check at the beginning.

• start (optional): Index to start checking from.

• end (optional): Index to stop checking.

✅ Example 1: Basic usage


text = "Python is fun"
print([Link]("Python")) # Output: True
✅ Example 2: Case-sensitive check
text = "Python is fun"
print([Link]("python")) # Output: False

✅ Example 3: With start index


text = "Python is fun"
print([Link]("is", 7)) # Output: True

✅ Example 4: Using a tuple of prefixes


text = "[Link]"
print([Link](("ex", "test"))) # Output: True

⚠️Notes:
• It's case-sensitive.
• Often used to validate file types, command inputs, prefixes, etc.

**endswith():
The endswith() method checks if a string ends with a specified suffix (substring).

📘 Syntax:
[Link](suffix, start=0, end=len(string))

• suffix: The substring (or a tuple of substrings) to check.

• start (optional): Index to start checking from.

• end (optional): Index to stop checking.

✅ Example 1: Basic usage


text = "[Link]"
print([Link](".csv")) # Output: True

✅ Example 2: Case-sensitive
text = "[Link]"
print([Link](".pdf")) # Output: False

✅ Example 3: Using start and end indexes


text = "python_is_fun"
print([Link]("is", 7, 9)) # Output: True

✅ Example 4: Using a tuple of suffixes


filename = "[Link]"
print([Link]((".txt", ".docx"))) # Output: True

⚠️Notes:
• endswith() is case-sensitive.

• Commonly used to check file extensions, URL suffixes, or specific endings.

**encode():
The encode() method is used to convert a string (text) into bytes, using a specified encoding
format (like UTF-8).

📘 Syntax:
[Link](encoding='utf-8', errors='strict')

• encoding (optional): The encoding type to use (default is 'utf-8').

• errors (optional): How to handle encoding errors.

• 'strict' (default): Raises an error on bad characters.

• 'ignore': Skips invalid characters.

• 'replace': Replaces with '?' or another replacement character.

✅ Example 1: Encode to UTF-8 (default)


text = "Hello"
encoded = [Link]()
print(encoded)
# Output: b'Hello'
✅ Example 2: Encode with a different encoding
text = "café"
encoded = [Link]("utf-8")
print(encoded)
# Output: b'caf\xc3\xa9'

✅ Example 3: Handling encoding errors


text = "café"
encoded = [Link]("ascii", errors="ignore")
print(encoded)
# Output: b'caf'

encoded = [Link]("ascii", errors="replace")


print(encoded)
# Output: b'caf?'

📌 Why use encode()?


• Needed when working with:
• Files, networks, or APIs that expect bytes.
• Manual text-to-byte conversions.
• Data serialization.

🔁 decode() Method in Python


The decode() method is used to convert bytes back into a string using a specific character

🔹
encoding (like 'utf-8').

It's the opposite of encode().

📘 Syntax:
[Link](encoding='utf-8', errors='strict')

• encoding (optional): The encoding type to use. Default is 'utf-8'.

• errors (optional):

• 'strict' (default): Raises an error on decoding issues.

• 'ignore': Skips invalid bytes.

• 'replace': Replaces problematic bytes with '�'.


✅ Example 1: Decode UTF-8 encoded bytes
data = b'Hello'
text = [Link]()
print(text)
# Output: Hello

✅ Example 2: Decode non-ASCII bytes


data = b'caf\xc3\xa9' # UTF-8 encoding of "café"
text = [Link]("utf-8")
print(text)
# Output: café

✅ Example 3: Handle decoding errors


data = b'caf\xe9' # Invalid UTF-8 byte
text = [Link]("utf-8", errors="replace")
print(text)
# Output: caf� (� shows replacement character)

🔄 Summary:
Action Method Result Type
String → Bytes .encode() bytes
Bytes → String .decode() str

**Slicing:
String slicing means extracting a part (or "slice") of a string using index positions.

📘 Syntax:
string[start:end:step]

• start – Index to begin slicing (inclusive)

• end – Index to stop slicing (exclusive)

📌
• step – (Optional) Step size or direction

Python string indices start at 0.


✅ Example String:
text = "Python Programming"

🔹 Basic Slicing:
print(text[0:6]) # Output: Python
print(text[7:18]) # Output: Programming

🔹 Omitting start or end:


print(text[:6]) # From beginning to index 5 → Python
print(text[7:]) # From index 7 to end → Programming

🔹 Using negative indices:


print(text[-11:]) # Output: Programming
print(text[:-12]) # Output: Python

🔹 Step value:
print(text[::2]) # Every 2nd character → Pto rgamn
print(text[::-1]) # Reversed string → gnimmargorP nohtyP

⚠️Out-of-range indexes:
Python handles them gracefully — no error!
print(text[0:100]) # Output: entire string

**Membership Operators:
Membership operators are used to check whether a character or substring is present in a string.

🔑 Operators:
Operator Meaning
in Returns True if found
not in Returns True if not found
✅ Example:
text = "Python is fun"

print("Python" in text) # Output: True


print("Java" in text) # Output: False

print("fun" not in text) # Output: False


print("boring" not in text) # Output: True

🔍 Common Uses:
• Searching in strings
• Validating input
• Conditionals (if, while, etc.)

🔁 With if statement:
user_input = "hello world"
if "world" in user_input:
print("Word found!")
else:
print("Not found!")

**Pattern Matching:
In Python, pattern matching refers to checking whether a string matches a specific format,
structure, or pattern. This is commonly done using:

✅ 1. Basic String Pattern Matching


Using in, startswith(), endswith(), and slicing:
text = "hello world"

# Check if "world" is in text


print("world" in text) # True

# Check if text starts with "hello"


print([Link]("hello")) # True

# Check if text ends with "world"


print([Link]("world")) # True
✅ 2. Advanced Pattern Matching: re module (Regular Expressions)

📘
The re module is used for complex pattern matching.

First, import the module:


import re

📌 Common Functions from re:


Function Description
[Link]() Checks if pattern exists anywhere in the string
[Link]() Checks if pattern matches from the start
[Link]() Returns all non-overlapping matches

🔹 Example 1: Check for digits


import re

text = "Roll number is 12345"


match = [Link](r"\d+", text) # \d+ means one or more digits
print([Link]()) # Output: 12345

🔹 Example 2: Email validation


email = "test@[Link]"
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"

if [Link](pattern, email):
print("Valid email")
else:
print("Invalid email")

🔹 Example 3: Find all vowels


text = "Hello Python"
vowels = [Link](r"[aeiouAEIOU]", text)
print(vowels) # Output: ['e', 'o', 'o']

✳️Special Symbols in Regex Patterns:


Symbol Meaning
. Any character
^ Start of string
$ End of string
* 0 or more repetitions
+ 1 or more repetitions
Symbol Meaning
? 0 or 1 repetition
\d Any digit (0-9)
\w Any word character (a-z, A-Z, 0-9, _)
[] Any one of the characters inside

**eval() Function in Python (Numeric Context)


The eval() function in Python evaluates a string as a Python expression and returns the result.

📘 Syntax:
eval(expression)

• expression: A string containing a valid Python expression (e.g., math operations,


variables, etc.).

✅ Example 1: Basic arithmetic


result = eval("10 + 5 * 2")
print(result) # Output: 20

✅ Example 2: Using variables


x = 7
result = eval("x * 3 + 1")
print(result) # Output: 22

✅ Example 3: From user input


expr = input("Enter an expression: ") # e.g., 8 + 4 / 2
print("Result:", eval(expr))

⚠️Warning:
• eval() can be dangerous if used with untrusted input.

• It can execute any code, not just math:


eval("__import__('os').system('rm -rf /')") # ❌ VERY DANGEROUS
🔐 Safer Alternatives:
If you only need to evaluate math expressions from user input, consider using:
• ast.literal_eval() (for safe literals only)

• A math parser library like sympy, numexpr, or simpleeval

✅ Use Case:
Useful for evaluating numeric input, calculator-like programs, and dynamic expressions — but
always with caution.

**max():
The max() function returns the largest item from an iterable (like a list, tuple) or the largest of
two or more arguments.

📘 Syntax:
1. With iterable:
max(iterable, *[, key, default])

2. With multiple arguments:


max(arg1, arg2, *args[, key])

• key (optional): A function to customize comparison.

• default (optional): Value to return if the iterable is empty (Python 3.4+).

✅ Example 1: Max in a list


numbers = [10, 5, 8, 20, 3]
print(max(numbers)) # Output: 20

✅ Example 2: Max of multiple arguments


print(max(4, 15, 9)) # Output: 15

✅ Example 3: Using key function


words = ["apple", "banana", "cherry"]
print(max(words, key=len)) # Output: banana (longest word)
✅ Example 4: With empty iterable and default
print(max([], default=0)) # Output: 0

⚠️Notes:
• Raises ValueError if called on an empty iterable without a default.

• Works with numbers, strings, and any comparable items.

**min():
The min() function returns the smallest item from an iterable (like a list, tuple) or the smallest of
two or more arguments.

📘 Syntax:
1. With iterable:
min(iterable, *[, key, default])

2. With multiple arguments:


min(arg1, arg2, *args[, key])

• key (optional): Function to customize comparison.

• default (optional): Value to return if the iterable is empty (Python 3.4+).

✅ Example 1: Min in a list


numbers = [10, 5, 8, 20, 3]
print(min(numbers)) # Output: 3

✅ Example 2: Min of multiple arguments


print(min(4, 15, 9)) # Output: 4

✅ Example 3: Using key function


words = ["apple", "banana", "cherry"]
print(min(words, key=len)) # Output: apple (shortest word)
✅ Example 4: With empty iterable and default
print(min([], default=0)) # Output: 0

⚠️Notes:
• Raises ValueError if called on an empty iterable without a default.

• Works with numbers, strings, and any comparable items.

**pow():
The pow() function calculates the power of a number, i.e., it raises a base number to the
exponent.

📘 Syntax:
pow(base, exponent, mod=None)

• base: The number to be raised.

• exponent: The power to raise the base to.

• mod (optional): If provided, computes (base ** exponent) % mod efficiently.

✅ Example 1: Basic power calculation


print(pow(2, 3)) # Output: 8 (2^3 = 8)

✅ Example 2: Using modulus (mod)


print(pow(2, 3, 5)) # Output: 3 (because 2^3 = 8; 8 % 5 = 3)

✅ Example 3: Large exponent with modulus


print(pow(5, 117, 19)) # Efficiently computes (5^117) % 19

⚠️Notes:
• pow() is faster than using ** operator especially with the mod argument.
**round():
The round() function rounds a floating-point number to a specified number of decimal places.

📘 Syntax:
round(number, ndigits=0)

• number: The number you want to round.

• ndigits (optional): Number of decimal places to round to. Defaults to 0 (round to nearest
integer).

✅ Example 1: Round to nearest integer


print(round(3.6)) # Output: 4
print(round(3.2)) # Output: 3

✅ Example 2: Round to 2 decimal places


print(round(3.14159, 2)) # Output: 3.14

✅ Example 3: Round to negative decimals (tens, hundreds)


print(round(1234, -2)) # Output: 1200 (rounds to nearest hundred)

⚠️Notes:
• If ndigits is omitted or zero, returns an int.

• Rounding behavior: Python rounds ties to the nearest even number (bankers rounding).

**int():
The int() function converts a value to an integer.

📘 Syntax:
int(x=0, base=10)
• x (optional): The value to convert (string, float, etc.). Defaults to 0.

• base (optional): Number base if x is a string (like 2 for binary, 16 for hex). Defaults to 10.

✅ Example 1: Convert float to int


print(int(3.7)) # Output: 3 (truncates decimal part)

✅ Example 2: Convert string to int


print(int("123")) # Output: 123

✅ Example 3: Convert string with base


print(int("1010", 2)) # Output: 10 (binary string to decimal)
print(int("FF", 16)) # Output: 255 (hex string to decimal)

✅ Example 4: Default value


print(int()) # Output: 0

⚠️Notes:
• int() truncates towards zero when converting floats.

• Raises ValueError if string is not a valid number in given base.

**random():
The random() function is part of the random module and returns a random float number
between 0.0 (inclusive) and 1.0 (exclusive).

📘 How to use:
import random

value = [Link]()
print(value) # Output: a random float like 0.37444887175646646
Key points:
• Returns a float x such that 0.0 <= x < 1.0.

• Commonly used to generate random probabilities or scale to other ranges.

Example: Generate random number between 0 and 10


import random

value = [Link]() * 10
print(value) # e.g., 7.3456789 (float between 0 and 10)

Other useful functions in random module:


• [Link](a, b) — random integer between a and b inclusive.

• [Link](seq) — randomly select an element from a sequence.

• [Link](list) — shuffle a list in place.

**ceil():
The ceil() function returns the smallest integer greater than or equal to a given number (i.e.,
it rounds a number up).

📘 Usage:
• ceil() is part of the math module.

• You need to import it before use.


import math

result = [Link](4.2)
print(result) # Output: 5

✅ Examples:
import math

print([Link](3.1)) # 4
print([Link](7.9)) # 8
print([Link](-2.3)) # -2 (rounds up towards positive infinity)
🔍 Difference from floor():
• ceil() rounds up

• floor() rounds down

**floor():
The floor() function returns the largest integer less than or equal to a given number (i.e., it
rounds a number down).

📘 Usage:
• floor() is part of the math module.

• You need to import it before use.


import math

result = [Link](4.7)
print(result) # Output: 4

✅ Examples:
import math

print([Link](3.9)) # 3
print([Link](7.1)) # 7
print([Link](-2.3)) # -3 (rounds down towards negative infinity)

🔍 Difference from ceil():


• floor() rounds down

• ceil() rounds up
** sqrt():
The sqrt() function calculates the square root of a number.

📘 Usage:
• sqrt() is part of the math module.

• You must import math before using it.


import math

result = [Link](16)
print(result) # Output: 4.0

✅ Examples:
import math

print([Link](25)) # 5.0
print([Link](2)) # 1.4142135623730951 (approximate)
print([Link](0)) # 0.0

⚠️Note:
• sqrt() only works with non-negative numbers.

• Passing a negative number raises a ValueError.

**Date & Time Functions:


Python provides powerful modules to work with date and time, mainly:
• datetime
• time
• calendar

1. datetime module
Common classes:
• [Link] — Represents a date (year, month, day)
• [Link] — Represents time (hour, minute, second)

• [Link] — Combines date and time

✅ Examples:
from datetime import datetime, date, time

# Current date and time


now = [Link]()
print(now) # e.g., 2025-05-24 15:30:10.123456

# Current date only


today = [Link]()
print(today) # e.g., 2025-05-24

# Create a specific date


my_bday = date(1995, 12, 15)
print(my_bday) # 1995-12-15

# Create a specific time


t = time(14, 30, 45)
print(t) # 14:30:45

Date formatting and parsing:


now = [Link]()

# Format date/time as string


formatted = [Link]("%Y-%m-%d %H:%M:%S")
print(formatted) # e.g., "2025-05-24 15:30:10"

# Parse string back to datetime


dt = [Link]("2025-05-24 15:30:10", "%Y-%m-%d %H:%M:%S")
print(dt)

Date arithmetic:
from datetime import timedelta

today = [Link]()
tomorrow = today + timedelta(days=1)
print(tomorrow) # Tomorrow's date

# Difference between dates


diff = tomorrow - today
print([Link]) # 1

2. time module
• Deals mostly with timestamps and delays.
import time

print([Link]()) # Current time in seconds since epoch (Jan 1, 1970)

[Link](2) # Pause program for 2 seconds


print("Waited for 2 seconds")

3. calendar module
• Provides calendar-related functions.
import calendar

print([Link](2025, 5))
# Prints the calendar for May 2025

**Recursion:
Recursion is a programming technique where a function calls itself to solve smaller instances of
the same problem until it reaches a base case.

Key Points:
• Every recursive function needs a base case to stop.
• Each recursive call should move towards that base case.
• Useful for problems like factorial, Fibonacci, tree traversals, etc.

Example 1: Factorial using recursion


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

print(factorial(5)) # Output: 120

How it works:
• factorial(5) calls factorial(4)

• factorial(4) calls factorial(3) ... and so on


• Once n is 0, base case returns 1

• Then it returns back up multiplying all values

Example 2: Fibonacci sequence using recursion


def fibonacci(n):
if n <= 1:
return n # Base cases: 0 and 1
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive calls

print(fibonacci(6)) # Output: 8

Important Notes:
• Recursive calls can be expensive in terms of time and memory.
• Use recursion when it makes the solution simpler and clearer.
• For large inputs, consider iterative solutions or memoization (caching results).

You might also like