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

Python Basics

The document provides a comprehensive introduction to Python, covering its features, syntax rules, variable behavior, data types, operators, and input/output functions. Key highlights include Python's interpreted nature, dynamic typing, and the importance of indentation. Additionally, it outlines common operations and pitfalls associated with data types and operators, along with tips for multiple-choice questions (MCQs) related to these topics.

Uploaded by

vashvi.0202
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)
4 views25 pages

Python Basics

The document provides a comprehensive introduction to Python, covering its features, syntax rules, variable behavior, data types, operators, and input/output functions. Key highlights include Python's interpreted nature, dynamic typing, and the importance of indentation. Additionally, it outlines common operations and pitfalls associated with data types and operators, along with tips for multiple-choice questions (MCQs) related to these topics.

Uploaded by

vashvi.0202
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

1 — Introduction to Python (detailed)

Features of Python — what to remember (MCQ-friendly)


 Interpreted — Python code is executed line-by-line by an interpreter (no explicit
compile step you see in Java).
 High-level — abstracts away memory management and low-level details.
 Dynamically typed — variable types are determined at runtime (you don’t declare int
x like in Java).
 Strongly typed — Python won’t implicitly do unsafe conversions (e.g. concatenating
3 + "4" raises an error).
 Readable / clean syntax — emphasis on human-readable code.
 Object-oriented — everything is an object (even functions).
 Portable — runs on Windows, Linux, macOS without source changes (same .py file).
 Extensive standard library — batteries included (os, math, datetime, json, etc.).
 Interactive mode & REPL — you can test expressions quickly in the interpreter.

MCQ tips: questions often ask which features are true/false (interpreted vs compiled,
dynamic vs static, strong vs weak typing).

Python syntax — basic rules & examples


 Statements end at newline (no semicolons required). You can use ; to put multiple
statements on one line, but it’s not idiomatic.
 Blocks are specified by indentation, not {} braces.
 Keywords (like def, if, for) are reserved.

Example — small program:

name = input() # read string


age = int(input()) # convert to int
if age >= 18:
print(f"{name} is adult")
else:
print(f"{name} is minor")

MCQ tip: indentation and colon (:) after if/for/def are commonly tested.

Indentation — why it matters and rules


 Indentation is the syntactic marker of blocks. A consistent number of spaces (PEP 8
recommends 4 spaces) must be used.
 Mixing tabs and spaces causes TabError or inconsistent behavior — always use spaces
in professional settings.
 Example of an indentation error:

if True:
x=1
y = 2 # wrong: extra space -> IndentationError

 Nested blocks increase indentation:

for i in range(3):
if i % 2 == 0:
print(i)

MCQ tip: they may show code with incorrect indentation and ask whether it runs or raises an
error.

