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

Short Note

The document provides concise notes on various Python programming concepts including identifiers, input/output, operators, flow control, pattern printing, modules, functions, lists, membership operators, list slicing, searching algorithms, and tuples. It covers rules, properties, and examples for each topic, emphasizing key points and best practices. This serves as a comprehensive reference for Python programming fundamentals.

Uploaded by

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

Short Note

The document provides concise notes on various Python programming concepts including identifiers, input/output, operators, flow control, pattern printing, modules, functions, lists, membership operators, list slicing, searching algorithms, and tuples. It covers rules, properties, and examples for each topic, emphasizing key points and best practices. This serves as a comprehensive reference for Python programming fundamentals.

Uploaded by

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

✏️Short Notes – Python Identifiers

 Identifiers are the names used to represent variables, functions, classes, modules, etc.

 Must start with a letter (A–Z or a–z) or underscore (_).

 Can contain letters, digits, and underscores.

 Cannot start with a digit or include special characters like @, $, %, etc.

 Python identifiers are case-sensitive: Name, name, and NAME are all different.

 Keywords (like for, if, class) cannot be used as identifiers.

 Use .isidentifier() to check if a string is a valid identifier.

 Use [Link]() to check if a string is a Python keyword.

 Naming conventions (PEP8):

o Variables: user_name

o Constants: MAX_VALUE

o Classes: MyClass

o Private: _var, __var (name-mangled)

o Special (dunder): __init__

 Avoid using names of built-in functions (like sum, print) as identifiers.

 Identifiers live in namespaces: built-in, global, local.

📝 Short Notes: Input and Output in Python (Part 2)

 Default behavior

o input() → always returns string.

o Example:

o data = input("Enter something: ")

 Type Conversion

o Convert input to required type.

o int(), float(), str().

o Example:

o num = float(input("Enter number: "))


 Printing multiple values

 a, b = 5, 10

 print("Sum:", a + b)

 Special print parameters

o sep → controls separation between items.

o end → controls line ending.

o Example:

o print("Python", "Rocks", sep="***", end="!!!")

 Formatted output

o f-string (modern, clean):

o print(f"{name} scored {marks}/100")

o format() method:

o print("{} scored {}/100".format(name, marks))

✅ In short:

 Use input() for taking data.

 Convert input when needed (int, float).

 Use print() with formatting (f-string, sep, end) for output.

📝 Short Notes on Operators in Python

 Operators → Special symbols to perform operations on variables/values.

🔹 Types of Operators

1. Arithmetic → + , - , * , / , // , % , **

2. Relational / Comparison → == , != , > , < , >= , <=

3. Logical → and , or , not

4. Assignment → = , += , -= , *= , /= , //= , %= , **=

5. Bitwise → & , | , ^ , ~ , << , >>

6. Identity → is , is not (checks memory location)

7. Membership → in , not in (checks sequence membership)

🔹 Operator Precedence (highest → lowest)

1. () → Parentheses
2. ** → Exponent

3. *, /, //, %

4. +, -

5. Comparison (==, >, <, ...)

6. not

7. and

8. or

9. Assignment (=, +=, ...)

👉 Example:

print(10 + 2 * 3) # 16

print((10 + 2) * 3) # 36

📝 Short Notes on Flow Control in Python

 Flow Control → decides the order of execution of statements.

🔹 Conditional Statements

 if → Executes if condition true.

 if-else → Executes one block if condition true, else another.

 if-elif-else → Multiple conditions.

 nested if → if inside another if.

🔹 Looping

 for loop → Iterates over sequence/range.

 while loop → Runs while condition true.

🔹 Loop Control

 break → Exit loop immediately.

 continue → Skip current iteration.

 pass → Do nothing (placeholder).

🔹 Nested Loops

 Loops inside loops (e.g., tables, patterns).

🔹 Loop with else

 else runs if loop finishes without break.


👉 Example:

x = 20

if x > 10:

if x > 15:

print("x > 15")

else:

print("11 <= x <= 15")

📝 Short Notes on Pattern Printing in Python

 Pattern Printing → Done using nested loops.

o Outer loop → Rows.

