0% found this document useful (0 votes)
7 views16 pages

Complete Python Notes - All Topics (Class 11)

wow

Uploaded by

drishtirajora01
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)
7 views16 pages

Complete Python Notes - All Topics (Class 11)

wow

Uploaded by

drishtirajora01
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
You are on page 1/ 16

Complete Python Notes — All Topics You Asked

(Class 11)
These notes cover everything you asked in the chat: Python basics, data types, escape sequences, punctuators,
keywords, operators (all kinds), type() and conversions, sequences, slicing & range (special focus), control
statements (if/else/elif/nested), loops (for/while/fixed & unfixed iteration), break/continue/else with loops,
augmented assignment, nested loops, strings (assignment, traversal, slicing, built-in functions) and practical
examples. Detailed definitions, examples, common errors and exam/viva tips are included.

1. Quick Introduction & Running Python


What is Python? - High-level, interpreted, general-purpose language. Readable, dynamically typed, and
widely used.

Running Python programs - IDLE (Python’s default editor): Create file → Save as filename.py → Run
Module (F5). If F5 does nothing, make sure file is saved and you're in IDLE editor. Some laptops require
Fn+F5 for function keys. - Terminal / Command Prompt: python filename.py or py
filename.py . - Other editors/IDEs (VS Code, PyCharm) have their own Run settings — F5 may be
mapped differently.

Troubleshooting if F5 isn’t running in IDLE: - Ensure the file is saved with .py extension. - Open file in
IDLE (right-click → Open With → IDLE). - If python --version fails in terminal, Python may not be
installed or PATH not set.

2. Identifiers, Keywords & Punctuators


Identifier (variable/function/class names) - Rules: Can contain letters (a–z, A–Z), digits (0–9) and
underscore _ . - Cannot start with a digit. - Case-sensitive ( age ≠ Age ). - Cannot be a keyword.

Keywords - Reserved words that have special meaning and cannot be used as identifiers. Examples:
False , True , None , and , or , not , if , else , elif , for , while , break , continue ,
class , def , return , import , from , in , is , lambda , with , try , except , finally ,
pass , raise , global , nonlocal , yield , etc. - Example: class = 5 is invalid because class is
a keyword used to define classes.

Punctuators (symbols used in syntax) - () parentheses — function calls, tuple creation, order of
operations. - [] square brackets — lists, indexing, slicing. - {} curly braces — dictionaries and sets
(literal syntax). - : colon — start of an indented block (after if , for , def , class , etc.) and used in
dicts. - , comma — separator for items. - . dot — attribute or method access (e.g., str.upper ). - =

1
assignment operator. - ; statement separator (rare in Python; usually avoided). - _ underscore — valid in
identifiers and special names like __init__ .

3. Escape Sequences (in strings)


Escape sequences are special character combinations starting with a backslash \ used inside strings.

Common escape sequences: - \n → newline - \t → tab - \\ → backslash - \' → single quote - \" →
double quote - \r → carriage return (rarely used) - \b → backspace (removes previous char)

Examples:

print("Hello\nWorld") # prints Hello then newline then World


print('It\'s OK') # prints It's OK
print("C:\\Users\\Drishti") # prints C:\Users\Drishti

4. Data Types — Definitions, Properties &


Examples
Data type: classification of data that tells Python what operations are allowed on that data and how it is
stored.

4.1 Basic (Atomic) Data Types


• int — integers: 0 , -5 , 100 .
• float — floating-point numbers (decimals): 3.14 , -0.5 .
• complex — complex numbers: 3+5j (real + imag * j).
• bool — boolean values: True or False (internally 1 and 0 ).
• str — string: sequence of characters: 'hello' , "Python" .
• NoneType — single value None representing no value.

Check type:

x = 10
print(type(x)) # <class 'int'>

2
4.2 Collection Types (Sequences & Mappings)
• list — ordered, mutable collection: [1, 2, 'a'] .
• tuple — ordered, immutable collection: (1, 2, 3) .
• set — unordered, unique elements: {1, 2, 3} .
• dict — key-value mapping: {'name': 'Drishti', 'age': 15} .
• range — immutable sequence of numbers (commonly used in loops).
• str is also a sequence (immutable) of characters.