Comments (# and triple-quotes """ ... """)


 Single-line comment: starts with # — ignored by interpreter.
 # this is a comment
 x = 10 # inline comment
 Triple-quoted strings (""" ... """ or ''' ... ''') are string literals. When placed right after a
function/class/module header, they act as docstrings (accessible via .__doc__). If used
elsewhere, they are just multi-line string objects (and if not assigned, ignored at
runtime but still create a literal object at compile time).
 def f():
 """This is the docstring for f"""
 return 1

 print(f.__doc__) # prints the docstring
 Multi-line comments are usually done by consecutive # lines or using triple-quotes as
a docstring (but triple-quotes are not technically comments).

MCQ tip: question may ask difference between # and """ — # is a comment; """ creates a
string literal and is used as a docstring when placed in the right position.

2 — Variables & Data Types (detailed)


Variable rules (naming & behavior)
 Identifiers can contain letters (a–z, A–Z), digits (0–9), and underscores (_), but cannot
start with a digit.
o Valid: age, _count, user1
o Invalid: 1st, user-name (hyphen not allowed)
 Case-sensitive: Age and age are different.
 Keywords (e.g., def, for, if, class, return, ...) cannot be used as variable names.
 No explicit declaration needed; assignment creates the variable in the current scope:
 x=5 # creates x
 x = "hello" # x now refers to a string (dynamic typing)
 A variable refers to an object; assignment binds a name to an object.

MCQ tip: they often ask which names are valid/invalid, or whether reassigning a different
type is allowed (it is).

Dynamic typing — what it means & pitfalls


 Definition: types are associated with objects, not names. A name can be rebound to
objects of different types at runtime.
 a = 10 # a points to an int object
 a = "ten" # now a points to a str object
 Pros: fast to write, flexible for scripting and quick coding.
 Cons / pitfalls:
o Type errors appear at runtime (e.g., trying arithmetic on a string).
o Static-type errors that a Java compiler would catch could slip by; use tools like
mypy for optional static checking.

MCQ tip: dynamic typing is a common property tested — they might contrast it with Java’s
static typing.

Basic data types — definitions, examples, and common


operations
int — integers

 Arbitrary precision (no fixed int size).


 Operations: + - * // % **
 Example:
 a = 42
 b = -3
 c = 2**60 # large integer ok

MCQ traps: // is floor division, e.g., -3 // 2 == -2 (floor towards negative infinity).

float — floating-point numbers

 Double-precision floats (IEEE 754).


 Beware of precision issues:
 0.1 + 0.2 # gives 0.30000000000000004
 Use round() or decimal module for precise decimal arithmetic.
bool — booleans

 Two values: True, False (capitalized, they are instances of int under the hood: True == 1,
False == 0).
 Useful with logical operators:
 x=5
 is_even = (x % 2 == 0) # True or False

MCQ tip: True + True == 2 is a valid expression (True acts like 1).

str — strings

 Immutable sequence of Unicode characters.


 Creation: single or double quotes, or triple quotes for multi-line.
 s = "hello"
 s2 = 'world'
 s3 = """line1
 line2"""
 Common operations: indexing s[0], slicing s[1:4], concatenation s + "!", repetition
"ha"*3.
 Methods: upper(), lower(), split(), strip(), replace(), find(), join().

MCQ traps: strings are immutable — operations return new strings; s[0] = 'H' raises an error.

complex — complex numbers

 Literal form: 3+4j (note the j for imaginary part).


 Real and imaginary parts accessible: (3+4j).real, (3+4j).imag.
 Support arithmetic and abs() for magnitude.

MCQ tip: complex numbers use j (not i).

Type conversion — int(), float(), str(), and more


 int(x) converts x to an integer (if possible). Converting a float truncates toward zero:
int(3.9) == 3, int(-3.9) == -3.
 float(x) converts x to a float.
 str(x) converts x to a string representation.
 Other helpful conversions:
o bool(x) — truthiness conversion (0, 0.0, '', [], {}, None → False; everything else →
True).
o list(iterable), tuple(iterable), set(iterable), dict(...)
(for dict you typically pass
sequences of key-value pairs or use comprehensions).
 Examples:
 n = int("42") # 42
 f = float("3.14") # 3.14
 s = str(100) # "100"
 L = list("abc") # ['a','b','c']
 Errors: int("3.14") raises ValueError (string must represent an int). int("abc") → ValueError.

MCQ tip: be careful with int() on floats in string form — int("3.9") is invalid; you must
float("3.9") then int() if you want truncation.

type() function — inspect the type of an object


 Usage: type(obj) returns the object's class/type.
 type(10) # <class 'int'>
 type(3.14) # <class 'float'>
 type("hi") # <class 'str'>
 Combined with isinstance() for safe type checks:
 isinstance(5, int) # True
 isinstance(True, bool) # True
 isinstance(True, int) # True (bool is subclass of int)
 MCQ tip: type() equality checks exact type, while isinstance() supports subclass
relationships.

🔵 3. OPERATORS (Detailed Explanation)


Operators are special symbols that perform operations on variables and values.

3.1 Arithmetic Operators


Used for mathematical operations.

Operato Meaning Example Result


r
+ Addition 5+2 7
- Subtraction 5-2 3
* Multiplication 5*2 10
/ Division 5/2 2.5 (float)
// Floor Division 5 // 2 2 (removes decimal)
% Modulus 5%2 1 (remainder)
** Exponent 2 ** 3 8
🔹 Notes:

 / gives float result always.


 // gives integer result by removing decimal.
 ** is used for power calculation.

3.2 Comparison (Relational) Operators


Used to compare two values. They always return True or False.

Operato Meaning Example Outpu


r t
== equal to 5 == 5 True
!= not equal to 5 != 3 True
> greater than 10 > 5 True
< less than 3<1 False
>= greater or 5 >= 5 True
equal
<= less or equal 2 <= 3 True

3.3 Logical Operators


Used to combine conditions. Output is Boolean: True/False.

Operator Meaning Example Result


and True if both are True True and False False
or True if at least one is True True or False True
not reverses condition not True False

Example:
a = 10
b=5
print(a > 2 and b < 10) # True
print(a < 5 or b == 5) # True
print(not(a == 10)) # False

3.4 Assignment Operators


Used to assign values to variables.

Basic assignment:
x = 10

Shorthand assignment:

Operato Meaning Example Result


r
+= x = x + value x += 2 adds 2
-= x = x - value x -= 2 subtracts 2
*= multiply and assign x *= 3 x = x*3
/= divide and assign x /= 4 x = x/4

Example:
x=5
x += 3 # x = 8
x -= 2 # x = 6
x *= 2 # x = 12
x /= 3 # x = 4.0

3.5 Membership Operators


Used to check if a value exists in a sequence (string, list, tuple, set, dictionary).

Operator Meaning Example Output


in True if value present 'a' in 'apple' True
not in True if value not present 3 not in True
[1,2,4]

Example:
nums = [1, 2, 3]
print(2 in nums) # True
print(4 not in nums) # True

3.6 Identity Operators


Used to compare memory locations, not values.

Operator Meaning Example


is True if both refer to same object a is b
is not True if they don't share same object a is not b

Example:
a = [1,2,3]
b = [1,2,3]
print(a == b) # True (values same)
print(a is b) # False (different memory)

Important:

 == → compares value
 is → compares memory address

🔵 4. INPUT & OUTPUT (Detailed


Explanation)

4.1 input() Function


input() is used to take user input from keyboard.

Important:

 Always returns string type.

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

If you need numbers:


age = int(input("Enter age: "))
salary = float(input("Enter salary: "))

4.2 print() Function


Used for output.

Basic usage:
print("Hello World")

Printing multiple values:


print("Name:", "Ravi")
Using sep (separator):
print("A", "B", "C", sep="-") # A-B-C

Using end:
print("Hello", end=" ")
print("World")

Output:

Hello World

4.3 f-strings (Formatted Strings)


f-strings allow inserting variables directly inside strings using {}.

Example:
name = "Ravi"
age = 21
print(f"My name is {name} and I am {age} years old.")

Expressions inside f-strings:


print(f"5 + 3 = {5 + 3}")

Formatting numbers:
pi = 3.14159
print(f"{pi:.2f}") # 3.14

Strings — detailed explanation


1. String creation
 A string literal can be surrounded by single quotes '...', double quotes "...", or
triple quotes '''...''' / """...""".
 s1 = 'hello'
 s2 = "world"
 s3 = """multi
 line
 string"""
 Triple quotes are used for multi-line strings or docstrings.
 Strings are sequences of Unicode characters in Python 3 (so they can hold non-ASCII
text).
2. Indexing
 Strings behave like sequences: you can access characters by index. Indexing is zero-
based.
 s = "python"
 s[0] # 'p'
 s[3] # 'h'
 Negative indices count from the end:
 s[-1] # 'n' (last char)
 s[-2] # 'o' (second last)
 Attempting to access an index outside range raises IndexError:
 s[100] # IndexError

3. Slicing
 Syntax: s[start:stop:step]
o start — inclusive index where slice begins (default 0)
o stop — exclusive index where slice ends (default len(s))
o step — stride (default 1)
 Examples:
 s = "abcdefgh"
 s[2:5] # 'cde' (indexes 2,3,4)
 s[:3] # 'abc' (start default 0)
 s[3:] # 'defgh' (to end)
 s[:] # full copy, 'abcdefgh'
 s[::2] # 'aceg' (every 2nd char)
 s[::-1] # 'hgfedcba' (reverse string)
 Important details:
o stop is exclusive — common MCQ trap.
o If start >= stop with positive step, you get an empty string ''.
o Negative step slices go right-to-left; with negative step, defaults for
start/stop are reversed (so s[::-1] reverses).
o Slicing never raises IndexError — if indexes are out of range, Python clips
them to valid bounds and returns what it can.

4. Common string methods (MCQ-relevant)


 [Link]() → returns a new string with all characters converted to uppercase.
 [Link]() → all lowercase.
 [Link]() → returns a new string with leading and trailing whitespace removed.
o [Link]() removes only left (leading) whitespace.
o [Link]() removes only right (trailing) whitespace.
 [Link](sep=None, maxsplit=-1) → splits into a list of substrings.
o If sep is None (default) it splits on any whitespace and treats multiple
whitespace as a single separator.
o maxsplit controls number of splits.
 " a b c ".split() # ['a', 'b', 'c']
 "a,b,c".split(',') # ['a', 'b', 'c']
 "a b c d".split(maxsplit=2) # ['a', 'b', 'c d']
 [Link](sub) / [Link](sub):
o find returns -1 if sub not found.
o index raises ValueError if not found.
 [Link](old, new, count=-1) → returns a new string where occurrences of old
are replaced by new. count limits replacements.
 [Link](prefix) / [Link](suffix) → boolean checks.
 ''.join(iterable) — important: to concatenate a list of strings efficiently:
 '-'.join(['a','b','c']) # 'a-b-c'

Avoid using + in a loop to build large strings (inefficient).

5. String concatenation
 Use + or string formatting or join():
 "hello " + "world" # 'hello world'
 f"{name} is {age}" # f-string (Python 3.6+), fast and
readable
 " ".join(["hello","world"]) # preferred for concatenating many
pieces
 Concatenation with + is fine for a few strings; for many or in loops prefer join().

6. String immutability
 Strings are immutable: once created, you cannot change a character in-place.
 s = "hello"
 s[0] = 'H' # TypeError: 'str' object does not support item
assignment
 Any operation that looks like it "changes" a string returns a new string (original
remains unchanged):
 s2 = [Link]() # 'HELLO', but s is still 'hello'
 This immutability is why methods like replace() return new strings and why join()
is efficient (it allocates once for the final string).

Control Statements — detailed explanation


1. if, elif, else syntax
if condition1:
# block executed if condition1 is truthy
elif condition2:
# executed if condition1 false and condition2 truthy
else:
# executed if all above conditions false

 Every if, elif, else header must end with a colon :.


 The body is defined by indentation.
 elif and else are optional; you can have any number of elif branches.

2. What counts as True / False (truthiness)


 False values: False, None, 0 (zero of any numeric type), empty
sequences/collections ('', (), [], {}, set()), and objects that define __bool__() /
__len__() to return False/0.
 Everything else is True.
 if []:
 print("won't execute")
 if "hello":
 print("will execute")

3. Nested conditions
 You can nest if blocks inside other if/else blocks.
 x = 10
 if x > 0:
 if x % 2 == 0:
 print("positive even")
 else:
 print("positive odd")
 else:
 print("non-positive")
 Use nesting to express multi-level decision logic, but avoid very deep nesting —
prefer combining conditions or extracting logic into functions for readability.

4. Short-hand if (single-line / conditional expression)


There are two common "short forms":

A. Single statement if (no else)


if condition: action

Example:

if x > 0: print("positive")

Useful for tiny one-liners, but not for complex logic.

B. Ternary conditional expression (most useful)


value_if_true if condition else value_if_false

Example:

status = "even" if x % 2 == 0 else "odd"


# Equivalent to:
# if x % 2 == 0:
# status = "even"
# else:
# status = "odd"

 This is an expression, it returns a value (unlike the multi-line if which is a


statement). It's commonly used in assignments and return statements.
5. Combining conditions and operator precedence
 Logical operators: not has highest precedence, then and, then or.
 if a and b or c: # equivalent to ((a and b) or c)
 ...
 Use parentheses to make intent clear:
 if (a and (b or c)):
 ...

6. Short-circuit evaluation
 and and or short-circuit:
o For A and B: if A is false, B is not evaluated (overall result false).
o For A or B: if A is true, B is not evaluated (overall result true).
 This is useful to avoid errors:
 if obj is not None and [Link](): # safe: [Link]() called
only if obj not None
 ...

7. pass, break, continue


 pass — placeholder, does nothing. Useful when a block is syntactically required but
you have nothing to execute.
 if cond:
 pass # TODO implement later
 break — exits the nearest loop.
 continue — skips to next iteration of loop.

8. Common pitfalls / MCQ traps


 Indentation errors: mixing tabs and spaces can raise IndentationError. Use 4
spaces per level (PEP8 recommendation).
 Using assignment = inside if: Python disallows using assignment as an expression
(if x = 5: is a SyntaxError). (Modern Python has walrus := for assignment
expressions, but that's advanced and often intentionally tested.)
 Equality vs identity:
o == checks value equality (for strings, content).
o is checks identity (same object in memory); do not use is to compare strings
for content.
 a = "hello"
 b = "hello"
 a == b # True
 a is b # may be True or False (implementation-dependent), so avoid
for value checks
 Order of elif: conditions are evaluated top-to-bottom; once a true condition is
found, later elif branches are skipped.
Loops & Core Data Structures — detailed,
example-packed, MCQ-ready
I'll explain each item you listed with clear theory, runnable examples, common pitfalls, and
quick notes you’ll see in MCQs. Since you know Java, I’ll add small Java analogies when
helpful.

1. Loops
for loop
What it is: iterates over any iterable (list, tuple, string, dict, range, etc.).
Python for is not index-based like C for(i=0;...) — it directly gives items.

# iterate list
arr = [10, 20, 30]
for x in arr:
print(x)

# iterate string
for ch in "abc":
print(ch)

# iterate dictionary keys


d = {"a":1, "b":2}
for key in d: # same as for key in [Link]()
print(key, d[key])

Useful patterns

 enumerate(iterable) → gives (index, value) (MCQ favorite).


 for i, v in enumerate(["a","b"]):
 print(i, v)
 zip(a, b) → iterate pairs from two iterables.
 for x, y in zip([1,2],[3,4]):
 print(x+y)

Pitfalls / MCQ points

 Iterating a dictionary directly yields keys.


 You can mutate the iterable reference (e.g., reassign loop variable) without changing
the original list.
 Modifying a list while iterating can cause skipped elements or unexpected behavior.

Java analogy: Python for x in list ≈ Java for (Type x : list).


while loop
What it is: repeats while a boolean condition is True.

i = 0
while i < 3:
print(i)
i += 1

else with loops (MCQ trick):


Both for and while can have an else: block that executes only if the loop completes
normally (no break).

for i in range(3):
print(i)
else:
print("completed") # runs because no break occurred

for i in range(3):
if i == 1:
break
else:
print("won't run") # does not run because break happened

Pitfalls

 Infinite loops if condition never becomes False.


 while is good when iterations depend on runtime condition (not a fixed count).

range() function
What it does: produces a sequence of integers; commonly used in for loops.

Signatures:

 range(stop) → 0 .. stop-1
 range(start, stop) → start .. stop-1
 range(start, stop, step) → step increments (step can be negative)

list(range(5)) # [0,1,2,3,4]
list(range(2, 6)) # [2,3,4,5]
list(range(5, 0, -1)) # [5,4,3,2,1]

Important facts (MCQ fodder)

 range() returns a range object, not a list (but it’s iterable and lazy).
 range(0) is empty.
 range supports len() and indexing: range(10)[3] == 3.

Java analogy: for (int i=0;i<n;i++) → Python for i in range(n).


Loop control statements: break, continue, pass
 break — immediately exit the innermost loop.
 for x in [1,2,3]:
 if x==2:
 break # loop ends when x is 2
 continue — skip the rest of current iteration and continue with next.
 for x in range(4):
 if x % 2 == 0:
 continue
 print(x) # prints only odd numbers
 pass — no-op placeholder where a statement is syntactically required.
 if cond:
 pass # do nothing for now

MCQ tips

 break prevents the loop else from executing.


 pass does nothing; it's not the same as continue or break.

2. Python Data Structures


I'll cover Lists, Tuples, Sets, Dictionaries — how to create, index/slice, key methods,
complexity where relevant, and MCQ traps.

List
Definition: ordered, mutable, allow duplicates, heterogeneous.

Creation
a = [] # empty
a = [1, 2, 3]
a = list([1,2,3]) # from iterable

Indexing & slicing

 Indexing: a[0], a[-1] (last element)


 Slicing: a[start:stop:step] — returns a new list
 a = [0,1,2,3,4]
 a[1:4] # [1,2,3]
 a[:3] # [0,1,2]
 a[::2] # [0,2,4]
 a[::-1] # reversed copy
Key point: slices return new lists; original unchanged.

List methods (behaviour + complexity)

 append(x) → add to end. Amortized O(1).


 [Link](5)
 pop() → remove & return last element. O(1). pop(i) removes index i: O(n).
 [Link]() # last
 [Link](0) # first element => O(n)
 insert(i, x) → insert at index i. O(n) because shifting.
 remove(x) → remove first matching value, O(n).
 sort() → sorts list in-place, O(n log n).
 reverse() → reverses list in-place, O(n).
 extend(iterable) → append multiple elements. Amortized O(k).

MCQ traps

 sort() returns None because it's in-place. Writing b = [Link]() sets b to None.
 sorted(a) returns a new sorted list, leaving a unchanged.
 a + b concatenates and returns a new list.

List comprehension (very Pythonic and frequent in MCQs)

Concise way to build lists.

squares = [x*x for x in range(5)] # [0,1,4,9,16]


evens = [x for x in range(10) if x % 2 == 0] # conditional
pairs = [(x,y) for x in [1,2] for y in [3,4]]

Generator expression (lazy) — similar syntax but with () instead of []:

gen = (x*x for x in range(5)) # yields values on demand

Pitfalls

 List comprehensions create a full list in memory; use generator for large data.

Java analogy: List comprehensions ≈ stream operations or manual loops building arraylists.

Tuple
Definition: ordered, immutable, allows duplicates.

Creation & packing/unpacking


t = (1, 2, 3)
t2 = 1, 2, 3 # parentheses optional (packing)
a, b, c = t # unpacking
Single-element tuple: requires trailing comma:

x = (5,) # NOT (5)

Why use tuples?

 Immutable → safe for keys in dicts (if contents immutable).


 Slightly faster & smaller than lists.

MCQ points

 Attempting t[0] = 5 raises TypeError.


 Tuples support indexing and slicing just like lists (slice returns tuple).

Set
Definition: unordered collection of unique elements. Mutable (but elements must be
immutable).

Creation
s = {1, 2, 3}
s2 = set([1, 2, 2]) # => {1, 2}

Basic methods & operations

 add(x) → add element (O(1) average)


 remove(x) → remove element; raises KeyError if absent
 discard(x) → remove if present; no error if absent
 pop() → remove & return an arbitrary element
 union, intersection, difference, symmetric_difference
 [Link](b) # a | b
 [Link](b) # a & b
 [Link](b) # a - b
 a.symmetric_difference(b) # a ^ b

MCQ traps

 Sets are unordered → no indexing (s[0] raises TypeError).


 Sets cannot contain mutable items (e.g., lists), but can contain tuples.

Java analogy: Set like HashSet.

Dictionary
Definition: mapping of keys → values. Keys must be immutable (hashable), values can be
anything.

Creation
d = {"a": 1, "b": 2}
d = dict(a=1, b=2)

Access & safe access

 d[key] → returns value, raises KeyError if key absent


 [Link](key, default) → returns default if key absent (MCQ favorite)
 [Link]("c", 0) # 0 if c not present

Methods

 [Link]() → view of keys (iterable)


 [Link]() → view of values
 [Link]() → view of (key, value) pairs
 [Link](other) → merges another dict or iterable of pairs; existing keys
overwritten
 [Link]({"b": 3, "c":4}) # now b maps to 3, c to 4
 [Link](key[, default]) → remove key and return value; if default provided and
key missing, returns default
 del d[key] → removes key (raises KeyError if absent)

Views vs lists

 [Link]() returns a dynamic view into the dict: if dict changes, the view reflects that.
Often converted to list for indexing: list([Link]())[0].

Iteration

 for k in d: → iterate keys


 for k, v in [Link](): → iterate pairs

MCQ traps

 Duplicate keys in literal: later value overrides earlier one: {"a":1, "a":2} → a:2.
 [Link]() vs d["key"]: get won’t raise KeyError.
 [Link]() is not a list (but convertible).

Java analogy: HashMap behavior is similar; get vs containsKey are analogous.

⭐ 9. FUNCTIONS (BASIC + DETAILED)


A function is a block of code that runs only when it is called.
✔ Defining Functions using def
Syntax:

def function_name(parameters):
# body
return value

Example:

def greet():
print("Hello!")

Calling:

greet()

Key points:

 Keyword def is used to define a function.


 Parentheses are required.
 Colon : starts the function block.
 Indentation is mandatory.

✔ Parameters & Return


Parameters → values the function receives.
Return → output of the function.

Example:

def add(a, b):


return a + b

Calling:

result = add(5, 3) # 8

If return is not used → function returns None by default.

✔ Default Arguments
Default values assigned to parameters.
Example:

def greet(name="Guest"):
print("Hello", name)

Calls:

greet() # Hello Guest


greet("John") # Hello John

Important rule:

Default arguments must come after normal parameters.

❌ Wrong:

def fun(a=10, b):


pass

✔ *args → Variable-Length Positional Arguments


Collects extra arguments into a tuple.

Example:

def fun(*args):
print(args)

fun(1, 2, 3)

Output:

(1, 2, 3)

Use when you don’t know how many arguments will come.

✔ **kwargs → Variable-Length Keyword Arguments


Collects extra keyword arguments into a dictionary.

Example:

def fun(**kwargs):
print(kwargs)

fun(a=1, b=2)

Output:
{'a': 1, 'b': 2}

Use when arguments come in the form key=value.

✔ Lambda Functions (Basic Only)


A lambda function is a small anonymous function (no name).

Syntax:

lambda arguments : expression

Example:

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

Output:

25

Used for small, simple operations.

⭐ 10. MODULES & PACKAGES (BASIC)


A module is a file containing Python code (functions, variables).
A package is a collection of modules.

✔ Import Statement
Used to bring modules into your program.

Examples:

import math
import random
import time
from math import sqrt

✔ Using built-in modules


math module
Provides mathematical functions:

import math

print([Link](25)) # 5.0
print([Link](3.7)) # 3
print([Link](3.1)) # 4
print([Link](2, 3)) # 8.0

random module

Used to generate random numbers.

import random

print([Link]()) # 0 to 1
print([Link](1, 10)) # between 1 and 10
print([Link]([1,2,3])) # chooses random element

⭐ 11. EXCEPTION HANDLING (BASIC)


Exceptions = errors that stop program execution.
Handled using try, except, and finally.

✔ Syntax
try:
# risky code
except:
# runs if error occurs
finally:
# always runs

✔ Example
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")

Output:

Cannot divide by zero


Done

✔ finally always executes


Even if there is an exception.

✔ Common Errors (MCQ-important)


 ZeroDivisionError
 TypeError
 ValueError
 IndexError
 KeyError
 FileNotFoundError

Example:

int("abc") # ValueError

⭐ 12. FILE HANDLING (BASIC)


Used to read and write files.

✔ Opening a file (open)


Syntax:

open("filename", "mode")

Common modes:

Mode Meaning
"r" read (default)
"w" write (overwrites file)
"a" append
"rb" read binary
"wb" write binary

✔ Reading a file
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

Other methods:
 readline() → reads one line
 readlines() → returns list of lines

✔ Writing to a file
f = open("[Link]", "w")
[Link]("Hello World")
[Link]()

✔ Using with open()

This is the recommended approach.


It automatically closes the file.

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


data = [Link]()
print(data)

Writing:

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


[Link]("\nNew line added")

You might also like