o Inner loop → Columns (stars/numbers/spaces).

🔹 Types of Patterns

1. Star Patterns

o Square → n rows & n stars.

o Right triangle → Increasing stars.

o Inverted triangle → Decreasing stars.

o Pyramid → Stars + spaces.

o Diamond → Pyramid + inverted pyramid.

o Hollow square/pyramid → Use if conditions for edges.

2. Number Patterns

o Increasing numbers → 1, 1 2, 1 2 3...

o Repeated row numbers → 1, 2 2, 3 3 3...

o Floyd’s triangle → Continuous numbers.

3. Alphabet Patterns

o Increasing alphabets → A, A B, A B C...

o Repeated alphabets → A, B B, C C C...

o Alphabet pyramid → With spaces.

4. Special Shapes
o X pattern → Stars at diagonal positions.

o Cross (+) → Stars at center row & column.

o Checkerboard → Alternate * and space.

o Heart shape → Combination of loops.

🔹 Key Concepts

 Use "* " for stars, " " for spaces.

 Use chr() / ord() for alphabet patterns.

 break/continue can modify designs.

 Symmetry → Spaces are critical for pyramid, diamond, heart.

👉 Example quick logic:

 Pyramid → " "*(n-i) + "* " * i

 Diamond → Upper pyramid + lower inverted pyramid.

📝 Short Notes on Modules & Packages in Python

🔹 Module

 A file containing Python code (.py).

 Can have functions, classes, variables.

 Helps in code reusability.

 Example:

 # [Link]

 def greet(name):

 return f"Hello {name}"

 import mymodule

 print([Link]("Ardra"))

🔹 Package
 A collection of modules in a folder.

 Must contain an __init__.py file (even empty).

 Allows hierarchical structuring.

 Example:

 mypackage/

 __init__.py

 [Link]

 [Link]

 from mypackage import module1

🔹 Importing

 import module → Imports whole module.

 from module import func → Imports specific function/class.

 import module as alias → Short name.

 from module import * → Imports everything.

🔹 Built-in Modules

 Examples:

o math → math functions.

o random → random numbers.

o os → operating system.

o sys → system-specific parameters.

✅ Key Difference:

 Module → Single file ([Link]).

 Package → Collection of modules in a directory (mypackage/).

 📝 Short Notes on Functions in Python


🔹 Definition

 Function → Block of reusable code.

 Defined using def keyword.

 Improves modularity, reusability, readability.

🔹 3 Basic Methods

1. No argument, no return type

2. def greet():

3. print("Hello")

4. With argument, no return type

5. def square(n):

6. print(n*n)

7. With argument, with return type

8. def add(a,b):

9. return a+b

🔹 Function Types

 Built-in → print(), len(), max(), min()

 User-defined → Made by programmer.

 Recursive → Calls itself (e.g., factorial).

 Lambda (anonymous) → lambda x: x*x

🔹 Function Arguments

 Default args → def f(x=10): ...

 Keyword args → f(y=20, x=10)

 Variable length →

o *args → multiple values as tuple

o **kwargs → multiple key-value pairs as dict

🔹 Other Concepts

 Return multiple values → return a, b


 Scope:

o Local → inside function

o Global → outside function (use global)

 Docstring → """ function description """

✅ Key Uses

 Avoids repetition

 Easy debugging

 Organized code

📝 Short Notes on List in Python

🔹 Rules / Properties

1. How to define? → Using square brackets [ ].

2. mylist = [10, 20, 30]

3. Heterogeneous data supported? ✅ Yes

4. mixed = [1, "hello", 3.5, True]

5. Duplicates allowed? ✅ Yes

6. nums = [1, 2, 2, 3, 3]

7. Insertion order preserved? ✅ Yes

8. fruits = ["apple", "banana", "cherry"]

9. Mutable or Immutable? → ✅ Mutable (update possible).

10. a = [10, 20, 30]

11. a[1] = 99 # update

🔹 Common Operations

 append(x) → add at end

 insert(i,x) → add at index

 remove(x) → remove value

 pop(i) → remove by index / last if no index


 clear() → empty list

 sort() → ascending sort

 reverse() → reverse list

 len(list) → length

 max(list), min(list), sum(list)

