Short Notes
Short Notes
Short Notes
Immutability of Strings
InPython, stringsareimmutable.
Immutablemeans:
A stringcannot bechangedafter it iscreated.
Example
s= "Hello"
s[0] = "h"
Error
TypeError: 'str' object doesnot support itemassignment
Thisshowsthat wecannot changecharactersina string.
Example
s= "Hello"
s= s+" World"
print(s)
Output
HelloWorld
Here, Pythoncreatesa newstringinsteadof changingtheoldstring.
Effect onMemory
Becausestringsareimmutable:
● Pythoncreatesa newstringwhenchangesaremade
● Oldstringsremainunchanged
● Pythoncanreusestringsandmanagememory easily
But repeatedchangescreatemany newstrings, whichmay usemorememory.
2. Describestringoperations, stringslicingandcommonly usedstringmethodswithexamples. (AU –Nov/Dec2025)[UN]
StringOperations
Stringoperationsareactionsperformedonstrings.
1. Concatenation(+)
It isusedtojointwostrings.
Example
a = "Hello"
b = "Python"
print(a +" " +b)
Output
HelloPython
2. Repetition(*)
It isusedtorepeat a string.
Example
word= "Hi "
print(word* 3)
Output
Hi Hi Hi
3. Membership(in, not in)
It checkswhether a wordexistsina string.
Example
text = "Programming"
print("gram"intext)
Output
True
4. StringSlicing
Stringslicingmeanstakinga part of a stringusingindex numbers.
Syntax
string[start : end: step]
start –startingposition
end–endingposition
step–skipcharacters
Example
s= "PythonProgramming"
print(s[0:6])
print(s[6:])
print(s[::2])
Output
Python
Programming
PtoPormig
Negativeindex example
print(s[-5:])
Thisprintsthelast 5characters.
CommonStringMethods
Pythonprovidesbuilt-infunctionsfor strings.
1. lower() andupper()
Convert letterstolowercaseor uppercase.
Example
name= "Python"
print([Link]())
print([Link]())
Output
python
PYTHON
2. strip()
Removesspacesfromthebeginningandend.
Example
text = " hello "
print([Link]())
Output
hello
3. replace()
Replacesonewordwithanother.
Example
msg= "I likeJava"
print([Link]("Java", "Python"))
Output
I likePython
4. split()
Splitsa stringintoa list.
Example
line= "apple,banana,orange"
print([Link](","))
Output
['apple', 'banana', 'orange']
5. find()
Findsthepositionof a character ina string.
Example
word= "Python"
print([Link]("t"))
Output
2
Logic
1. Readthevalueof N
2. Set sum= 0
3. Usea looptoaddnumbersfrom1toN
4. Print thefinal sum
PythonProgramUsingfor Loop
n= int(input("Enter thevalueof N: "))
total = 0
for i inrange(1, n+1):
total = total +i
print("Sumof first", n, "natural numbersis:", total)
Explanation
● nstoresthenumber of natural numbers.
● total storesthesum.
● Thefor looprunsfrom1ton.
● Eachnumber isaddedtototal.
● After theloopends, thefinal sumisprinted.
Example
Input
Enter thevalueof N: 5
Calculation
1+2+3+4+5= 15
Output
Sumof first 5natural numbersis: 15
UsingBuilt-inFunction
import math
num= float(input("Enter a number: "))
result = [Link](num)
print("Squareroot of thenumber is:", result)
Explanation:
1. Import themathmoduletousesqrt().
2. Readthenumber fromtheuser andstoreinnum.
3. Computethesquareroot [Link](num)andstoreinresult.
4. Print theresult.
ExampleExecution:
Input:
Enter a number: 25
Output:
Squareroot of thenumber is: 5.0
EuclideanAlgorithmfor GCD
TheEuclideanalgorithmisbasedontheprinciple:
GCD(a,b)=GCD(b,amodb)
● Repeat theprocessuntil theremainder becomeszero.
● Thelast non-zerodivisor isthe GCD.
AlgorithmSteps
1. Readtwointegersa andb.
2. Whileb isnot zero:
o Assigna = b
o Assignb = a %b
3. Whenb becomeszero, a istheGCD.
PythonProgramUsingFunction
def gcd(a, b):
whileb != 0:
a, b = b, a %b
returna
x = int(input("Enter first number: "))
y = int(input("Enter secondnumber: "))
result = gcd(x, y)
print("GCDof thegivennumbersis:", result)
Explanationof theProgram
● gcd() functiontakestwonumbersasinput.
● Thewhilelooprepeatedly appliesthemodulooperation.
● Tupleassignment (a, b = b, a %b) updatesvaluesefficiently.
● Whenb becomeszero, theloopstopsanda holdstheGCD.
ExampleExecution
Input:
Enter first number: 48
Enter secondnumber: 18
Output:
GCDof thegivennumbersis: 6
Control FlowRepresentation
Control flowistheorder inwhichstatementsareexecuted.
Flowchartsshow:
● Sequential execution–stepshappenoneafter another
● Conditional branching–decisionsintheprogram
● Looping/ Iteration–repeatingsteps
By followingthearrows, wecanunderstandhowtheprogrammovesfromstart toend.
CommonFlowchart Symbols
Symbol Meaning
Oval Start / End
Parallelogram Input / Output
Rectangle Processingstep
Diamond Decisionmaking
Arrow Directionof control flow
Example: CheckingEvenor OddNumber
Advantagesof Flowcharts
● Makesprogramlogiceasy tounderstand
● Helpsidentify logical errors
● Actsasa blueprint beforecoding
● Useful for documentationandteaching
Linear Search
Steps:
1. Readthenumber of elementsandstorethemina list.
2. Readtheelement tosearch(key).
3. Start fromthefirst element.
4. Comparethecurrent element withthekey.
5. If found, display thepositionandstop.
6. If not foundafter checkingall elements, display “not found.”
PythonProgram(User Choice)
n= int(input ("Enter number of elements: "))
arr = []
for i inrange(n):
[Link](int(input ("Enter element: ")))
key = int(input ("Enter element tosearch: "))
found= False
for i inrange(n):
if arr[i] == key:
print("Element foundat position", i +1)
found= True
break
if not found:
print("Element not found")
Explanation:
● Theprogramcheckseachelement inthelist.
● If thekey matches, it printstheposition.
● If nomatchisfound, it prints“Element not found.”
Binary Search
Steps:
1. Readthenumber of elementsandstorethemina list.
2. Sort thelist inascendingorder.
3. Readtheelement tosearch(key).
4. Set low= 0andhigh= n-1.
5. Findthemiddleelement.
6. If middleelement = key, display position.
7. If key < middleelement, searchinleft half.
8. If key >middleelement, searchinright half.
9. Repeat until element isfoundor list isexhausted.
PythonProgram(User Choice)
n= int(input ("Enter number of elements: "))
arr = []
for i inrange(n):
[Link](int(input ("Enter element: ")))
[Link]()
print("Sortedlist:", arr)
key = int(input ("Enter element tosearch: "))
low= 0
high= n–1
found= False
while low<= high:
mid= (low+high) // 2
if arr[mid] == key:
print("Element foundat position", mid+1)
found= True
break
elif key < arr[mid]:
high= mid–1
else:
low= mid+1
if not found:
print("Element not found")
Explanation:
● Thelist issortedfirst.
● Theprogramcomparesthekey withthe middleelement .
● If not equal, it searchesinleft or right half.
● Repeatsuntil theelement isfoundor thelist ends.
ProgramLogic
1. Readthenumber of elementsinthearray.
2. Storetheelementsina list.
3. Initializea variabletotal tostorethesum.
4. Traversethearray andaddeachelement tototal.
5. Display thefinal sum.
PythonCode(UsingLoop)
n= int(input ("Enter number of elements: "))
arr = []
for i inrange(n):
[Link](int(input ("Enter element: ")))
total = 0
for numinarr:
total += num
print("Sumof array elements:", total)
Explanation:
● Theprogramreadsthenumber of elementsandstoresthemina list arr.
● total isinitializedto0.
● Eachelement of arr isaddedtototal usinga loop.
● Thefinal sumisdisplayed.
AlternativeMethodUsingBuilt-inFunction
Pythonprovidesa built-infunctionsum() tocalculatethesumeasily:
total = sum(arr)
print("Sumof array elements:", total)
● sum(arr) automatically addsall elementsof thelist.
● Thismethodissimpler andfaster for programmingtasks.
Explanation:
● Theloopbody executesfirst.
● Theconditionischeckedusinganif statement toterminate theloop.
DifferenceBetweenEntry-ControlledandExit-ControlledLoops
Feature Entry-ControlledLoop Exit-ControlledLoop
Conditionchecking Beforeloopbody After loopbody
Minimumexecution Zerotimes At least once
Looptypes for, while do–while(simulated)
Suitability Whenconditionmust bemet first Whenoneexecutionismandatory
10. What isfunction? Explainthetypesof argumentswithanexample. Analyzewhichargument typewill bebest one. (AU –
Nov/Dec2025)[AN]
● A functionisa namedblock of reusablecodethat performsa specifictask.
● Functionshelpinmodular programming, reducerepetition, andimprovereadability.
● InPython, functionsaredefinedusingthe def keyword.
Example:
def greet():
print("Hello, World!")
greet()
Typesof Arguments
1. Positional Arguments
● Passedinthesameorder asparametersaredefined.
● Number andpositionmust matchexactly.
Example:
def add(a, b):
returna +b
print(add(10, 20)) # Output: 30
2. KeywordArguments
● Passedusingparameter names.
● Order doesnot matter.
● Improvesclarity andreduceserrors.
Example:
def add(a, b):
returna +b
print(add(b=20, a=10)) # Output: 30
3. Default Arguments
● Parametershavedefault values.
● If novalueisprovided, thedefault valueisused.
Example:
def add(a, b=5):
returna +b
print(add(10)) # Output: 15
4. Variable-LengthArguments
● Usedwhenthenumber of argumentsisnot fixed.
● Representedusing*args.
Example:
def total(*numbers):
s= 0
for ninnumbers:
s+= n
returns
print(total(1, 2, 3, 4)) # Output: 10
List Slicing
List slicingisusedtoextract a portionof a list.
Syntax: list[start : end: step]
Example
nums= [10,20,30,40,50]
print(nums[1:4])
print(nums[:3])
print(nums[::2])
CommonList Methods
● append() –Addselement at theend.
● insert() –Insertselement at a specificposition.
● remove()–Removesa specificvalue.
● pop() –Removeselement by index.
● sort()–Sortsthelist.
● reverse() –Reversesthelist.
● len() –Returnsnumber of elements.
Aliasingof Lists
Aliasingoccurswhentwovariablesrefer tothesamelist inmemory. If onevariablechangesthelist, thechange
will appear intheother variablealso.
Example
list1= [1, 2, 3]
list2= list1
[Link](4)
print(list1)
print(list2)
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
Bothvariablespoint tothesamelist, sochangesaffect both.
Problemsof Aliasing
● Unwantedsideeffects
● Difficult debugging
● Unexpecteddata changes
Cloningof Lists
Cloningmeanscreatinga separatecopy of a list. Changesinonelist will not affect theother.
Methodsof Cloning
1. Usingslicing
list1= [1,2,3]
list2= list1[:]
2. Usinglist() function
list2= list(list1)
3. Usingcopy() method
list2= [Link]()
DifferenceBetweenAliasingandCloning
Aspect Aliasing Cloning
Memory reference Sameobject Different objects
Data modification Affectsall references Independent changes
Safety Risky Safe
List inPython
A list isanorderedandmutablecollectionof elements. It iswrittenusingsquarebrackets[ ]. Sincelistsare
mutable, their elementscanbechangedafter creation.
Example
lst = [10, 20, 30]
lst[1] = 25
print(lst)
TupleinPython
A tupleisanorderedandimmutablecollectionof elements. It iswrittenusingparentheses( ). Oncea tupleis
created, itselementscannot bemodified.
Example
tup= (10, 20, 30)
print(tup)
DifferencesBetweenList andTuple
Feature List Tuple
Syntax [ ] ( )
Mutability Mutable Immutable
Modification Allowed Not allowed
Performance Slower Faster
Memory usage More Less
Dictionary key Not allowed Allowed
Methods Many methods Limitedmethods
AppropriateUseCases
Listsareusedwhen:
● Data needstobemodifiedfrequently
● Elementsare addedor removed
● Operationslikesortingor insertingareneeded
Examples:
Student markslist, shoppingcart items, dynamicdata.
Tuplesareusedwhen:
● Data shouldremainconstant
● Data integrity isimportant
● Storingfixedrecords
Examples:
Coordinates(x, y), daysof theweek, functionreturnvalues.
4. ExplaindictionariesinPythonanddescribehowdictionariesarecreated, accessedandmodifiedwithsuitableexamples.
(VSBEC- Nov/Dec2024)[UN]
A dictionary inPythonisa built-indata typeusedtostoredata askey–valuepairs. Dictionariesallowfast access
tovaluesusinguniquekeys. They aremutable, meaningtheir contentscanbechangedafter creation.
Dictionary Example
A dictionary iscreatedusingcurly braces{ } anda colon(:) betweenkey andvalue.
student = {"roll_no": 101, "name": "Arun", "marks": 85}
Here:
● Keys: roll_no, name, marks
● Values: 101, "Arun", 85
Characteristicsof Dictionaries
● Storedata as key–valuepairs
● Keysmust beuniqueandimmutable
● Valuescanbeany data type
● Mutableandsizecanchange
● Providefaster data access
CreatingDictionaries
1. UsingCurly Braces
emp= {"id": 1, "name": "Ravi", "salary": 30000}
2. Usingdict() Function
emp= dict(id=2, name="Kumar", salary=35000)
AccessingDictionary Elements
Valuesareaccessedusingkeys.
print(student["name"])
print([Link]("marks"))
Theget() methodavoidserrorsif thekey isnot present.
ModifyingDictionaries
Updatinga value
student["marks"] = 90
Addinga newkey–valuepair
student["grade"] = "A"
Deletinganelement
del student["roll_no"]
ExampleProgram
student = {"name": "Anu", "marks": 78}
student["marks"] = 85
student["result"] = "Pass"
print(student)
Output
{'name': 'Anu', 'marks': 85, 'result': 'Pass'}
BasicDictionary Operations
1. AccessingValues
Valuesareaccessedusingkeys.
student = {"name": "Ravi", "marks": 82}
print(student["marks"])
2. UpdatingValues
student["marks"] = 90
3. AddingNewKey–ValuePair
student["grade"] = "A"
4. DeletingElements
del student["name"]
CommonDictionary Methods
keys() –Returnsall keys.
print([Link]())
values() –Returnsall values.
print([Link]())
items() –Returnskey–valuepairs.
print([Link]())
get() –Returnsvalueof a key safely.
print([Link]("marks"))
update() –Updatesdictionary withanother dictionary.
[Link]({"marks": 95, "result": "Pass"})
pop() –Removesa key andreturnsitsvalue.
[Link]("grade")
ProcessingKey–ValuePairsUsingLoops
TraversingKeys
for key instudent:
print(key)
TraversingValues
for [Link]():
print(value)
TraversingKey–ValuePairs
for key, [Link]():
print(key, value)
ExampleProgram
marks= {"Maths": 85, "Physics": 78, "Chemistry": 90}
total = 0
for subject, mark [Link]():
total += mark
print("Total Marks:", total)
AdvancedList ProcessingTechniques
Advancedprocessingmainly involves:
● Transformingelements
● Filteringelementsusingconditions
● Aggregation(sum,max, min)
● Creatingnewlists
Theseoperationscanbedoneusingloops, built-infunctions, or list comprehension.
FilteringElementsUsingLoop
Filteringselectselementsthat satisfy a condition.
numbers= [1, 2, 3, 4, 5, 6]
even= []
for ninnumbers:
if n%2== 0:
[Link](n)
print(even)
MappingElements(Transformation)
Mappingmeansapplyinganoperationtoeachelement.
numbers= [1, 2, 3, 4]
squares= []
for ninnumbers:
[Link](n* n)
print(squares)
List Comprehension
List comprehensionisa short andpowerful way tocreatelists.
Syntax
[expressionfor iteminiterableif condition]
Example
numbers= [1, 2, 3, 4, 5]
squares= [n* nfor ninnumbers]
print(squares)
List ComprehensionwithCondition
numbers= [1, 2, 3, 4, 5, 6]
even_numbers= [nfor ninnumbersif n%2== 0]
print(even_numbers)
NestedList Comprehension
matrix = [[1, 2], [3, 4], [5, 6]]
flattened= [numfor rowinmatrix for numinrow]
print(flattened)
Comparison
Aspect Loop List Comprehension
Codelength Longer Short
Readability Moderate High
Performance Slower Faster
PythonProgramtoGeneratea Histogram
values= [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
histogram= {}
for valueinvalues:
if valueinhistogram:
histogram[value] += 1
else:
histogram[value] = 1
print("Histogram:")
for key inhistogram:
print(key, ":", histogram[key])
Explanationof theProgram
● Thelist valuescontainstheinput data.
● Anempty dictionary histogramisusedtostorefrequency counts.
● Thefor looptraverseseachelement inthelist.
● If theelement already existsasa key inthedictionary, itscount isincremented.
● Otherwise, a newkey iscreatedwithaninitial count of 1.
● Finally, thedictionary isdisplayedasa histogram.
SampleOutput
Histogram:
1: 1
2: 2
3: 3
4: 4
8. Developa Pythonprogramfor retail bill preparationusingdictionariesandlistsandexplainthesequenceof operations
involved. (VSBEC- Apr/May 2025)[CR]
A retail bill preparationsystemcalculatesthetotal amount payableby a customer basedonpurchaseditems, their
quantities, andprices. InPython, thiscanbeimplementedusingliststostoreitemsanddictionariestostoreprices.
PythonProgram
items= ["Rice", "Sugar", "Oil"]
prices= {"Rice": 50, "Sugar": 40, "Oil": 120}
total = 0
print("RETAILBILL")
for iteminitems:
qty = int(input(f"Enter quantity of {item}: "))
cost = qty * prices[item]
print(item,":", qty, "x", prices[item], "=", cost)
total += cost
print("Total Amount:", total)
Explanationof theProgram
● Thelist items storesthenamesof availableproducts.
● Thedictionary prices storespriceinformationusingitemnamesaskeys.
● A looptraversesthelist of items.
● Quantity isreadfromtheuser for eachitem.
● Cost iscalculatedusingquantity ×price.
● Thetotal bill amount isaccumulatedanddisplayed.
SampleOutput
RETAILBILL
Enter quantity of Rice: 2
Rice: 2x 50= 100
Enter quantity of Sugar: 1
Sugar : 1x 40= 40
Enter quantity of Oil: 1
Oil : 1x 120= 120
Total Amount: 260
2. AccessingTupleElements(Indexing)
Tupleelementsareaccessedusingindex numbersstartingfrom0.
t = (10, 20, 30, 40)
print(t[0])
print(t[-1])
3. TupleSlicing
Slicingextractspart of a tuple.
print(t[1:3])
print(t[:2])
print(t[::2])
Output
(20, 30)
(10, 20)
(10, 30)
4. TupleConcatenation
Tuplescanbecombinedusingthe +operator.
a = (1, 2)
b = (3, 4)
c= a +b
print(c)
5. TupleRepetition
The* operator repeatstupleelements.
t = (5, 10)
print(t * 3)
6. MembershipOperation
Checksif anelement existsina tuple.
t = (10, 20, 30)
print(20int)
print(40not int)
Built-inFunctionswithTuples
len() –Returnsnumber of elements
print(len(t))
max() andmin() –Largest andsmallest elements
print(max(t))
print(min(t))
sum() –Sumof numericelements
print(sum(t))
TupleMethods
Becausetuplesareimmutable, they haveonly twomethods.
count() –Countsoccurrencesof anelement
t1= (10, 20, 10, 30)
print([Link](10))
index() –Returnsindex of first occurrence
print([Link](20))
ProgramLogic
● Reada tupleandanelement fromtheuser.
● Usethecount methodtofindthenumber of occurrences.
Code:
t = (1, 2, 3, 2, 4, 2, 5)
element = int(input("Enter element: "))
count = [Link](element)
print("Number of occurrences:", count)
Explanation
Thecount methodreturnsthenumber of timesthespecifiedelement appearsinthetuple.
7. Developa Pythonprogramtoreaduser data, writeit intoa fileandcopy thecontentstoanother file. (VSBEC- Nov/Dec
2024)[CR]
8. Developa Pythonprogramtovalidatevoter’sagebetween18and100usingsuitableexceptionhandlingmechanism.(VSBEC-
Nov/Dec2024)[AP]
9. ExplaincommandlineargumentsinPythonanddescribehowthey areaccessedina program.(VBSEC–Apr/May 2025)[UN]