Mutability - Mutable: list, set, dict (you can change contents in place). - Immutable: int, float, bool, str, tuple,
range (you can't change the object; you can create a new one).

Important built-ins: len() returns length, min() , max() , sum() (on numeric sequences), indexing
seq[index] and slicing seq[start:stop:step] .

5. type() , id() and isinstance()


• type(obj) → returns the data type/class of obj .
• id(obj) → returns a unique integer (address in CPython) that identifies object in memory.
• isinstance(obj, Class) → checks if obj is instance of Class (useful for type checking).

x = 10
print(type(x)) # <class 'int'>
print(id(x)) # some integer (memory id)
print(isinstance(x,int))# True

6. Type Conversion (Casting)


6.1 Implicit Conversion (Coercion)
• Python sometimes converts smaller/compatible types to bigger ones automatically (e.g., int +
float → float ).

x = 5 # int
y = 2.5 # float
z = x + y # z becomes float: 7.5

6.2 Explicit Conversion (Casting)


• Use functions: int() , float() , complex() , str() , bool() .

3
int(3.9) # 3
float(5) # 5.0
int('10') # 10
str(12) # "12"
complex(2,3) # (2+3j)

Note: input() returns a string — convert to int or float when needed.

7. Operators (Complete Breakdown)


An operator performs operations on values/operands. Python supports many operator types.

7.1 Arithmetic Operators


• + addition
• - subtraction
• * multiplication
• / division (always float)
• // floor division (quotient, integer part)
• % modulus (remainder)
• ** exponentiation (power)

Examples:

5 + 3 # 8
10 / 3 # 3.333333... (float)
10 // 3 # 3
10 % 3 # 1
2 ** 4 # 16

7.2 Relational (Comparison) Operators


• < , > , <= , >= , == (equality), != (not equal)
• Result is True or False .

5 > 2 # True
5 == 5 # True

7.3 Logical Operators


• and , or , not operate on boolean expressions.

4
(5>2) and (3<4) # True
not (5>2) # False

7.4 Assignment Operators


• = basic assignment.
• Augmented assignment operators: combine an operation with assignment:
• += -= *= /= //= %= **=

Example:

x = 10
x += 5 # now x = 15
x *= 2 # now x = 30

Augmented operators work with mutables too — with lists you can do lst += [4] which modifies in
place.

7.5 Membership Operators


• in , not in — test membership in sequences or containers.

"a" in "apple" # True


3 in [1,2,3] # True

7.6 Identity Operators


• is , is not — check whether two references point to the same object (same memory id), not
just equal value.

x = [1,2]
y = x
z = [1,2]
print(x is y) # True
print(x is z) # False

7.7 Operator Precedence (important for expressions)


• Operators have precedence; arithmetic ** highest (among arithmetic), then * / // % , then +
- , then relational, logical. Use parentheses () to control evaluation.

Example:

5
2 + 3 * 4 # 14 (multiplication before addition)
(2 + 3) * 4 # 20

8. Augmented Assignment Operators (Detailed)


Definition: shorthand for performing operation and assignment in one step.

List & equivalent: - x += y → x = x + y - x -= y → x = x - y - x *= y → x = x * y -


x /= y → x = x / y (float division) - x //= y → x = x // y (floor division) - x %= y →
x = x % y - x **= y → x = x ** y

Notes: - For mutable objects (lists, dicts), += often modifies in place instead of creating a new object. -
Useful in loops for counters and accumulators.

Example:

sum = 0
for i in range(1, 6):
sum += i
print(sum) # 15

9. Sequences (definition & types)


Sequence: an ordered collection of elements that can be indexed and sliced.

Common sequence types: - str — immutable sequence of characters. - list — mutable sequence. -
tuple — immutable sequence. - range — immutable sequence of numbers (useful with for ).

Common operations on sequences: - Indexing: seq[i] (0-based). Negative indexing allowed: seq[-1]
last element. - Slicing: seq[start:stop:step] (returns same type for list/tuple/str — a sub-sequence). -
Concatenation + , repetition * , membership in .

10. Slicing — In-Depth (Special focus)


Definition: Slicing extracts part of a sequence returning a new sequence of the same general type
(string→string, list→list, tuple→tuple).

6
Syntax: sequence[start:stop:step] - start (inclusive) default 0 if omitted (or len+start if
negative). - stop (exclusive) default len(sequence) if omitted. - step default 1 . If step is
negative, slicing goes backwards.

Important properties: - start index included; stop index excluded. So a[0:3] includes indices
0,1,2 . - Values out of bounds are handled gracefully (no IndexError on slicing) — slicing truncates to
sequence boundaries. - a[:] returns a shallow copy (for mutable sequences). - Reversing a sequence:
a[::-1] .

Examples:

s = "PYTHON"
print(s[0:3]) # 'PYT' (0,1,2)
print(s[:4]) # 'PYTH' (start omitted)
print(s[2:]) # 'THON' (stop omitted)
print(s[::2]) # 'PTO' (every 2nd character)
print(s[::-1]) # 'NOHTYP' (reverse string)
print(s[-3:-1]) # 'HO' (negative indices)

Slicing with lists:

lst = [10,20,30,40,50]
print(lst[1:4]) # [20, 30, 40]
print(lst[::-1]) # [50, 40, 30, 20, 10]

Common exam/viva points: - Remember the stop is excluded. A common error is to expect inclusion. -
Reversal: seq[::-1] — very useful trick. - Step value can be any non-zero integer; negative reverses
direction.

11. range() — Deep Dive (Special focus)


range() produces an immutable sequence of numbers and is memory efficient. Often used with for
loops.

Forms: - range(stop) — numbers from 0 to stop-1 . - range(start, stop) — numbers from


start to stop-1 . - range(start, stop, step) — uses step increment (can be negative for
descending sequences).

Behavior notes: - stop is exclusive. - range(5) is equivalent to 0,1,2,3,4 . - range(2, 8, 2)


produces 2,4,6 .

7
Step and omitting expressions: - Omitting start defaults to 0 . - Omitting step defaults to 1 . -
Negative step (e.g., range(10, 0, -2) ) counts down: 10,8,6,4,2 .

Examples:

for i in range(5): print(i) # 0..4


for i in range(2, 7): print(i) # 2..6
for i in range(1, 10, 2): print(i) # odd numbers 1..9
for i in range(10, 0, -2): print(i) # 10,8,6,4,2

Practical uses: - Looping fixed number of times, indexing into lists, generating sequences for patterns.

12. Control Flow — if , if-else , if-elif-else ,


nested if
Decision making lets the program run different code paths.

12.1 if statement

if condition:
statements

- If condition evaluates to True , the indented block runs; otherwise skipped.

12.2 if-else statement

if condition:
# True block
else:
# False block

12.3 if-elif-else statement

if cond1:
# block1
elif cond2:
# block2

8
elif cond3:
# block3
else:
# fallback

- Python evaluates top to bottom and runs the first True block only.

12.4 Nested if (if inside if)


• Used when decisions depend on previous decisions.

if age >= 18:


if citizen == 'Indian':
print('Can vote in India')
else:
print('Cannot vote in India')
else:
print('Too young')

Important: Indentation matters — Python uses indentation to group statements.

13. Loops — for , while , Break, Continue, else


with loops, Finite vs Infinite, Interconversion
13.1 Concept: Fixed vs Unfixed Iteration
• Fixed iterative loop: number of iterations known or controlled — use for (with range ).
• Unfixed iterative loop: iterate until a condition becomes False — use while .

13.2 for loop (fixed iterations)

for item in sequence:


statements

- Iterate over any sequence — list, tuple, string, range. Commonly used with range() for numeric
sequences.

13.3 while loop (unfixed iterations)

9
while condition:
statements

- Condition is evaluated before each iteration. - Must ensure condition will become False at some point to
avoid infinite loop, unless infinite is intended.

13.4 break
• Immediately exits the innermost loop.

for i in range(1,10):
if i == 5:
break
print(i) # prints 1..4

13.5 continue
• Skips rest of current iteration, proceeds to next iteration.

for i in range(1,6):
if i == 3:
continue
print(i) # prints 1 2 4 5

13.6 else with loops


• else block after a loop runs only when the loop finishes normally (no break ).

for i in range(3):
print(i)
else:
print("Done") # prints Done because loop ended normally

for i in range(3):
if i == 1:
break
else:
print("Will not print") # else not executed because break occurred

13.7 Finite vs Infinite loops


• Finite: loop has a condition or iteration that will eventually stop.

10
• Infinite: loop with condition always true ( while True ) or never updated variable — program runs
forever until externally stopped (or break used inside).

Example of infinite loop:

while True:
print("Hello") # runs forever unless break used

13.8 Interconversion of loops


• Any for loop can be rewritten using while and vice versa by manually handling loop variable
and increment.

for → while example:

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

# Equivalent while
i = 1
while i <= 5:
print(i)
i += 1

14. Nested Loops — Elaborately


Definition: A loop inside another loop. For each iteration of the outer loop, the inner loop runs completely.

Use cases: building patterns (stars/digits), tables, matrix traversal, pairwise comparisons.

Example:

for i in range(3): # outer


for j in range(2): # inner
print(f"i={i}, j={j}")

Output order shows inner loop completes for each outer iteration.

Nested loops with break/continue: - break in inner loop only breaks inner loop; you can use flags or
break from outer using exceptions or additional conditions.

11
Patterns (classic examples): Right-angle triangle of * :

n = 5
for i in range(1, n+1):
for j in range(i):
print('*', end=' ')
print()

Multiplication table for 1..n (matrix style):

n = 5
for i in range(1, n+1):
for j in range(1, 11):
print(i*j, end='\t')
print()

15. Strings — Assignment, Traversal, Slicing, Built-


in Methods
15.1 Assigning strings
• Strings can be defined with single '...' , double "..." , or triple quotes '''...''' /
"""...""" (multi-line).

s1 = 'hello'
s2 = "Python"
s3 = '''This is
multi-line'''

15.2 Traversing strings (character by character)


Using for loop:

s = "Drishti"
for ch in s:
print(ch)

Using while loop with index:

12
s = 'Python'
i = 0
while i < len(s):
print(s[i])
i += 1

15.3 String indexing & slicing (recap)


• s[index] access single character.
• Negative indices allowed: s[-1] last char.
• Slicing: s[start:stop:step] — returns substring.

Examples:

s = "PROGRAM"
print(s[0]) # 'P'
print(s[-1]) # 'M'
print(s[1:4]) # 'ROG'
print(s[::-1])# reversed

15.4 Built-in string methods (common & useful)


• s.upper() → uppercase
• s.lower() → lowercase
• s.title() → title case (first letter capitalized for words)
• s.capitalize() → only first character capitalized
• s.strip() → remove leading/trailing whitespace
• s.lstrip() , s.rstrip() → left/right strip
• s.split(sep) → returns list of substrings
• sep.join(list_of_strings) → join with separator
• s.replace(old, new) → replace occurrences
• s.find(sub) → index of first occurrence or -1 if not found
• s.count(sub) → number of occurrences
• s.isalpha() , s.isdigit() , s.isalnum() → checks for alphabetic, digits, alphanumeric
• s.startswith(prefix) , s.endswith(suffix) → boolean checks
• ord(ch) → numeric Unicode code point for a character
• chr(code) → character for Unicode code point

Examples:

s = " Hello World "


print(s.strip()) # "Hello World"

13
print("apple,banana".split(',')) # ['apple', 'banana']
print("hello".upper()) # 'HELLO'
print("abc123".isalnum()) # True

16. Practice Examples & Small Programs (with


explanation)
16.1 Multiplication table (any size)

n = int(input("Enter number for table: "))


limit = int(input("Up to which multiple? "))
for i in range(1, limit+1):
print(f"{n} x {i} = {n*i}")

16.2 Table of tables (1 to n, each up to 10)

n = int(input("Enter n: "))
for i in range(1, n+1):
for j in range(1, 11):
print(i*j, end='\t')
print()

16.3 Reverse a string using slicing

s = input("Enter string: ")


print(s[::-1])

16.4 Count vowels in a string (traversal)

s = input("Enter text: ").lower()


vowels = 'aeiou'
count = 0
for ch in s:
if ch in vowels:
count += 1
print("Vowel count:", count)

14
16.5 Use break & else with a loop: search element

arr = [10, 25, 40, 55]


key = 25
for x in arr:
if x == key:
print("Found")
break
else:
print("Not Found")

17. Common Errors, Pitfalls & Tips (Exam/Viva


Friendly)
Common mistakes: - Using keywords as identifiers ( class , if , for ). - Forgetting that stop in
slicing/range is exclusive. - Trying to modify immutable types (e.g., s[0] = 'H' for string) - Not
converting input string to integer before arithmetic ( int(input()) ). - Index out of range when trying to
access invalid index (but slicing is safe). - Infinite loops due to not updating loop variables in while . -
Confusing is and == — is checks identity (same object), == checks value equality.

Good habits: - Use meaningful variable names. - Keep consistent indentation (4 spaces is common). - Use
comments to explain logic for complex parts. - Use functions ( def ) to modularize repeated code. - Test
code with edge cases (empty lists, zero, negative steps).

Viva tips: - Be ready to explain why a[::-1] reverses a sequence (step = -1 means start from end moving
backwards). - Show the difference between list[:] and list (copy vs reference) — list[:] returns
a shallow copy. - Explain range(1,6) gives 1..5 because stop is excluded.

18. Short Practice Set (Self-test)


1. What is output of print("abc"[::-1]) ?
2. How to generate even numbers from 2 to 20 using range() ?
3. Write if-elif-else to print grade for marks 0–100.
4. How does continue differ from break ?
5. Write a nested loop to print a 5x5 star square.
6. Convert string '45.6' to float and then to int — what happens?
7. What does len([1,2,3][:2]) return?
8. Explain difference between is and == with an example.

(Answers are easy to verify by trying in IDLE — practice is the fastest way to learn.)

15
19. Final Notes & How I can help next
• These notes are comprehensive for Class 11 basics and cover every topic you asked in the chat.
• If you want, I can:
• Convert these into a printable PDF or a one-page mindmap.
• Create a practice worksheet with solutions (code + explanation).
• Make a flowchart-style visual for control-flow and loops.

Good luck, Drishti — tell me which extra format (PDF / worksheet / mindmap) you want and I’ll prepare it
next.

16

You might also like