✅ Key Point:
List = ordered, mutable, supports duplicates, heterogeneous data.

📝 Short Notes on Membership Operators (in, not in)

🔹 Operators

 in → Returns True if element is present in a sequence.

 not in → Returns True if element is NOT present.

🔹 Works With

 ✅ List

 "apple" in ["apple","banana"] # True

 ✅ Tuple

 3 in (1,2,3) # True

 ✅ String

 "Py" in "Python" # True

 ✅ Set

 10 not in {20,30,40} # True

 ✅ Dictionary

o Checks keys by default.

 d = {"a":1,"b":2}

 "a" in d # True

 1 in d # False

 1 in [Link]() # True
🔹 Key Points

 Used to check membership in iterables.

 in → element exists.

 not in → element does not exist.

 In dict, it checks keys, not values (unless .values() used).

✅ Example:

print(5 in [1,2,3,4,5]) # True

print('x' not in "apple") # True

📝 Short Notes on List Slicing in Python

🔹 Syntax

list[start : stop : step]

 start → index to begin (default = 0)

 stop → index to end (exclusive)

 step → gap/jump (default = 1)

🔹 Rules

1. Start index inclusive, Stop index exclusive

2. a = [10,20,30,40,50]

3. print(a[1:4]) # [20,30,40]

4. Omit start/stop for default values

5. print(a[:3]) # [10,20,30]

6. print(a[2:]) # [30,40,50]

7. print(a[:]) # full copy

8. Negative index allowed

9. print(a[-4:-1]) # [20,30,40]

10. Step controls jump

11. print(a[::2]) # [10,30,50]

12. print(a[1::2]) # [20,40]


13. Reverse list with step -1

14. print(a[::-1]) # [50,40,30,20,10]

✅ Key Point:

 Always returns a new list (doesn’t modify original).

 Useful for sublists, reversing, skipping elements.

📝 Short Notes on Linear Search & Binary Search

🔹 Linear Search

 Definition → Sequentially checks each element until target is found or list ends.

 Works on → Any list (sorted or unsorted).

 Time Complexity → O(n).

 Algorithm:

1. Start from first element.

2. Compare with target.

3. If match → return index.

4. Else → continue until end.

👉 Example:

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

key = 30

if key in arr:

print("Found")

else:

print("Not Found")

🔹 Binary Search

 Definition → Repeatedly divides sorted list into halves to find target.

 Works on → Only sorted lists.

 Time Complexity → O(log n).


 Algorithm:

1. Find middle element.

2. If target == middle → found.

3. If target < middle → search left half.

4. If target > middle → search right half.

5. Repeat until found or low > high.

👉 Example:

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

key = 30

low, high = 0, len(arr)-1

found = False

while low <= high:

mid = (low + high)//2

if arr[mid] == key:

found = True

break

elif key < arr[mid]:

high = mid-1

else:

low = mid+1

print("Found" if found else "Not Found")

🔹 Comparison

Feature Linear Search Binary Search

Input list Unsorted/Sorted Must be Sorted

Approach Sequential Divide & Conquer

Time Complexity O(n) O(log n)

Easy to implement ✅ Yes ⚠ Needs sorting

✅ Key Point:
 Use Linear Search when list is small or unsorted.

 Use Binary Search for large sorted datasets (faster).

📝 Short Notes on Tuple in Python

🔹 Rules / Properties

1. How to define? → Using parentheses ( )

2. t = (10, 20, 30)

3. single = (5,) # comma needed

4. Heterogeneous data supported? ✅ Yes

5. t = (1, "hello", 3.5)

6. Duplicates allowed? ✅ Yes

7. t = (1, 2, 2, 3)

8. Insertion order preserved? ✅ Yes

9. t = ("a", "b", "c")

10. Mutable or Immutable? ❌ Immutable (cannot update).

🔹 Access & Slicing

t = (10, 20, 30, 40)

print(t[0]) # 10

print(t[-1]) # 40

print(t[1:3]) # (20, 30)

print(t[::-1]) # (40, 30, 20, 10)

