PYTHON PROGRAMMING
GATE फर्रे
Python is a high-level, interpreted, object-oriented 4. Assignment Operators
programming language used for easy coding,
automation, data science, web development, AI, and c = 5
c += 2 # c = c + 2 → 7
more.
Input function: input( ) → takes input from user as a
5. Bitwise Operators
string.
name = input("Enter your name: ")
print(a & b) # 2 (AND)
print(a | b) # 11 (OR)
Output function: print( ) → displays output.
6. Membership Operators
print("Hello", name)
print(3 in [1,2,3]) # True
List of operators in Python
print(4 not in [1,2,3]) # True
1. Arithmetic Operators 7. Identity Operators
a, b = 10, 3
print(a + b) # 13 (Addition)
x = [1,2]
print(a - b) # 7 (Subtraction)
y = [1,2]
print(a * b) # 30 (Multiplication)
print(x is y) # False
print(a / b) # 3.33 (Division)
print(x is not y) # True
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponent)
print(a // b) # 3 (Floor Division)
2. Comparison Operators
python
print(a > b) # True
print(a == b) # False
3. Logical Operators
x, y = True, False
print(x and y) # False
print(x or y) # True
print(not x) # False
Page No:- 01
PYTHON PROGRAMMING
GATE फर्रे
Python, short-circuiting happens with and / or if i == 4:
operators: break # stops at 4
print(i) # 0 1 3
# AND short-circuit (stops if first is
pass # does nothing, placeholder
False)
print(False and (10/0)) # False (does
not check 10/0)
1. break → exits loop immediately
# OR short-circuit (stops if first is
True)
print(True or (10/0)) # True (does for i in range(5):
not check 10/0) if i == 3:
break
print(i)
Python, flow control statements decide the order # Output: 0 1 2
of execution:
2. continue → skips current iteration
1. Conditional (if, elif, else):
for i in range(5):
x = 10 if i == 3:
if x > 0: continue
print("Positive") print(i)
elif x == 0: # Output: 0 1 2 4
print("Zero")
else:
print("Negative") range() → generates a sequence of numbers.
2. Looping (for, while): Syntax:
for i in range(3): range(start, stop, step)
print(i) # 0 1 2
• start → starting number (default 0)
count = 3
while count > 0: • stop → end (excluded)
print(count) # 3 2 1
count -= 1 • step → increment (default 1)
3. Jump (break, continue, pass):
for i in range(5):
if i == 2:
continue # skips 2
Page No:- 02
PYTHON PROGRAMMING
GATE फर्रे
Examples: • complex → numbers with real + imaginary part
z = 2 + 3j
print(list(range(5))) # print(type(z)) # <class 'complex'>
[0,1,2,3,4]
print(list(range(2, 7))) #
[2,3,4,5,6] 2. Sequence Types
print(list(range(1, 10, 2))) #
[1,3,5,7,9] • str (String) → text in quotes
Nested loop → a loop inside another loop. name = "Python"
print(type(name)) # <class 'str'>
Example:
• list → ordered, mutable collection
for i in range(3): # outer loop
for j in range(2): # inner loop
print(i, j) lst = [1, 2, 3]
print(type(lst)) # <class 'list'>
Output:
0 0
• tuple → ordered, immutable collection
0 1
1 0
1 1
2 0 tup = (1, 2, 3)
2 1 print(type(tup)) # <class 'tuple'>
Python, data types define the type of values stored 3. Set Types
in variables. • set → unordered, unique elements
1. Numeric Types s = {1, 2, 3, 2}
print(s) # {1, 2, 3}
• int → whole numbers
• frozenset → immutable set
x = 10
print(type(x)) # <class 'int'>
fs = frozenset({1, 2, 3})
• float → decimal numbers print(type(fs)) # <class 'frozenset'>
y = 3.14
print(type(y)) # <class 'float'>
Page No:- 03
PYTHON PROGRAMMING
GATE फर्रे
4. Mapping Type Syntax: string[start:end:step]
• dict → key-value pairs
s = "Python"
d = {"a": 1, "b": 2} print(s[0:4]) # "Pyth" (from index 0
print(type(d)) # <class 'dict'> to 3)
print(s[:3]) # "Pyt" (start
default 0)
5. Boolean Type
print(s[2:]) # "thon" (till end)
print(s[::-1]) # "nohtyP" (reverse)
flag = True
print(type(flag)) # <class 'bool'>
6. None Type
x = None
print(type(x)) # <class 'NoneType'>
1. What is a String?
A string is a sequence of characters enclosed in single
(' '), double (" "), or triple quotes (''' ''' or """ """).
Example:
s = "Hello Python"
print(type(s)) # <class 'str'>
2. What is String Slicing?
Slicing means extracting part of a string using
indexing.
Page No:- 04
PYTHON PROGRAMMING
GATE फर्रे
3. String Methods (Commonly Used)
Method Syntax Example Output
upper() [Link]() "hello".upper() "HELLO"
lower() [Link]() "HELLO".lower() "hello"
title() [Link]() "hello world".title() "Hello World"
strip() [Link]() " hi ".strip() "hi"
replace() [Link](old, new) "hello".replace("h","H") "Hello"
split() [Link](sep) "a,b,c".split(",") ['a','b','c']
join() [Link](list) "-".join(["a","b"]) "a-b"
find() [Link](sub) "hello".find("e") 1
count() [Link](sub) "banana".count("a") 3
startswith() [Link](val) "hello".startswith("he") True
endswith() [Link](val) "hello".endswith("lo") True
Page No:- 05
PYTHON PROGRAMMING
GATE फर्रे
What is a List?
• A list is an ordered, mutable (changeable), and indexed collection in Python.
• Written with square brackets [ ].
• Can store different data types.
Example:
my_list = [10, "hello", 3.14]
print(my_list) # [10, 'hello', 3.14]
print(type(my_list)) # <class 'list'>
2. Common List Methods
Method Syntax Example Output
append() [Link](x) l=[1,2]; [Link](3) [1,2,3]
insert() [Link](i,x) l=[1,2]; [Link](1,5) [1,5,2]
extend() [Link](iterable) l=[1]; [Link]([2,3]) [1,2,3]
remove() [Link](x) l=[1,2]; [Link](1) [2]
pop() [Link]([i]) l=[1,2]; [Link]() returns 2,
list=[1]
clear() [Link]() l=[1,2]; [Link]() []
index() [Link](x) [1,2,3].index(2) 1
count() [Link](x) [1,2,2].count(2) 2
sort() [Link]() l=[3,1,2]; [Link]() [1,2,3]
reverse() [Link]() l=[1,2]; [Link]() [2,1]
copy() [Link]() l=[1,2]; m=[Link]() m=[1,2]
Page No:- 06
PYTHON PROGRAMMING
GATE फर्रे
Method Syntax Example Output
count() [Link](x) (1,2,2,3).count(2) 2
index() [Link](x) (1,2,3).index(2) 1
1. What is a Tuple?
3. Tuple Operations
• A tuple is an ordered, immutable
(unchangeable) collection in Python. Although methods are limited, you can still:
• Written with parentheses ( ).
• Faster than lists. python
t = (1, 2, 3, 4)
Example:
print(t[1]) # Indexing → 2
python print(t[1:3]) # Slicing → (2,3)
print(len(t)) # Length → 4
my_tuple = (10, "hello", 3.14) print(max(t)) # Max → 4
print(my_tuple) # (10, 'hello', print(min(t)) # Min → 1
3.14) print(sum(t)) # Sum → 10
print(type(my_tuple)) # <class
'tuple'>
2. Tuple Methods (very few because tuples are
immutable)
Page No:- 07
PYTHON PROGRAMMING
GATE फर्रे
1. What is a Set?
• A set is an unordered collection of unique elements in Python.
• Written with curly braces { }.
• No duplicates, no indexing.
Example:
python
my_set = {1, 2, 3, 2}
print(my_set) # {1, 2, 3}
print(type(my_set)) # <class 'set'>
2. Set Methods
Method Syntax Example Output
add() [Link](x) s={1,2}; [Link](3) {1,2,3}
update() [Link](iterable) s={1}; [Link]([2,3]) {1,2,3}
remove() [Link](x) s={1,2}; [Link](1) {2}
discard() [Link](x) s={1,2}; [Link](3) {1,2} (no error)
pop() [Link]() s={1,2,3}; [Link]() removes random
element
clear() [Link]() s={1,2}; [Link]() set()
union() [Link](B) {1,2}.union({2,3}) {1,2,3}
intersection() [Link](B) {1,2}.intersection({2,3}) {2}
difference() [Link](B) {1,2,3}.difference({2,3}) {1}
symmetric_difference() A.symmetric_difference(B) {1,2}.symmetric_difference({2,3}) {1,3}
issubset() [Link](B) {1,2}.issubset({1,2,3}) True
issuperset() [Link](B) {1,2,3}.issuperset({2}) True
isdisjoint() [Link](B) {1,2}.isdisjoint({3}) True
copy() [Link]() s={1,2}; t=[Link]() {1,2}
Page No:- 08
PYTHON PROGRAMMING
GATE फर्रे
1. What is a Dictionary?
• A dictionary is an unordered collection of key–value pairs.
• Keys must be unique & immutable (like strings, numbers, tuples).
• Values can be anything.
• Written with curly braces { }.
Example:
python
my_dict = {"name": "John", "age": 25, "city": "Delhi"}
print(my_dict["name"]) # John
print(type(my_dict)) # <class 'dict'>
2. Dictionary Methods
Method Syntax Example Output
get() [Link](key[, default]) d={"a":1}; [Link]("a") 1
keys() [Link]() d={"a":1}; [Link]() dict_keys(['a'])
values() [Link]() d={"a":1}; [Link]() dict_values([1])
items() [Link]() d={"a":1}; [Link]() dict_items([('a',1)])
update() [Link](other) d={"a":1}; {'a':1,'b':2}
[Link]({"b":2})
pop() [Link](key[,default]) d={"a":1,"b":2}; returns 1, dict={'b':2}
[Link]("a")
popitem() [Link]() d={"a":1,"b":2}; removes last → ('b',2)
[Link]()
setdefault() [Link](key[,default]) d={"a":1}; {'a':1,'b':2}
[Link]("b",2)
fromkeys() [Link](keys[,value]) [Link]([1,2],0) {1:0,2:0}
copy() [Link]() d={"a":1}; x=[Link]() {'a':1}
clear() [Link]() d={"a":1}; [Link]() {}
Page No:- 10
PYTHON PROGRAMMING
GATE फर्रे
Mutability vs Immutability in Python Example:
python
1. Mutable Objects
• Can be changed (modified) after creation. import copy
• Examples → list, dict, set
list1 = [[1, 2], [3, 4]]
Example: shallow = [Link](list1)
python
shallow[0][0] = 99
lst = [1, 2, 3] print(list1) # [[99, 2], [3, 4]] ✅
lst[0] = 100 affected
print(lst) # [100, 2, 3] ✅ changed print(shallow) # [[99, 2], [3, 4]]
2. Immutable Objects 2. Deep Copy
• Creates a completely independent copy, including
• Cannot be changed after creation. nested objects.
• Any modification creates a new object. • Changes in one don’t affect the other.
• Examples → int, float, str, tuple, frozenset • Done using: [Link]().
Example: Example:
python python
s = "hello" import copy
s = s + " world"
print(s) # "hello world" (new string list1 = [[1, 2], [3, 4]]
created) deep = [Link](list1)
deep[0][0] = 99
print(list1) # [[1, 2], [3, 4]] ✅
• Mutable → changeable (list, dict, set)
not affected
• Immutable → unchangeable (int, float, str, tuple,
print(deep) # [[99, 2], [3, 4]]
frozenset)
1. Shallow Copy
Shallow Copy → Copies outer object, inner
• Creates a new object, but copies references of references shared.
inner objects.
• Changes in nested objects affect both copies. Deep Copy → Full independent clone (outer + inner).
• Done using: [Link]() or [Link]( ) or
slicing.
Page No:- 11
PYTHON PROGRAMMING
GATE फर्रे
Function in Python
A function is a block of reusable code that performs a 2. Keyword Argument
specific task.
It helps in code reusability, modularity, and • We pass arguments using parameter names.
readability. • Order does not matter.
Syntax: Syntax & Example:
python
python
def function_name(parameters):
"""docstring (optional)""" def student(name, age):
# code block print(name, age)
return value # optional
student(age=21, name="Alice") # Alice
21
Example:
python Default Argument → assigns a default value.
def add(a, b): Keyword Argument → specify by name, order-free.
return a + b
Recursion in Python
print(add(5, 3)) # 8
• Recursion is a process where a function calls itself
1. Default Argument to solve a problem.
• A parameter with a default value.
• If no value is passed, the default is used. • Every recursive function must have a base case
(stopping condition), otherwise it runs infinitely.
Syntax & Example:
python Syntax:
python
def greet(name="Guest"):
print("Hello", name) def function_name(parameters):
if condition: # base case
greet("John") # Hello John return value
greet() # Hello Guest else:
return
function_name(modified_parameters)
Page No:- 12
PYTHON PROGRAMMING
GATE फर्रे
Example: Factorial using Recursion
python
def factorial(n):
if n == 0: # base case
return 1
else:
return n * factorial(n-1) # recursive call
print(factorial(5)) # 120
Lambda Function in Python
• A lambda function is a small, anonymous (nameless) function.
• Defined using the keyword lambda.
• Can take any number of arguments but has only one expression.
Syntax:
lambda arguments : expression
Examples:
python
# Add two numbers
add = lambda a, b: a + b
print(add(5, 3)) # 8
# Square of a number
square = lambda x: x * x
print(square(4)) # 16
# Using with sort()
nums = [(1, "b"), (3, "a"), (2, "c")]
[Link](key=lambda x: x[1])
print(nums) # [(3, 'a'), (1, 'b'), (2, 'c')]
Page No:- 13