🔹 Operations

 Concatenation → (1,2)+(3,4) → (1,2,3,4)

 Repetition → (1,2)*2 → (1,2,1,2)

 Membership → 2 in (1,2,3) → True

🔹 Functions

 len(t) → length
 max(t), min(t) → largest/smallest

 sum(t) → total

🔹 Methods

 [Link](x) → frequency of x

 [Link](x) → first index of x

🔹 Packing & Unpacking

t = 10, 20, 30 # packing

a, b, c = t # unpacking

✅ Key Point:
Tuple = ordered, immutable, allows duplicates, supports heterogeneous data.

📝 Short Notes on Set in Python

🔹 Rules / Properties

1. How to define? → { } or set()

2. s = {10, 20, 30}

3. s2 = set([1,2,3])

(⚠ {} creates a dictionary, not a set!)

4. Heterogeneous data supported? ✅ Yes

5. s = {10, "hi", 3.5, True}

6. Duplicates allowed? ❌ No

7. s = {1,2,2,3} # {1,2,3}

8. Insertion order preserved? ❌ No (unordered).

9. Mutable or Immutable?

o ✅ Set itself is mutable (add/remove).

o ❌ Elements must be immutable (list not allowed, tuple allowed).

🔹 Common 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 Diff → {1,2,5,6}

🔹 Methods

 add(x) → add element

 update([...]) → add multiple

 remove(x) → remove (error if not exists)

 discard(x) → remove (no error)

 pop() → removes random element

 clear() → empty set

🔹 Built-in Functions

 len(s), max(s), min(s), sum(s)

🔹 Frozen Set

 Immutable set → frozenset([1,2,3])

✅ Key Point:
Set = unordered, no duplicates, mutable, supports heterogeneous data.

📝 Short Notes on Dictionary in Python

🔹 Rules / Properties

1. How to define?

2. d = {"name":"Ardra", "age":21}

3. d2 = dict([("id",101),("marks",90)])
4. Heterogeneous data supported? ✅ Yes

5. Duplicates allowed?

o ❌ Keys → not allowed (last value kept)

o ✅ Values → allowed

6. Insertion order preserved? ✅ Yes (Python 3.7+)

7. Mutable or Immutable? ✅ Mutable

8. Keys must be immutable (int, str, tuple ✅; list ❌)

🔹 Access

d = {"name":"Ardra", "age":21}

print(d["name"]) # Ardra

print([Link]("age")) # 21

print([Link]("grade","N/A")) # N/A

🔹 Add / Update

d["city"] = "Kochi" # add

d["age"] = 22 # update

🔹 Remove

[Link]("age") # remove by key

[Link]() # remove last

del d["name"] # delete by key

[Link]() # empty dict

🔹 Loop

for k,v in [Link]():

print(k, v)

🔹 Methods

 keys() → all keys

 values() → all values


 items() → key-value pairs

 update({...}) → add/merge

 get(k,default) → safe access

🔹 Nested Dictionary

students = {101: {"name":"Ardra","age":21}}

print(students[101]["name"]) # Ardra

✅ Key Point:
Dictionary = unordered mapping of unique keys to values, insertion order preserved, mutable.

📝 Short Notes on File Operations in Python

🔹 File Modes

Mode Use

"r" Read (default, error if not found)

"w" Write (create/overwrite)

"a" Append (add at end)

"r+" Read & Write

"w+" Write & Read (overwrite)

"a+" Append & Read

🔹 Open & Close

f = open("[Link]","r")

[Link]()

👉 Best practice →

with open("[Link]","r") as f:

data = [Link]()

🔹 Writing

f = open("[Link]","w")
[Link]("Hello\n")

[Link]()

f = open("[Link]","a")

[Link]("New line\n")

[Link]()

🔹 Reading

f = open("[Link]","r")

print([Link]()) # entire file

print([Link]()) # one line

print([Link]()) # list of lines

[Link]()

🔹 Word Count Example

with open("[Link]","r") as f:

wc = {}

for line in f:

for word in [Link]():

word = [Link]()

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

print(wc)

✅ Input: "apple banana apple mango"


✅ Output: {'apple':2,'banana':1,'mango':1}

✅ Key Point:

 Use w to overwrite, a to append, r to read.

 Use with to auto-close file.

 Word count → dictionary + loop.

📝 Short Notes on OOPs in Python


🔹 Class

 Blueprint/template for objects.

class TV:

def power_on(self):

print("ON")

🔹 Object

 Instance of a class.

tv1 = TV()

tv1.power_on()

🔹 Reference

 Variable that points to an object.

tv2 = TV() # tv2 → reference

🔹 Rules

 Class names → Capital Letter.

 Functions inside class → methods.

 self → refers to current object.

🔹 Constructor

 __init__ → called automatically when object created.

class Student:

def __init__(self,name):

[Link] = name

🔹 OOP Properties

1️⃣ Inheritance → Reuse parent class.

class A: pass

class B(A): pass


2️⃣ Encapsulation → Hide data with private (__).

self.__balance

3️⃣ Polymorphism → Same method, different behavior.

[Link](), [Link]()

4️⃣ Abstraction → Hiding details using ABC.

from abc import ABC,abstractmethod

✅ Key Point:
OOP = Class + Object + Reference + self + Constructor + 4 Properties (Inheritance, Encapsulation,
Polymorphism, Abstraction).

📝 Short Notes on Functional Programming in Python

🔹 Functional Programming

👉 Modern style to minimize program length & optimize performance.


Key tools → lambda, map, filter, list comprehension.

🔹 Lambda (Anonymous Function)

 Function without a name.

square = lambda x: x*x

print(square(5)) # 25

🔹 Map

 Apply function to all elements.

lst = [1,2,3,4,5,6,7,8,9,10]

squares = list(map(lambda x:x**2, lst))

print(squares) # [1,4,9,16,25,36,49,64,81,100]

🔹 Filter

 Select elements based on condition.

evens = list(filter(lambda x:x%2==0, lst))

print(evens) # [2,4,6,8,10]
🔹 List Comprehension

 Short, elegant way to create lists.

squares = [x**2 for x in range(1,11)]

evens = [x for x in range(1,11) if x%2==0]

✅ Summary

Tool Purpose

Lambda Inline anonymous function

map() Apply function to all elements

filter() Pick elements by condition

List comprehension Short, pythonic alternative

📝 Short Notes on List Comprehension in Python

🔹 Definition

👉 List Comprehension = way to minimize code into one line for list-based operations.

Syntax

[expression for item in iterable if condition]

🔹 1. Range of Elements

lst = [x for x in range(1,11)]

# [1,2,3,4,5,6,7,8,9,10]

🔹 2. With Condition

evens = [x for x in range(1,11) if x%2==0]

# [2,4,6,8,10]

odd_squares = [x**2 for x in range(1,11) if x%2!=0]

# [1,9,25,49,81]
🔹 3. With Multiple Conditions

result = ["Even" if x%2==0 else "Odd" for x in range(1,6)]

# ['Odd','Even','Odd','Even','Odd']

fizzbuzz = [

"FizzBuzz" if x%15==0 else

"Fizz" if x%3==0 else

"Buzz" if x%5==0 else x

for x in range(1,16)

🔹 Nested List Comprehension

matrix = [[j for j in range(3)] for i in range(3)]

# [[0,1,2],[0,1,2],[0,1,2]]

✅ Key Point:
List comprehension = short, readable, powerful alternative to loops + map/filter.

📝 Short Notes on List Comprehension in Python

🔹 Definition

List comprehension is a one-line way to create lists by applying expressions and optional conditions.
Syntax:

[expression for item in iterable if condition]

🔹 1. Range of Elements

lst = [x for x in range(1, 6)]

# [1, 2, 3, 4, 5]

🔹 2. With Condition
evens = [x for x in range(1, 11) if x % 2 == 0]

# [2, 4, 6, 8, 10]

🔹 3. Multiple Conditions / Conditional Expressions

labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)]

# ['Odd', 'Even', 'Odd', 'Even', 'Odd']

🔹 Nested List Comprehension

matrix = [[j for j in range(3)] for i in range(3)]

# [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

✅ Key Points

 Shorter than loops

 Can replace map() and filter()

 Improves readability when used wisely

You might also like