0% found this document useful (0 votes)
6 views88 pages

Python Programming - 2026 Batch

The document provides an introduction to Python, covering its characteristics, applications, and basic concepts such as variables, constants, and functions. It includes details on how to download Python, naming rules for variables, the print() and input() functions, comments, type conversion, and operators. Additionally, it features examples and exercises to reinforce learning.
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)
6 views88 pages

Python Programming - 2026 Batch

The document provides an introduction to Python, covering its characteristics, applications, and basic concepts such as variables, constants, and functions. It includes details on how to download Python, naming rules for variables, the print() and input() functions, comments, type conversion, and operators. Additionally, it features examples and exercises to reinforce learning.
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

Introduction to Python (igjd; gw;wpa mwpKfk;)

• igjd; vd;gJ xU cau;kl;l (High Level), Interpreted, nghJ Nehf;f fzpdp nra;epuy;
nkhopahFk;. ,k; nkhopahdJ Guido van Rossum vd;gtuhy; cUthf;fg;gl;lJ. (The first
release was in 1991).

When to Use Python?


1. Web Development (server-side)
2. Data Science Application
3. Scripting
4. Desktop GUI Applications
5. Business Applications
6. Engineering Applications

• igjd; MdJ gy;NtW ,af;fKiwikfspYk; (O/S) ,aq;ff;$baJ. mj;Jld; C, C++,


C#, Java, Php, Perl Nghd;w midj;J epuyhf;f nkhopfSld; xj;jpirAk; tz;zk;
tbtikf;fg;gl;Ls;sJ.

Characteristics of Python
1. Easy-to-learn (fw;gjw;F ,yF)
2. Easy-to-read (thrpg;gjw;F ,yF)
3. Easy-to-Maintain (guhkupj;jy; ,yF)
4. A broad standard library (gue;j mstpyhd gy library cs;sd)
5. Portable - igjd; gue;j mstpyhd td;nghUs; jsq;fspy; ,aq;ff;$baJ. mj;Jld;
midj;J ,aq;Fjsq;fspYk; xNu tpjkhd ,ilKfj;ijf; nfhz;Ls;sJ.
6. GUI Programming - Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.

How to Download Python?


• You can download Python documentation from [Link] The documentation is
available in HTML, PDF, and PostScript formats.
• The most up-to-date and current source code, binaries, documentation, news, etc., is available on the
official website of Python [Link]

Variables (khwpfs;)
• juTfis epidtfj;jpy; jw;fhypfkhf Nrkpj;J itg;gjw;fhf gad;gLj;jg;gLk; ngau;fs;
khwpfs; vdg;gLk;.
A variable is a name that stores a value which can change during program execution.

• ,it nra;epuypy; epiyahff; fhzg;glhky; mjd; ngWkhdk; khwpf;nfhz;L nry;Yk;.

• x = 10
x = 20

• Here, x is a variable because its value changes.

1 of 87
Constants/ Literals - khwpypfs;
• ,J epiyahd nghUs; vdg;gLk;. mjhtJ> ,J nra;epuypy; khwhj;jd;ik cilajhff;
fhzg;gLk;.
A constant is a name that stores a value which should not change during program execution.

• Python does not enforce constants.


• Constants are created by naming convention (uppercase letters), not by language rules.

cjhuzk;:
PI = 3.14159

khwpfSf;Fg; ngaupLk; NghJ ftdpf;fg;gl Ntz;ba tplaq;fs;


Naming rules for variables in Python
1) khwpapd; Kjy; vOj;J vg;NghJk; Mq;fpy vOj;jhf my;yJ fPo;Nfhlhf ( _ ) Underscore
fhzg;gly; Ntz;Lk;. mijj; njhlu;e;J tUgit ,yf;fkhfNth my;yJ vOj;jhtNth
my;yJ fPo;f;NfhlhfNth fhzg;glyhk;.
A variable name must start with a letter (a–z, A–Z) or an underscore (_)

2) khwpfspd; ngau;fSf;fpilapy; ,ilntsp ,Uj;jy; $lhJ.


No spaces are allowed in variable names
myvar=10 ✔ my_var=10 ✔ my var=10 ✘

3) khwpfspd; ngau;fSf;fpilapy; Underscore ( _ ) FwpaPl;ilj; jtpu NtW ve;jf;


FwpaPilAk; gad;gLj;jf; $lhJ.

4) igjdpy; ghtpg;gjw;fhf xJf;fg;gl;l fl;lisr; nrhw;fis khwpahfg; gad;gLj;j


KbahJ.
Python keywords cannot be used as variable names

Reserved words
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except,
finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while,
with, yield
To check the keyword list, type following commands in interpreter
import keyword
[Link]

5) Variable names are case-sensitive


• age, Age, and AGE are different variables

2 of 87
nry;Ygbahd (valid) kw;Wk; nry;Ygbaw;w (invalid) khwpfSf;F cjhuzk; gpd;tUkhW>

1. Var = 10 ✔
2. my_var = 10 ✔
3. _my_var = 10 ✔
4. myVar = 10 ✔
5. MYVAR = “Raj” ✔
6. Myvar1 = “Raj” ✔
7. _1myvar = 10 ✔

1. 1Myvar = 10 ✘
2. my-var = 10 ✘
3. my var = 10 ✘
4. my#var = 10 ✘
5. _my$var=10 ✘
6. 5_var = 10 ✘
7. _#Comment = 10 ✘

Python print() Function


• The print() function is used to display output on the screen.
• Basic Examples
1. print("Hello World!") → Hello World!
2. print('Hello World!') → Hello World!
3. print('Hello + 10') → Hello + 10
4. print("10+5") → 10+5
5. print("Is it clear?") →Is it clear?

fPNo jug;gl;Ls;s igjd; FwpKiwapd; ntspaPl;bid vOJf.


1. print("Welcome to my python class - 6. print("Hello", 2026)
2026")

2. print('Hi! I am Sathith') 7. print(2026, "A/L")

3. print(I’m learning Python) 8. print(10*2, "Year", '20+6')

4. print(" 'Python' ") 9. print('It"s my Python class")

5. print("‘Python’") 10. print('It's my Python class')

11. print("It"s my Python class') 12. print("It"s my Python class")

3 of 87
13. print("It's Clear in 2026?") 15. print("It's my coding style")

14. print('It's my coding style') 16. Print("Oh My God!")


print('it's my coding style")
17. print("Simple Python!")

18. print("Object Oriented Programming Language")

Escape Characters in Python


1. '\n' → New line (moves cursor to next line)
2. '\t' → Horizontal tab (gives space)
3. '\\' → Backslash (\)
4. '\'' → Single quote (')
5. '\"' → Double quote (")

1. print("Python Programming") 12. print("Python\\\nClass")

2. print('Python\tProgramming') 13. print("Python\\nTutorial")

3. print("Python Tutorial") 14. print("Python\n\tTutorial")

4. print(Python) 15. print("Python\t\nPython")

5. print("Python\ttutorial") 16. print("Python\nPython")

6. print("Python\\tutorial")

7. print("Python\\\tutorial")

8. print("Python\\\\Class")

9. print("Python\\\\\Class")

10. print("Python\\ Class")

11. print("Python\\nClass")

4 of 87
Python input() Function
• The input() function is used to take input from the user through the keyboard.

• When the program reaches input(), it waits for the user to type a value and press Enter.
The entered value is always treated as text (string) by default.

• It always returns a string. Use int() or float() to convert input for calculations

Basic Syntax
variable = input()
or
variable = input("Message to user")

Example:

"Sparking minds, The best education"– [Link]


age = input("Enter your age: ")
print(age)

If user enters: 18 then output will be 18

Exercise:
1. msg = input("Message: ")
print("Your message is", msg)

2. num = input("Enter a number: ")


print(num + 10)

3. x = input("Enter value: ")


print(x + x)

4. name = input("Name: ")


print("Welcome", name)

5. print(input("Enter word: ") + " Class")

6. text = input("Enter text: ")


print(text + "2026")

7. num = int(input("Enter a number: "))


result = num + 10
print("Result:", result)

5 of 87
8. length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print("Area =", area)

Python Comments
Programming languages are like conversations between humans and machines. The machine only cares
about instructions. Humans, however, need context. Comments are the little notes programmers leave for
each other and for their future selves, who will inevitably forget why something clever was written at 2 AM.
In Python, comments are pieces of text that the interpreter ignores. They are used to explain code,
describe logic, or temporarily disable parts of a program during testing.
nra;epunyhd;wpd; Fwpg;gpl;l $w;Wf;fspid tpgupg;gjw;fhf toq;fg;gLk; $w;Wf;fs;. vjpu;fhyj;jpy;
Fwpj;j nra;epunyhd;wpid Fwpj;j egu; my;yJ NtnwhUtu; mwpe;J nfhs;tjw;fhf toq;fg;gLk;.
FwpKiwfshdJ ntspaPl;by; vt;tpj khw;wj;jpidAk; Vw;gLj;jhJ. igjd; nra;epuyhf;fj;jpy;
gpd;tUkhW Fwpg;Giu toq;fg;gLk;.
Single-Line Comment (#)
# This is a comment

"Sparking minds, The best education"– [Link]


print("Hello World")

# Calculate the sum of two numbers


num1 = 10
num2 = 20
total = num1 + num2 # Adding two numbers
print(total)
Multi-Line Comments
"""
This program calculates
the area of a rectangle
using length and width
"""
length = 5
width = 3
area = length * width
print("Area =", area)

6 of 87
Python Casting - Type Conversion
• juTfis xU tifapy; ,Ue;J ,d;DnkhU tiff;F khw;Wtjw;fhf ,e;;j El;gk;
gad;gLj;jg;gLfpd;wJ.
1) x = int(312) 5) y = float(9.63) 9) x = float("45")
print(x) print(y) print(x)

2) a = str(98) 6) x = int("34") 10) x = int("18.9")


print(a) print(x) print(x)
print(type(a)) print(type(x))

11) q = float("760")
3) x = int(4.72) 7) p = float("Coding") print(q)
print(x) print(p) print(type(q))

"Sparking minds, The best education"– [Link]


4) y = float(250) 8) r = float("581.7") 12) x = int("200")
print(y) print(r) y = float("5")
print(type(y)) print(x + y)

igjdpy; gad;gLj;jg;gLk; ,af;fpfs; / nraypfs; (Python Operators)


• igjdpy; gpd;tUk; ,af;fpfs; (Operators) gad;gLj;jg;gLfpd;wd.

1. vz;fzpj ,af;fpfs; (Arithmetic Operators)


2. xg;gil ,af;fpfs; (Assignment Operators)
3. xg;gPl;L ,af;fpfs; (Comparison Operators/ Relational Operators)
4. ju;f;ftpay; ,af;fpfs; (Logical Operators)
5. milahsg;gLj;jp ,af;fpfs; (Identity Operators)
6. mq;fj;Jt ,af;fpfs; (Membership Operators)
7. Bit njhlu;ghd ,af;fpfs; (Bitwise Operators)

Arithmetic Operators
Operators Name
+ $l;ly; (Addition)
- fopj;jy; (Subtraction)
* ngUf;fy; (Multiplication)
/ gpupj;jy; (Division)
% kPjp gpupg;ghd; (Modulus)
** mLf;F/ tY (Exponentiation/ power)
// Floor Division

7 of 87
1) x = 12 15) -7 * -8 30) 84 / 12.0
y = 38
x+y
16) 14 % 4 31) 24 % -7

2) 15 * 12
17) 6**3 32) -5**2

3) 7 * 3.5
18) -54 + 80 33) 85 - 120

4) 72.0 / 9.0
19) 7 * 14.0 34) 12.0 / 48

5) 72.0 / 9
20) 35 % 6 35) 24 % -5

6) 28 % -5

"Sparking minds, The best education"– [Link]


21) 8**2.0 36) (-5)**2

7) 28 % -6
22) 20 - 9 37) -3**7

8) a = 18
b = 7.0 23) 96 / 6 38) 6 // 3
a + b + 12

24) 7 % 15 39) 7.8// 2


9) 9 * (-7)

25) 9**3 40) -9 // 3


10) -8 * 11

26) 20.0 - 9 41) (-3)**7


11) 14 % 3

27) 81 / 9 42) 10 // 5
12) 9 % 4

28) 15 % 120 43) 6 // -3


13) 35 % -9

29) 5**3 44) -6 // -3


14) 63 % -12 -75 - 25
15 + 6.0
45) -3 // -6

8 of 87
Exercise : fPNo jug;gl;Ls;s igjd; vz;fzpj nraw;ghLfisj; jPu;f;f.

Kd;Dupik tupir (Priority Order)


1. ( ) – milg;G
2. **
3. *, /, %, // → ,lkpUe;J tyk; Nehf;fp
4. +, - → ,lkpUe;J tyk; Nehf;fp
midj;J nraw;ghLfSk; ,lkpUe;J tyk; Nehf;fpathW Kd;Dupik mbg;gilapy; Nkw;nfhs;sg;gLk;.
1) 4**2*(6+2)/5 6) (45-38)+6%3**5/4

2) (3+8)//4*7-3/3 7) 5**3-(4%7)+3/5*8

3) 7%3/2+5**2-8//3 8) (4%11)+20-6/8*5//4**3*3

"Sparking minds, The best education"– [Link]


4) 8*5//4*(7%4)+30%7 9) 30+(14//6)*3-3**3/3

5) 6*3+(10-5)**2%4 10) 7*5+(18/6)+4-3**3

Assignment Operators

Operator Example xNu jlitapy; gy khwpfis tiuaiw


= x=10 nra;Ak; Kiw
+= x+=5
-= x-=5 x=y=z=10 → x,y,z Mfpa %d;W khwpfspd;
ngWkhdq;fs; 10 MFk;.
*= x*=5
/= x/=5 x,y,z= “Hi”,10,15.0 → ,q;F x,y,z Mfpa
%= x%=5 khwpfspd; ngWkhdq;fs; KiwNa “Hi”,10,15.0
//= x//=5
**= x**=5 x=10; y=”Hi” → ,q;F x,y ,d; ngWkhdq;fs;
|= x|=5 KiwNa 10, “Hi”
^= x^=5
>>= x >> =5
<<= x << =5

9 of 87
1) a = 15 9) a //= b
b=6 print(a)
a += 4
a += b
print(a) 10) x += y
z -= x
print(z)
2) x = 7
y = 12
z=5 11) b *= 8.0
x *= y print(b)
y *= x
print(z)
12) x //= z
x //= y
3) a %= b print(x)
print(a)

"Sparking minds, The best education"– [Link]


13) a += b
4) z += y b -= a
print(x) b=a
a += 12
a *= b
5) b %= a print(a)
print(b)

14) print(b)
6) print(x)

15) y += x
7) print(z) z *= 5
a /= 3 print(z)
b /= a
print(b, a)
16) print(x)

8) x %= 6
print(x + z)

10 of 87
Comparison Operators/ Relational Operators
,uz;L my;yJ mjw;F Nkw;gl;l $Wfis xg;gPL nra;J True my;yJ False Mfpa ,U
KbTfspy; VjhtJ xd;iwg; ngWtjw;fhf ,t; ,af;fp gad;gLj;jg;gLfpd;wJ.
,q;F $w;W cz;ik vdpd; True vDk; tpisTk;> $w;W ngha; vdpd; False vDk; tpisTk;
ngwg;gLk;.
1. Equal ==
2. not equal !=
3. Greater than >
4. Less than <
5. Greater than and equal >=
6. Less than and equal <=
Priority Order → ==, !=, >=, >, <=, <
1) 7 = 3 7) 6 != 4

2) 18 < 12 8) 25 != 19

"Sparking minds, The best education"– [Link]


3) 6 == 6 9) 3 > 7

4) 14.0 <= 11 10) 30 >= 25

5) 6 != 6 11) 12 > 12

6) 13 < 21 12) 19 > 15 == 14 < 12

Logical Operator
,J epge;jidf; $w;Wf;fis ,izg;gjw;fhf gad;gLj;jg;gLfpd;wJ.
Logical Operator gad;gLj;jg;gLk; NghJ True my;yJ False vDk; tpisT fpilf;Fk;.
1. NOT → ,q;F $w;W True vdpd; False vdTk;> $w;W False vdpd; True vdTk; tpist
fpilf;Fk;.
2. AND → ,q;F ,U $w;Wf;fSk; True fhzg;gbd; khj;jpuNk tpisT True MFk;.
3. OR → ,q;F VjhtJ xU $w;W True Mf fhzg;gbd; ntspaPL True Mf fpilf;Fk;.
Priority Order → NOT, AND, OR

11 of 87
1) 12 > 5 and 5 < 12 6) 8 < 12 and 15 > 10

2) 18 > 18 or 16 < 20 7) 20 >= 20 or 18 < 15

3) 14 > 20 and 19 >= 19 or 22 > 10 8) 13 > 17 and 21 >= 21 or 9 > 3

4) 25 == 25 or 20 > 18 and 16 <= 16 or 14 > 11 9) 30 == 30 or 25 > 20 and 12 <= 14

5) 90 > 30 and 25 != 20 or 10 > 12 10) 70 > 50 and 40 != 30 or 15 > 25

Identity Operator
xU nghUs; epidtfj;jpy; Fwpg;gpl;l ,lj;jpid Rl;bf;fhl;Lfpd;wjh? vd;gij rupghu;g;gjw;fhf
gad;gLj;jg;gLfpd;wJ. ,q;F True my;yJ False Mfpa ,uz;L tpisTfs; ngwg;gLk;. ,jpy;

"Sparking minds, The best education"– [Link]


gpd;tUk; ,uz;L tifahd Operators gad;gLj;jg;gLfpd;wd.
1. is
2. is not
In Python, the Identity Operator is used to check whether two variables refer to the same object in
memory. It does not check whether the values are equal; instead, it checks whether both variables point to
the exact same location in memory.

Operator Meaning
is Returns True if both variables refer to the same object
is not Returns True if both variables refer to different objects

1) a = ["python", "code"] 2) x = ("data", "science")


b = ["python", "code"] y = ("data", "science")
a is b x is y

a == b y is x

a is not b x == y

x is not y

12 of 87
3) a = "Programming" 4) a = 8
b = "Programming" b=8
a is b b is not a

b is a a is b

a == b a == b

a is not b c=a
a is c

c is a

c == a

a is not c

"Sparking minds, The best education"– [Link]


Membership Operators
nrhw;fspy; fhzg;gLfpd;w vOj;Jf;fshdJ kw;iwajpy; fhzg;gLfpd;wjh vdg; guPl;rpg;gjw;F ,J
gad;gLj;jg;gLfpd;wJ. ,jd; %yk; True my;yJ False Mfpa ,uz;L tpisTfs; ngwg;gLk;. ,jpy;
gpd;tUk; ,uz;L tifahd Operators gad;gLj;jg;gLfpd;wd.
1. in
2. not in

The Membership Operator in Python is used to check whether a value exists inside a sequence or
collection. The collection can be a list, tuple, string, set, or dictionary. Instead of comparing objects or
identities, membership operators ask a simpler question: Is this element contained within that structure?
Python provides two membership operators:

Operator Meaning
in Returns True if the value exists in the sequence
not in Returns True if the value does not exist in the sequence

1) x=”Eppudi irukku python”


“o” in x →
i in x →
“Y” in x →
“thon” in x →
“irukkupython” in x →
“a” in “a” →
“apple” in “a” →
“a” in “apple” →
“eppudi” not in x →

13 of 87
5) team = ["IND", "AUS", "ENG", "SA"]
"IND" in team →
"PAK" in team →
"NZ" not in team →
"I" in team[0] →
"G" in team[2] →
"S" in team[3] →
"AUS" in team →
"U" in team[1] →

6) mob = ("Nokia", "Samsung", 10)


"Nokia" in mob →
"iphone" not in mob →

"Sparking minds, The best education"– [Link]


"S" in mob[1] →
"a" in mob[1] →
"u" in mob →
"10" in mob →
10 in mob →

7) a = {"city": "Colombo", "country": "Sri Lanka", "river": "Mahaweli"}


"city" in a →
"Colombo" in a →
"country" in "Sri Lanka" →
"Sri" in "country" →
"o" in a →
"Mahaweli" in a["river"] →
"Lake" in a["river"] →

8) b = {"lang": "Python", "editor": "VSCode", "os": "Linux"}


"lang" in b →
"Python" in b →
"VSCode" in b["editor"] →
"Code" in b["editor"] →
"x" in b →

14 of 87
Bitwise Operators
bit njhlu;ghd ju;f;ftpay; ,af;fpfshf gpd;tUtd fhzg;gLfpd;wd. ,it bit fspd; kPJ
khj;jpuNk gpuNahfpf;fg;gLfpd;wd. bit njhlu;ghd ju;f;ftpay; ,af;fpfshf gpd;tUtd
gad;gLj;jg;gLfpd;wd.

Operator Name Example

& AND 5&3

` ` OR

^ XOR 5^3

~ NOT ~5

<< Left Shift 5 << 1

"Sparking minds, The best education"– [Link]


>> Right Shift 8 >> 1

Priority Order → >>, <<, &, ^, |, ~


1) 6 & 9 11) 36 >> 3

2) 18 & 23 12) 48 >> 4

3) 10 | 7 13) 15 & 12

4) 5 | 12 14) 6 & 7 | 10 | 6 & 21 << 1

5) 14 ^ 9 15) 20 >> 3 | 18 ^ 11 << 2 & 16

6) 40 ^ 28 16) 28 | 14 << 3 | 28 ^ 9 & 20 << 1

7) ~12 17) 54 & 26 ^ 38 & 6 >> 3 & 20 & 15

8) ~-18 18) 9 & 6 | 10 | 9 & 21

9) 5 << 3 19) 16 | 7 & 12 | 8 & 18 & 10

10) 9 << 2 20) 22 & 18 ^ 14 | 9 & 16

15 of 87
Standard Data types in python

• igjdpy; cs;s xt;nthU ngWkjpfSf;Fk; (value) juTtif (Data type) cs;sJ. igjd;
nra;epuypy; midj;Jk; nghUs; (object) vd;gjhy; juT tiffs; tFg;Gf;fshfTk;
(classes) khwpfshdJ mt; tFg;Gf;fspd; nghUs; MfTk; fhzg;gLk;.

Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

1. Numbers
• Integral → Whole-number types.
o Integer → Stores positive or negative whole numbers without decimals.
o Boolean → Stores only two values: True or False.
• Real → Usually refers to floating-point numbers (float), which contain decimal values.
• Complex → Stores complex numbers with a real and imaginary part. Imaginary part is

"Sparking minds, The best education"– [Link]


written using j.

2. Sequences → Ordered collections of items.


• Immutable sequences → Cannot be changed after creation.
o Strings → Used to store text.
o Tuples → Ordered collection that cannot be modified.
o Bytes → Immutable sequence of bytes, used for binary data. Ex: b = b"hello"
• Mutable sequences → Can be changed after creation.
o Lists → Ordered, changeable collection of items.
o Byte arrays → Mutable version of bytes. Ex: data = bytearray(b"abc")

3. Set types → Unordered collections of unique elements.


• Sets → Mutable collection of unique values.
• Frozen sets → Immutable version of a set. Ex: fs = frozenset([1, 2, 3])

4. Mappings → Store data in key-value pairs.


• Dictionaries → Each value is accessed using a key.

16 of 87
Python Numbers

• ,J gpd;tUk; 3 tifahd juT tiffisf; nfhz;Ls;sJ.


1. integer (int) → 1,2,3
2. float →1.0, 2.5, 6.7
3. complex → 3.14j, 45.j, 9.322e-36j, .857j, -.5152+j5, 4e+14j

Note1 → You cannot convert complex numbers to another number type


(complex ,yf;fq;fis NtW ,yf;f juT tiff;F khw;w KbahJ)

Note2 → To verify the type of any object in python, use the type( ) function
(VjhtJ nghUspw;fhd juT tifia ghu;g;gjw;F type( ) vDk; function gad;gLj;jg;gLk;)

1. min(6,10) 7. max(10,4,20.0) 13. min(10,2)

2. pow(2,8) 8. pow(4,7) 14. round(10.75,1)

"Sparking minds, The best education"– [Link]


3. 3e2 9. 4e2 15. type(10.0)

4. min(7,8,2,6) 10. max(7,8,4.2) 16. max(8,4)

5. pow(-2,4) 11. round(10.75) 17. round(10.75,2)

6. 10e6 12. type(10) 18. type(10+3j)

Strings (ruk;/ tupAUj;njhlu;)


• igjdpy; tupAUj; njhlupahdJ single quotation mark ( ‘ ’ ) or double quotation mark ( “ ” ) ,Ds;
vOjg;gLk;.
• ,yf;fj;juTfis tupAUj;njhlu; juT tiff;Fs; tiuaiw nra;jhy; mtw;iw vz;fzpj
nraw;ghLfSf;fhf gad;gLj;j KbahJ. fhuzk;> string juT tiff;Fs; fhzg;gLk; midj;J
ngWkjpfSk; tupAUf;fshfNt nfhs;sg;gLk;.
• String MdJ Immutable Datatype (khw;w Kbahj juTtif) Mf fhzg;gLtjdhy; String I
tiuaiw nra;j gpd;du; mjpy; vt;tpj khw;wq;fisAk; Nkw;nfhs;s KbahJ.

17 of 87
name = "Hello world" x = "Python Programming"

x = "Welcome"

1. print(name) 1. print(x[0])

2. print(x) 2. print(x[1:5])

3. print("name") 3. print(x[0:6])

4. print(name[1]) 4. print(x[11:12])

5. print(name[4]) 5. print(x + " " + "is simple")

6. print(name + name) 6. print(x[-1])

7. print(name + x) 7. print(x[-1:-4])

"Sparking minds, The best education"– [Link]


8. print(Name + x) 8. print(x[-1:-9])

9. print(x, "to", name) 9. print(x - "i")

10. print("My name is" + name) 10. print("python * 5")

11. print(x * 2) 11. print("Python" * 5)

12. print(name * 5) 12. x = "python"

13. print("I'm a" + "Software Engineer") 13. print("Hello! " + x)

18 of 87
x = "Software Engineering" val = "Networking"

1. print(x[1:5]) 1. print(val[-1:-10])

2. print(x[5:12])
2. print(val[-1:-10:-1])
3. print(x[1:])
3. print(val[-1:-11:-1])
4. print(x[5:])
4. print(val[-1:-15:-1])
5. print(x[:8])

6. print(x[:10]) 5. print(val[-1:-11:-2])

7. print(x[:])
6. print(val[:-8:-1])
8. print(x[0:10:1])
7. print(val[-4::-1])
9. print(x[:10:2])

"Sparking minds, The best education"– [Link]


8. print(val[-4::])
10. print(x[0:10:3])

11. print(x[0:5:]) 9. print(val[-9::])

12. print(x[::2])
10. print(val[-5::-1])
13. print(x[:14])
11. print(val[:-4:-2])
14. print(x[::3])
12. print(len(val))
15. print(x[::2])

16. print(x[0:10:]) 13. print(len("Welcome"))

17. print(x[:10:1])
14. print([Link]())
18. print(x[1:1])
15. print([Link]())
19. print(x[1:1:1])

20. print(x[:10:])

21. print(x[:5:2])

22. print(x[12:16:3])

19 of 87
x = "Sathith Python Tutorial"

1. print(len(x)) 13. print([Link]("t",3))

2. a = [Link]() 14. print([Link](x[7]))

3. print(a) 15. s = len(x)

4. y = [Link]() 16. p = str(s)

5. print(y) 17. q = p + "Hello Python"

6. print([Link]("T","D")) 18. print(q[1:6:2])

7. print([Link](x[7],"&")) 19. print("type of q is:", type(q))

"Sparking minds, The best education"– [Link]


8. print([Link](x[1],"&")) 20. x = "Sathith Python Tutorial"

9. r = [Link]("t") 21. print([Link]("t"))

10. print(r) 22. print([Link]("a"))

11. print([Link]("t",1)) 23. print([Link]("h"))

12. print([Link]("t",2)) 24. print([Link]("O"))

20 of 87
LIST (gl;bay;)
• xU jdp khwpapDs; gy ngWkjpfis Nrkpg;gjw;fhf ,J gad;gLj;jg;gLk;.
• mjhtJ> gy;NtWgl;l juTtiffis cs;slf;fpa (int, float, str, tuple) xU njhFjpahd
juTtif ,JthFk;.
• ,J igjd; nra;epuypy; [ ] milg;gpDs; vOjg;gLtNjhL mtw;wpy; cs;slf;fg;gLk;
ngWkhdk; comma ( , ) %yk; NtWgLj;jg;gLk;.
• ,it tupir Kiwapy; mike;jpUf;Fk; ngWkhdj;ij cs;slf;Fk; (Ordered)
• igjdpy; LIST I cUthf;fpa gpd;du; mjpy; khw;wq;fis Vw;gLj;jyhk; (changeable)

Note1: List Items are ordered → it means that the item have a defined order, and that order will not change.
If you add new items to a list, the new item will be placed at the end of the list.
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
Note2: List Items are changeable → it means that we can update, add and remove items in a list after it

"Sparking minds, The best education"– [Link]


has been created.
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………

Note3: List Allow Duplicated Values


………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………

Note4: List items are indexed → the first item has index [0], the second item has index [1] etc.
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………

21 of 87
Question 01: Question 02:

data = ["Book", "Pen", 25, "Car", 42, "Laptop"] nums = [7, 12, 3, 9, 15]

print(data) print(nums)

print(data[1]) print(nums + nums)

print(data[4]) print(nums * 3)

print(data[6]) nums += [5, 8, 11]

print(data[2],[3]) print(nums)

print(data[2], data[3]) print(nums[-1])

"Sparking minds, The best education"– [Link]


print(data[-1]) print(nums[2])

print(data[-5]) print(nums[2:6])

print(data[1:4]) print(nums + "nums")

print(data[1:2]) print(len(nums))

print(data[:5]) y = 12

print(data[::2]) print(y in nums)

print(data[-1:-4:-1]) print("12" in nums)

print(data[1:5:-2]) print(9 in nums)

print(data[4::-1])

print(data[1::-1])

22 of 87
Question 03: Question 04:
print([3,7,1] + [9,2,5]) items = ["Python", 12, [5, 9, 3], 7, "Code"]

print(["Hello","8"] + [3,9,"Hello"]) print(items)

print([6] * 3) print(len(items))

print([12,5,7] * 2) print(len(items[2]))

print(type([3,9,4,"Text",15])) print(len(items[0]))

print([7,3,9][2] * [5]) print(len(items[4]))

"Sparking minds, The best education"– [Link]


print([6] * [8]) items2 = items[0] + items[4]

print([9,2,4][1] * 5) print(items2)

print(["code",5,8,"Python"][3][1] * 3) print(type(items2))

print([2,7,8,11] * [6]) print(len(items2))

print([2,7,8,11] * 6) print(items[0] * 2**1)

print([2,7,8,11][2] * [6]) print(items * items[2][1])

print(items + ["Data"])

23 of 87
Question 05: Index Method. Questions 07: Python List Extend()
letters = ["P", "Q", "R", "S", "T"] The extend() method adds all the elements of an
iterable (list, tuple, string etc.) to the end of the
list.
index = [Link]("P")

subA = ['math', 'science']


print("Index of P is", index)

subB = ['history', 'art']


print("Index of Q is", [Link]("Q"))

[Link](subB)
print([Link]("T"))

print(subA)
values = [3,6,9,12,'9',15,9,'15']

print(subB)
print([Link](9))

[Link]('geo')
print([Link]('9'))

"Sparking minds, The best education"– [Link]


flavorA = ('Mango', 'Orange')
print([Link](15))

flavorB = ['Apple']
print([Link]('15'))

[Link](flavorB)
Question 06: The append() method adds an
item to the end of the list
print(flavorA)
snacks = ["Burger", "Pizza", "Sandwich"]
languages = ['Spanish']
[Link]("Pasta")
lang_tuple = ('German', 'Italian')
print(snacks)
lang_set = {'Arabic'}
# Adding list to a list
[Link](lang_tuple)
new_snacks = ["Noodles", "Fries"]
print("New Language List is:", languages)
[Link](new_snacks)
[Link](lang_set)
print(snacks)
print("New Language List is:", languages)

24 of 87
x = [12,18]
y = [25,35]
z = (3,4)
[Link](z)
print(z)
[Link](z)
print(y)

#Python List Insert()


#The list insert() method inserts an element to the list at the
specified index.

name = [‘Raj’, ‘nimal’, ‘aravind’]


[Link](2, ’vijay’) →
print(“New name list:”, name)

list1 = [ (10,12), {4,6}, (10,15) ]

"Sparking minds, The best education"– [Link]


list_in = [20,15]
[Link](1, list_in)
print(“Updated list:”, update) →

# Python List remove()


# The remove() method removes the first matching element
(which is passed as an argument) from the list.

fruit = [‘Mango’, ‘Apple’, ‘Orange’, ‘Cherry’]


[Link](‘Orange’) →
print(“New fruit list:”, fruit)

sub = [‘ET’, ‘AT’, ‘BST’, ‘ICT’, ‘AT’, ‘ET’, ‘AT’, ‘IAT’]


[Link](‘AT’)
print(sub) →
[Link](‘IAT’) →

# Python List count()


# The count() method returns the number of times the specified
element appears in the list.

sub = [‘ET’, ‘AT’, ‘BST’, ‘ICT’, ‘AT’, ‘ET’, ‘AT’, ‘IAT’]


count = [Link](‘ICT’)
count2 = [Link](‘AT’)
count3 = [Link](‘ET’)
count4 = [Link](‘Agri’)
print(count) →
print(‘Count of AT:’, count2) →
print(‘Count of ET:’, count3) →
print(count4) →

25 of 87
# Python List pop()
# The pop() method removes the item at the given index from the list and returns the removed
item.

Note →
1. The pop() method takes a single argument (index).

2. The argument passed to the method is optional. If not passed, the default index -1 is passed
as an argument (index of the last item).

3. If the index passed to the method is not in range, it throws IndexError: pop index out of
range exception.

vowels = [‘a’, ’e’, ’i',’o’, ‘e’, ’u’]


rem_vow = [Link](4)
print(‘Removed item:’, rem_vow) →
print(‘Vowels:’, vowels) →

# pop() without an index, and for negative indices

"Sparking minds, The best education"– [Link]


course = [‘Java’, ‘C’, ‘C++’, ‘C#’, ‘Python’, ‘HTML’]
print(‘When index is not passed:’) →
print(‘Removed value:’, [Link]()) →
print(‘New course:’, course) →

print(‘When -1 is passed’) →
rem = [Link](-1)
print(course) →

print(‘When -6 is passed’) →
print(‘Return value:’, [Link](-6)) →
print(‘New course:’, course) →

# Python List reverse()


# The reverse() method reverses the elements of the list.
subject = [‘Eng’, ‘Maths’, ‘Science’, ‘ICT’]
[Link]()
print(‘Updated subject order:’, subject) →

flavor = [‘Vanilla’, ‘Choco’, ‘Strawberry’]


reversed_flavor = flavor[::-1]
print(‘Reversed flavor:’, reversed_flavor) →

26 of 87
# Python List sort()
# The sort() method sorts the elements of a given list in a specific ascending or descending order.

vowels = [‘e’, ‘a’, ‘o’, ‘u’, ‘i']


[Link]()
print(‘Sorted list:’, vowel) →

vowels = [‘e’, ‘a’, ‘o’, ‘u’, ‘i']


[Link](reverse=True)
print(‘Sorted list (in descending):’, vowel) →

# Python List copy()


# The copy() method returns a shallow copy of the list.

list1 = [18,10,15,’Hello’]
list2 = list1
print(list2) →
[Link](‘Python’)

"Sparking minds, The best education"– [Link]


print(‘New list:’, list2) →
print(‘Old list:’. list1) →

Note: The problem with copying lists in this way is that if you modify list2, list1 is also modified. It
is because the new list is referencing or pointing to the same list1 object.

Note2: However, if you need the original list unchanged when the new list is modified, you can use
the copy() method.

old = [4,5,6,8]
new = [Link]()
print(‘Copied list:’, new) →

[Link](10)
print(new) →

# Copy List Using Slicing Syntax

old_list = [4,6,8,10,12]
new_list = old_list[:]
print(new_list) →
new_list.append(14)
print(‘Old list is:’, old_list) →
print(‘New list is:’, new_list) →

# Python List clear()

x = [5,10,48,42]
[Link]()
print(x) →

27 of 87
# Emptying the List Using del

x = [10,12,16]
del x[:]
print(x) →

# Delete the list

x = [5,4,6,8]
del x
print(x)

Tuple (kb/ gjpT)


• xU jdp khwpapy; gy ngWkjpfis Nrkpg;gjw;fhf ,J gad;gLj;jg;gLfpd;wJ.
• ,J igjdpy; ( ) ,Ds; vOjg;gLtNjhL> ,jpYs;s xt;nthU ngWkjpfSk; comma (,) ,dhy;
NtWgLj;jg;gl;bUf;Fk;.
• A Tuple is a collection which is ordered and unchangeable.

"Sparking minds, The best education"– [Link]


……………………………………………………………………………………………………..
• Tuple are Indexed, Tuple item allow duplicated values.
……………………………………………………………………………………………………..

Creating a Tuple
variable_name = (val1, val2, val3, Valn)

subjects = ('Math', 'ICT', 'Science', 'History', 'English')

print(subjects) →

print(len(subjects)) →

print(type(subjects)) →

tuple1 = ('Java',)

print(type(tuple1)) →

tuple2 = ('Java')

print(type(tuple2)) →

tuple3 = (25)

print(type(tuple3)) →

tuple4 = (12.8)

28 of 87
print(type(tuple4)) →

tuple5 = (7,14)

print(type(tuple5)) →

tuple6 = ([8,3])

print(type(tuple6)) →

tuple7 = ("Hi", "Welcome")

print(type(7)) →

# Note: To create a tuple with only one item, you must add a comma.

x = ("Book", 25, True, False, "False")

print(x) →

"Sparking minds, The best education"– [Link]


print(type(x)) →

new = tuple(('Orange', 12, 20))

print(new) →

print(type(new)) →

y = tuple([5, 9, 'Python'])

print(y, 'is a', type(y)) →

items = ('Burger', 'Pizza', 'Pasta', 'Noodles')


print(items[1]) →
print(items[3]) →
print(items[10]) →
print(items[-1]) →
print(items[-2]) →
print(items [1:3]) →
print(items[1:4]) →
print(items[:1]) →

29 of 87
a = (10,12,5,6,7,8,10,22,10)
print(a[0:]) →
print(a[0::2]) →
print(a[::-1]) →
print(a[-1::-3]) →
print(a[1:10:3]) →

fruit = ("Apple", "Mango", "Apple", "Grapes")


print(fruit) →
fruit[2] = “Orange” →

Note → Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable
as it also is called. But there is a workaround. You can convert the tuple into a list, change the list,

"Sparking minds, The best education"– [Link]


and convert the list back into a tuple.

Question: ISP vDk; ngaupy; cUthf;fg;gl;l Tuple xd;W fPNo jug;gl;Ls;sJ.


ISP = (‘Dialog’, ‘Airtel’, ‘SLT’, ‘Hutch’, ‘Mobitel’)
NkNy jug;gl;Ls;s Tuple ,y; SLT vDk; ngWkjpia Sri Lanka Telecom vDk; ngauhf khw;wp
ntspaPL nra;tjw;Fj; Njitahd igjd; FwpKiwapid vOJf.

fruit = ("Apple", "Mango", "Apple", "Grapes")


[Link](‘Cherry’)
print(fruit)

30 of 87
fruit = ("Apple", "Mango", "Apple", "Grapes")
[Link](‘Grapes’)
print(fruit) →

Note → You cannot remove items in a tuple. Because Tuple is an immutable Datatype.
Note → You can delete the tuple completely

fruit = ("Apple", "Mango", "Apple", "Grapes")


del fruit
print(fruit) →

Unpack Tuple

"Sparking minds, The best education"– [Link]


When we create a tuple, we normally assign values to it. This is called "packing" a tuple. But, in Python,
we are also allowed to extract the values back into variables. This is called "unpacking"
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
>>> T = ('red', 'green', 'blue', 'cyan')

>>> print(T) →

The values ‘red’, ‘green’, ‘blue’ and ‘cyan’ are packed together in a tuple.

>>> T = ('red', 'green', 'blue', 'cyan')

>>> (a,b,c,d) = T →

>>> print(a) →

>>> print(b) →

>>> print(c) →

>>> print(d) →

The tuple T is unpacked into a, b, c and d variables.

31 of 87
Question

x = (10, [15, 3,17], 18)


x[1][1] = “Hello”
print(x)

Answer → ?

Unpacking Tuple using Asterix (*)

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")


(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

"Sparking minds, The best education"– [Link]


a = (5,6,8)
b = (“Apple”,”Orange”)
c = a+b
print(c) →
print(a*5) →
print(b*3) →
x = (‘a’,’b’,’c’,’a’,’d’,’a’,’c’)
print([Link](‘a’)) →
print([Link](‘b’) →
print(‘a’ in x) →
print(‘d’ in x) →
print(‘e’ in x) →

32 of 87
Set (njhil)
• xU jdp khwpapy; gy ngWkjpfis Nrkpg;gjw;fhf ,J gad;gLj;jg;gLfpd;wJ.
• ,J igjdpy; { } ,Ds; vOjg;gLtNjhL> ,jpYs;s xt;nthU ngWkjpfSk; comma (,) ,dhy;
NtWgLj;jg;gl;bUf;Fk;.
• A Tuple is a collection which is unordered and unindexed.
• Sets are unchangeable → Sets are unchangeable, meaning that we cannot change the items after the set
has been created. Once a set is created, you cannot change its items, but you can add new items.
• Duplicated not allowed – Sets cannot have two items with the same value.

Python set is an unordered collection of unique items. They are commonly used for computing mathematical
operations such as union, intersection, difference, and symmetric difference.

"Sparking minds, The best education"– [Link]


>>> tuple1 = {‘Kandy’, ‘Colombo’, ‘Jaffna’, ‘Ampara’}
>>> print(tuple1) →
>>> print(type(tuple1)) →
>>> print(len(tuple1)) →
>>> tuple2 = {“Batticaloa”, “Trincomalee”, “Gampaha”}
>>> print(tuple2) →
>>> print( “Trincomalee” in tuple2) →
>>> print(‘Kandy’ in tuple1) →

33 of 87
>>> x = {‘ICT’, ‘BST’, ‘ET’, ‘SFT’}
>>> [Link](‘Agri’) # Add items
>>> print(‘New Tuple x is:’,x) →
>>> print(len(x)) →
>>> brand = {‘Asus’, ‘Acer’, ‘Apple’, ‘Dell’}
>>> brand2 = {‘Hp’, ‘IBM’, ‘Singer’, ‘Huawei’}
>>> [Link](brand2)
>>> print(brand) →
>>> print(brand2) →
# The object in the update() method does not have be a set, it can be any iterable object (tuples,
lists, dictionaries etc).
>>> num1 = {4,6,8,7}
>>> num2 = [10,12,16,18]
>>> [Link](num2)

"Sparking minds, The best education"– [Link]


>>> print(num1)

>>> brand = {‘Asus’, ‘Acer’, ‘Apple’, ‘Dell’}


>>> [Link](‘Apple’)
# If the item to remove does not exist, remove() will raise an error.
>>> print(brand) →
>>> [Link](‘Hp’) →
>>> print(brand) →
>>> brand2 = {‘Hp’, ‘IBM’, ‘Singer’, ‘Huawei’}
>>> [Link](‘Singer’)
>>> print(brand2) →
>>> [Link](‘Asus’) →
# If the item to remove does not exist, discard() will NOT raise an error.

34 of 87
# You can also use the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
# Sets are unordered, so when using the pop() method, you do not know which item that gets removed.
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

>>> brand = {‘Asus’, ‘Acer’, ‘Apple’, ‘Dell’} →


>>> x = [Link]()
>>> print(x) →
>>> brand2 = {‘Hp’, ‘IBM’, ‘Singer’, ‘Huawei’}
>>> [Link]()
>>> print(brand2) →

"Sparking minds, The best education"– [Link]


>>> del brand
>>> print(brand) →

Note: Python - Join Set


• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all items from both sets, or the
update() method that inserts all the items from one set into another.
• Both union() and update() will exclude any duplicate items.

>>> x = {‘apple’, 5, 10, ‘orange’}


>>> y = {’15’, 20, ‘apple’, ‘strawberry’, ‘orange’}
>>> z = [Link](y)
>>> print(z) →
>>> [Link](y)
>>> print(y) →
>>> set_1 = {‘apple’, ‘orange’, ‘10’, 15, 20} →
>>> set_2 = {‘10’, ‘20’, ‘apple’, ‘orange’}
>>> set_1.intersection_update(set_2) →
>>> print(set_1) →
>>> print(set_2) →

35 of 87
# The intersection_update() method will keep only the items that are present in both sets.
# The intersection() method will return a new set, that only contains the items that are present in both sets.

>>> set1 = {10,14,1,3,4,6,5,7,8}


>>> set2 = {21,20,14,3,4,7,8,24,64}
>>> set3 = [Link](set2)
>>> print(set3) →
>>> print(set1) →

# The symmetric_difference_update() method will keep only the elements that are NOT present in both
sets.

>>> set1 = {10,14,1,3,4,6,5,7,8}

"Sparking minds, The best education"– [Link]


>>> set2 = {21,20,14,3,4,7,8,24,64}
>>> set1.symmetric_difference_update(set2)
>>> print(set1) →

# The symmetric_difference() method will return a new set, that contains only the elements that are NOT
present in both sets.

>>> set1 = {10,14,1,3,4,6,5,7,8}


>>> set2 = {21,20,14,3,4,7,8,24,64}
>>> set3 = set1.symmetric_difference(set2)
>>> print(set3) →
>>> print(set1) →

36 of 87
Set Operations
• Sets are commonly used for computing mathematical operations such as intersection, union,
difference, and symmetric difference.
Set Union
• You can perform union on two or more sets using union() method or | operator.

>>> Set1 = {10,15,16,19,11,3,1,2}

"Sparking minds, The best education"– [Link]


>>> Set2 = {1,64,47,3,11,23}
>>> print(Set1 | Set2) →
>>> print([Link](Set2)) →

Set Intersection
• You can perform intersection on two or more sets using intersection() method or & operator.

>>> Set1 = {10,15,16,19,11,3,1,2}


>>> Set2 = {1,64,47,3,11,23}
>>> print(Set1 & Set2) →
>>> print([Link](Set2)) →

37 of 87
Set Difference
• You can compute the difference between two or more sets using difference() method or -
operator.

>>> Set1 = {10,15,16,19,11,3,1,2}


>>> Set2 = {1,64,47,3,11,23}
>>> print(Set1 – Set2) →
>>> print([Link](Set2)) →

"Sparking minds, The best education"– [Link]


Set Symmetric Difference
• You can compute symmetric difference between two or more sets using symmetric_difference()
method or ^ operator.

>>> Set1 = {10,15,16,19,11,3,1,2}


>>> Set2 = {1,64,47,3,11,23}
>>> print(Set1 ^ Set2) →
>>> print(Set1.symmetric_difference(Set2)) →

38 of 87
Dictionary (mfuhjp)
• Dictionaries are used to store data values in key : value pairs.
……………………………………………………………………………………………………
• An item has a key and a corresponding value that is expressed as a pair (key: value).
……………………………………………………………………………………………………
• A dictionary is a collection which is unordered, changeable and does not allow duplicates.
………………………………………………………………………………………………………
…………………………………………………………………………………………………
• Dictionaries are written with curly brackets - { }, and have keys and values.
……………………………………………………………………………………………………
• While the values can be of any data type and can repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and must be unique.
………………………………………………………………………………………………………
…………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………

>>> meals = {'veg':'dhal', 'non-veg':'chicken', 'fruit':'mango', 'drink':'milk'} "Sparking minds, The best education"– [Link]

>>> print(meals)
>>> print(len(meals))
>>> print(type(meals))
>>> print(meals['veg'])
>>> print(meals['non-veg'])
>>> print(meals['dhal'])

39 of 87
>>> new_dict = {'Name': 'Sathith', 'Year': 1999, 'M,D': ['Jun', 21]}
>>> print(new_dict)
>>> print(len(new_dict))
>>> print(type(new_dict))
>>> print(new_dict['Name'])
>>> print(new_dict['M,D'])
we can also create a dictionary using the built-in dict() function.
>>> dict_2 = dict({1:'one', 2:'two', 3:'three', 4:'four', 5:'five'})
>>> print(dict_2)
>>> print(dict_2[1])

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

"Sparking minds, The best education"– [Link]


>>> new_dict = {'Name': 'Sathith', 'Year': 1999, 'M,D': ['Jun', 21]}
>>> print(new_dict[‘Year'])

There is also a method called get() that will give you the same result
>>> new_dict = {'Name': 'Sathith', 'Year': 1999, 'M,D': ['Jun', 21]}
>>> print(new_dict.get(‘Name’))
>>> year = new_dict.get(‘Year’)
>>> print(year)

Note →
If we use the square brackets [ ], KeyError is raised in case a key is not found in the dictionary. On the
other hand, the get() method returns None if the key is not found.
>>> city = {'Eastern':'Trincomalee', 'Northern':'Jaffna', 'Western':'Colombo'}
>>> print(city['Northern'])
>>> print([Link]('Western'))
>>> print(city['Southern'])
>>> print([Link]('Southern'))

40 of 87
>>> x = {'Name': 'Sathith', 'Year': 1999, 'M,D': ['Jun', 21]}
>>> [Link]( ) →
>>> x['Name']='Sathithraj'
>>> print(x) →
>>> y = [Link]() →
>>> print(y) →

Note→ The returned list is a view of the items of the dictionary, meaning that any changes done to
the dictionary will be reflected in the items list.

>>> x['Name'] = 'Sathith'


>>> print(x) →
>>> print(y) →

"Sparking minds, The best education"– [Link]


Change the Dictionary Values()
>>> meals = {'veg':'dhal', 'non-veg':'chicken', 'fruit':'mango', 'drink':'milk'}
>>> meals[‘fruit’] = ‘Banana’
>>> meals[‘drink’] = ‘Juice’
>>> print(meals)

Update Dictionary
The update() method will update the dictionary with the items from the given argument. The argument
must be a dictionary, or an iterable object with key:value pairs.
>>> meals = {'veg':'dhal', 'non-veg':'chicken', 'fruit':'mango', 'drink':'milk'}
>>> [Link]({‘fruit’ : ’grapes’})
>>> print(meals)

Add Dictionary Items


>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> month['Apr'] = 4
>>> print(month) →

41 of 87
Note → The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.

>>> [Link]({‘May’:5})
>>> print(month) →

Remove Dictionary Items


Method 1 → Using pop( )
>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> print(month) →

Note → The pop() method removes the item with the specified key name

"Sparking minds, The best education"– [Link]


>>> [Link](‘Jan’)
>>> print(month) →

Method 2 → Using popitem( )


>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> print(month) →

Note → The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead)

>>> [Link]()
>>> print(month) →

Method 3 → Using del keyword


>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> print(month) →

Note → The del keyword removes the item with the specified key name
>>> del month[‘Mar’]
>>> print(month) →

42 of 87
Empties the Dictionary
>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> print(month) →

>>> [Link]()

>>> print(month) →

Delete the Dictionary completely


>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> print(month) →

>>> del month

>>> print(month) →

"Sparking minds, The best education"– [Link]


Copy a Dictionary
Method 1 → Using copy( )
>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> monthcopy = [Link]()

>>> print(month) →

>>> print(monthcopy) →

Method 2 → Using dict( ) function


>>> month = {'Jan':1, 'Feb':2, 'Mar':3}
>>> monthcopy2 = dict(month)

>>> print(monthcopy2) →

43 of 87
nra;epuy; tpUj;jpapy; fl;Lg;ghl;Lf; fl;likg;Gf;fisg; gad;gLj;Jthu;
nra;epuy; fl;Lg;ghnlhd;wp gha;r;ryhdJ %d;W mbg;gilf; fl;Lg;ghl;Lf; fl;likg;Gf;fisf;
nfhz;L nraw;gLj;jg;gLk;.
1. njhlu; (Sequence)
2. njupT (Selection)
• if
• if-else
• if-elif-else

3. kPs;nray; (Repeating) – igjdpy; ,uz;L tifahd jlkply; $w;Wf;fisf; nfhz;Ls;sJ.


• for
• while

"Sparking minds, The best education"– [Link]


Selection
1. vspa njupT (Simple Selection) – if condition
2. gy njupT (Multiple Selection)
3. Nested if Condition

rhjhuzkhf FwpaPl;il vOJtjpid tpl> xU epge;jid jpUg;jpaspf;fg;gLk; NghJ rpy


$w;Wf;fis ,af;f itg;gjw;fhf FwpaPl;bid vOJtJ rpwe;jjhFk;. ,jw;fhf igjdpy;
gpd;tUk; $w;Wf;fs; gad;gLj;jg;gLfpd;wd.
1. if
2. elif
3. else
nghJthf if, else fl;lisahdJ xU epge;jidf; $w;wpif guPl;rpj;J mf;$w;W cz;ik vdpd;
xU tpisitAk;> ,y;iynadpy; ,d;Dk; xU tpisitAk; ntspaPL nra;tjw;fhfg;
gad;gLj;jg;gLfpd;wJ.

44 of 87
if fl;lisf;fhd gha;r;rw; Nfhl;Lg;glk; :

Python if condition example →


num1 = 10
if num1>5:
print("num1 is greater than 5")

Python if… else statement

"Sparking minds, The best education"– [Link]


Python if…else condition example →
num1 = 1
if num1>5:
print("num1 is greater than 5")
else:
print("Num1 is less than 5")

xU vz; cs;sPL nra;ag;gLk; NghJ mJ xw;iw vz;zh? my;yJ ,ul;il vz;zh? vdf;
fhz;gjw;Fj; Njitahd igjd; FwpKiwapid vOJf.

45 of 87
Python if…elif…else statement

Python if…elif…else condition example →


num1 = 5
if num1>5:
print("num1 is greater than 5")
elif num1<5:
print("Num1 is less than 5")
else:
print("Num1 is 5")

OR

Python if…elif…else condition example →

"Sparking minds, The best education"– [Link]


num1 = 5
if num1>5:
print("num1 is greater than 5")
else:
if num1<5:
print("Num1 is less than 5")
else:
print("Num1 is 5")

46 of 87
Question 01

a=7
b=3
if a > b:
print(a + b)
print(a - b)

Question 02

marks = 75
if marks >= 50:
print("Pass")
else:
print("Fail")
print("Result Released")

"Sparking minds, The best education"– [Link]


Question 03

x = 15
if x % 3 == 0:
print("Divisible by 3")
else:
print("Not divisible by 3")
if x % 5 == 0:
print("Divisible by 5")

Question 04

x = 20
y = 10

if x > 15:
if y > 5:
print("P")
print("Q")
print("R")

47 of 87
Question 05

a=8
b = 12
if a > 5:
if b < 10:
print("X")
else:
print("Y")
else:
print("Z")

Question 06

x=6
y=9

"Sparking minds, The best education"– [Link]


if x < 10:
print("A")
if y > 10:
print("B")
else:
print("C")
if x + y > 12:
print("D")
print("E")

Question 07

x=5
y = 15
z = 10
if x < y:
print("A")
if y < z:
print("B")
else:
print("C")
if z > x:
print("D")
else:
print("E")
print("F")

48 of 87
Question 08

x=5
y = 15
z=5
if x == z:
print("P")
if y > x:
print("Q")
if y % x == 0:
print("R")
else:
print("S")
else:
print("T")
else:
print("U")

"Sparking minds, The best education"– [Link]


print("V")

Question 09

a=9
b=4
c = 12
if a > 5:
print("X")
if b % 2 == 0:
print("Y")
if c < 10:
print("Z")
else:
print("W")
if a + b == c:
print("T")
else:
print("U")
else:
print("V")
else:
print("N")
print("END")

49 of 87
Repetition
• Python ,y; 02 tifahd looping fl;lisfs; gad;gLj;jg;gLfpd;wd.
1. while loops
2. for loops
The while Loop
• ,U epge;jid cz;ikahf ,Uf;Fk; tiu rpy nraw;ghLfis Nkw;nfhs;tjw;F ,J
gad;gLj;jg;gLfpd;wJ.
Flow Chart
Syntax

i = 0 (Starting value)

while (i<10): (Condition)


print(i)
loop statement
i=i+1

"Sparking minds, The best education"– [Link]


i=0 i=0 i=0
while (i < 10): while (i<10): while (i<10):
print(i) print(i) print(i)
i += 1 i=i+2

i=0 i=1 i=1


while (i<20): while (i<15): while (i<15):
print(i) print(i) print('No',i)
i=i+3 i=i+5 i=i+5
print(i) print(i)

50 of 87
i=1 i=1 i=1
while (i<15): while (i<10): while (i<10):
print('No',i) print(i*i) print(i*i, end="")
i=i+5 i+=1 i+=1
print('No+No =',i+i)

i=1 i=1 n=1


while (i<10): while (i<10): while (n<10):
print(i*i, end=" ") print(i*i, end=",") print(n*n)
i+=1 i+=1 n=n+2
print(n*'Ha')

"Sparking minds, The best education"– [Link]


n = 1; m=4; a = 10 x=1
while (n<100): b=5 Sum = 0
print(n+m) while(x<12):
n=n*m while(a>0): Sum=Sum+x
m=m+n print(a-b) print(x)
print(m) a-=2 x=x+1
b=b*2.0 print(Sum)
print(b)

x=1 x=1 x=1


Sum = 0 Sum = 0 Sum = 0
while(x<12): while(x<12): while(x<10):
Sum=Sum+x Sum=Sum+x Sum=Sum+x
x=x+1 x=x+1 x=x+1
print(Sum) print(Sum) print(Sum)
print(Sum+5)
Sum=Sum+2
print(Sum-10)

51 of 87
x=1 x=1 x=1
y = 10 while(x<6): while(x<6):
while(x<5): print("Sathith") print(("raj"*x)," @")
y = y*x x=x+1 x=x+1
x=x+1
y=y-2
print("x = ",x)
print("y = ",y)
print(x+y)

x=1 x = 10 x=1
y=1
while x <= 3: while x > 0:
y=1 print(x // 3) while x <= 3:
while y <= 2: x -= 3 while y <= 3:
print(x, y) print(x + y)
y += 1 y += 1

"Sparking minds, The best education"– [Link]


x += 1 x += 1

i=1 x=1 x=2


j=5 y=1
while x <= 4:
while i <= 3: print(x * x) while x <= 6:
print(i + j) x += 1 print(x - y)
i += 1 x += 2
j -= 1 y += 1

i=1 x=1 x=1


y=1
while i <= 3: while x <= 3:
j=1 print(x) while x <= 2:
while j <= 3: x += 1 while y <= 3:
print(i * j) print(x) print(x * y)
j += 1 y += 1
i += 1 x += 1

52 of 87
The For Loop
for VAL in range (Start value, end value, Step by)
Questions
for i in range(10): for i in range(0,10): for i in range(0,10):
print(i) print(i) print(i,end='')

for i in range(1,11): for i in range(1,20,2): for i in range(1,20,3):


print(i*i) print(i) print(i)

for i in range(20,0): for x in range(10,0,-1): for x in range(10,0,-2):


print(i) print(x) print(x)

"Sparking minds, The best education"– [Link]


for x in range(10,50,5): for x in range(10,50,5): for x in range(10,50,5):
print(x+10) print(x+10) print(x+10)
x=x+5 x=x+5 x=x+5
print(x) print(x,end='')

for x in range(1,10,-1): for x in range(1,1,1): for x in range(0,1):


print(x) print(x) print(x)

for x in range(0,1,2): Sum=0 Sum=0


print(x) for x in range(10,15,2): for x in range(10,15,2):
Sum=Sum+x Sum=Sum+x
x=x+2 x=x+2
print(Sum) print(Sum)
print(x)

53 of 87
for x in range(10,15,2): for x in range(10,15,2): Total=0
Sum=0 Sum=Sum+x for x in range(1,15,2):
Sum=Sum+x x=x+2 Total=Total+1
x=x+2 print(Sum) x=x+5
print(Sum) print(x) print(x)
print(x) print(Total)

for y in range(10,-1): for y in range(10,-1,-1): for i in range(1,10):


print(y) print(y, end=“ ”) print(i*"@")

name = "Sathithraj" y = "Python" n=0

"Sparking minds, The best education"– [Link]


for x in name: for i in y: x = 'Programming'
print(x) print(y) for letter in x:
print(letter*n)
n+=1
print(x)

comb = '' for i in 'Tutor Sathith': name = 'Faculty of Technology'


x = 'Python' print(i) for i in name:
for letter in x: if(i=='t'):
comb += letter print([Link](i))
print(comb)

x = ['Python',1,2,3,4,5] x = ['Python',1,2,3,4,5] x = ['Python',1,‘Hi’,3,‘Hello’,5]


for i in x: for i in x: for i in x:
print(i) print(x) print(i)

54 of 87
num = [1,2,3,4,5] vowels = ['a','e','i','o','u'] vowels = ['a','e','i','o','u']
ltr = ['A','B','C','D','E'] for vow in range (len(vowels)): for vow in range (len(vowels)):
for x in ltr: print(vow) print(vowels[vow])
[Link](x)
print(num)

power = [ ] x = ['Cloud'] cloud = ('G-


for x in range(5): y = ['Drive, 'Mega', 'Dropbox'] Drive','Mega','Dropbox','Onedrive')
[Link](2 ** x) for a in x: for x in cloud:
print(power) for b in y: print('Cloud Computing:',x)
print(a,':',b)

num = (1,2,3,4,5,6,7,8,9,10) c=1


for i in range (len(num)): course =
print(num[i]) {'Electrical','Electronical','Civil'}

"Sparking minds, The best education"– [Link]


for cs in course:
print("Course",c,cs)
c=c+1

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for x in dict1:
print(x)

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for x in dict1:
print(dict1[x])

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for x in [Link]():
print(x)

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for x in [Link]():
print(x)

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for a,b in [Link]():
print(a,b)

dict1 = {'name':'Sathith', 'program':'Python', 'country':'Sri Lanka'} →


for a,b in [Link]():
print(b,a)

55 of 87
Questions →
fPNo jug;gl;Ls;s ntspaPl;bidg; ngWtjw;Fj; Njitahd igjd; FwpKiwf; $w;wpid vOJf.
output code

"Sparking minds, The best education"– [Link]

56 of 87
The pass Statement

• In Python programming, the pass statement is a null statement. t is used as a placeholder for future
implementation of functions, loops, etc.

Example →

x=1

"Sparking minds, The best education"– [Link]


while x<10:
pass

The break Statement


• epge;jid cz;ikahf ,Ug;gpDk; break statement ,idg; gad;gLj;jp kPs;tUifapid
(loops) epWj;j KbAk;.
i=1 i=1 i=1
while i < 7: while i < 7: while i < 7:
print(i) if i == 5: if i == 5:
if i == 5: print(i) break
break break print(i, end=' ')
i += 1 i += 1 i += 1

Answer → Answer → Answer →

i=1 i = 10 i = 10
while i < 7: while i > 1: while i > 1:
if i == 3: i-=1 i-=1
break if i == 5: if i == 5:
i += 1 break break
print(i, end=‘,’) print(i) i -= 1
print(i, end=“ ”)
Answer → Answer →
Answer →

57 of 87
count = 0 count = 0 count = 1
while 1: while True: while True:
print(count) count += 1 count += 1
count += 1 print(count) if count >= 5:
if count >= 5: if count >= 5: break
break break print(count)

Answer → Answer → Answer →

The continue Statement

i=1 i=1 i=1


while i < 10: while i < 5: while i < 5:

"Sparking minds, The best education"– [Link]


i += 2 i += 1 i += 1
if i == 5: if i == 3: print(i**2)
continue continue if i == 4:
print(i) print(i*i) continue

Answer → Answer → Answer →

rhu;Gfs;/ nraypfs; (Function)


• rhu;G vdg;gLtJ> xOq;fikf;fg;l;l> kPz;Lk; gad;gLj;jf;$ba FwpaPLfis cs;slf;fpa xU
njhFjp MFk;.
• nra;epuypy; miof;Fk;NghJ khj;jpuNk ,J gad;gLj;jg;gLk;.
• In Python a function is defined using the def keyword

Example →
defining a function
def fun1( ):
print("Python by Sathith")

Calling a function →
• To call a function, use the function name followed by parenthesis:

def fun1( ):
print("Python by Sathith")
calling a function
fun1( )

58 of 87
def calc():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))

add = num1+num2
sub = num1-num2
mul = num1*num2
div = num1/num2

print('Sum',add)
print('Subtract',sub)
print('Multiplication',mul)
print('Division',div)

calc()

"Sparking minds, The best education"– [Link]


rhu;gpDs; Arguments/ Parameter ,idg; ghtpj;jy;
Example 1 → Example 2 →

def mulBy10(no): def func1(prov):


print(no*10) print('Province '+prov)

mulBy10(7.5) func1('Eastern')

Example 3 → Example 4 →

def calc(a,b): def calc(a,b):


print(a+b) a+=15
b*=a
calc(10,15) print(a+b)

calc(5,10)

59 of 87
Use a default parameter value
Example 1 → Example 2 →

def newFun(x,y,z=10): def newFun(x,y,z=10):


print(x*z) print(x*z)
print(y*x) print(y*x)
print(x+y) print(x+y)

newFun(2,10) newFun(2,10,12)

Example 3 → Example 4 →

def newFun(x,y,z=10): def newFun(x,y,z=10):


print(x*z) print(x*z)
print(y*x) print(y*x)

"Sparking minds, The best education"– [Link]


print(x+y) print(x+y)

newFun(2) newFun(2,4,10,12)

Example 5 → Example 6 →

def printName(name='Sathith'): def printName(name='Sathith'):


print('Name',name) print('Name',name)

printName() printName('Sathithraj')

x = 10 x = 10
def fun(): def fun():
x=30 x=30
print('Value inside the function:',x) print('Value inside the function:',x)

print('Value outside the function:',x) print('Value outside the function:',x)


fun() fun()
print(x)

60 of 87
def new(x,y,z=10): def new(x,y,z=10):
print(x*y,z) print(x*y,z)
a=10 new(10,12)
b=5
new(a,b)

def err(x=10,y): def err(x=10,y,z=5):


z = x+y z = x+y+z
print(z) print(z)
err(4) err(4)

Note→

def err(x=10,y=4,z): def err(x,y=4,z):


z = x+y+z z = x+y+z

"Sparking minds, The best education"– [Link]


print(z) print(z)
err(4) err(4)

def err(x=5,y=4,z): def err(x=5,y,z):


z = x+y+z z = x+y+z
print(z) print(z)
err(4) err(4)

rhu;gpDs; return ,idg; ghtpj;jy;


• return MdJ rhu;gpDs; ntspaPl;bidf; fhl;Ltjw;fhf gad;gLj;jg;gLk; xU fl;lis
MFk;.
def cal(x=5,y=2): def cal(x=5,y=2):
if(x==5): if(x==5):
if(y==1): if(y==1):
return 'y is 1' return 'y is 1'
else: else:
return 'y is 2' return 'y is 2'
else: else:
return "x isn't 5" return "x isn't 5"

cal() print(cal())

61 of 87
def returnFun(): def returnFun():
x=4 x=6
return(x) return x

print(returnFun()) print(returnFun())

x = 10 def key():
def returnFun(): x=5
x=6 return 5*x
return x
return x return x
print(returnFun()) print(key())

Note →

"Sparking minds, The best education"– [Link]


def loopFun(): def loopFun():
for x in range(1,10): for x in range(1,10):
return x print(x)

print(loopFun()) loopFun()

def loopWhile(x=5): def loopWhile(x=5):


while(x>=1): while(x>=1):
return x*5 return x*5
return 'Hello' print('Hello')

print(loopWhile()) print(loopWhile())

def loopWhile(x=5): def loopWhile(x=5):


while(x>=1): while(x>=1):
print(x*5) print(x*5)
x-=1 x-=1
return 'Hello' return 'Hello'
return 'Hi'
print(loopWhile())
print(loopWhile())

62 of 87
def loopWhile(x=5): def loopWhile(x=5):
while(x>=1): while(x>=1):
print x return x
x-=1 x-=1

print(loopWhile()) print(loopWhile())

print kw;Wk; return Mfpatw;wpid xg;gpl;L NtWgLj;Jf.


xg;gPL →

print return

"Sparking minds, The best education"– [Link]

63 of 87
Python Global, Local and Nonlocal Variables
(G+Nfhs khwp> cs;sik khwp kw;Wk; cs;sik my;yhj khwp)
Global Variable (G+Nfhs khwp)
• In Python, a variable declared outside of the function or in global scope is known as a global variable.
This means that a global variable can be accessed inside or outside of the function.
Example →

x = 5 # Global Variable
def globalVar():
print('x inside:',x)
globalVar()
print('x outside:',x)

output →

"Sparking minds, The best education"– [Link]


• NkYs;s cjhuzj;jpy; x vDk; global variable cUthf;fg;gl;Ls;sJ. mj;Jld; globalVar()
vDk; rhu;ghdJ global variable x ,id ntspaPL nra;tjw;fhf cUthf;fg;gl;Ls;sJ.

Example 2 →

x = 5 # Global Variable
def globalVar():
x = x + 10
globalVar()

output → UnboundLocalError: local variable 'x' referenced before assignment


• NkYs;s cjhuzj;jpid epiwNtw;Wk; NghJ Error Njhw;Wtpf;fg;gl;Ls;sJ. fhuzk;
globalVar() vDk; rhu;gpDs; fhzg;gLfpd;w x vDk; khwpapid igjd; local variable Mf
fUJfpd;wJ. mj;Jld; khwp x MdJ rhu;gpDs; tiuaWf;fg;gltpy;iyahFk;.
• ,jid eptu;j;jp nra;tjw;F global vDk; fl;lisr; nrhy; rhu;gpDs; gad;gLj;jg;gLk;.
Example →

x = 5 # Global Variable
def globalVar():
global x
x = x + 10
print(x)
globalVar()

64 of 87
Question →
x=5 x=5 x=5
def globalVar(): def globalVar(): def globalVar():
global x global x global x
x = x + 10 x = x + 10 x = x + 10
print(x) print(x) print(x)

globalVar() print(x) print(x)


print(x) globalVar() globalVar()
print(x)

Local Variable (cs;sik khwp)


• A variable declared inside the function's body or in the local scope is known as a local variable

"Sparking minds, The best education"– [Link]


def localVar(): def localVar():
x = 10 x = 10
return x return x

print(localVar()) print(localVar())
print(x)

Nonlocal Variable (cs;sik my;yhj khwp)


def outer(): def outer(): x = 'global'
x = "local" x = "local" def outer():
x = "local"
def inner(): def inner():
nonlocal x nonlocal x def inner():
print("inner:", x) x = "nonlocal" nonlocal x
print("inner:", x) x = "nonlocal"
inner() print("inner:", x)
print("outer:", x) inner()
print("outer:", x) inner()
outer() print("outer:", x)
outer()
outer()
print(x)

65 of 87
x = 'global' x = 'global' x = 'global'
def outer(): def outer(): def outer():
x = "local" x = "local" x = "local"

def inner(): def inner(): def inner():


nonlocal x nonlocal x nonlocal x
x = "nonlocal" x = "nonlocal" x = "nonlocal"
print("inner:", x) print("inner:", x) print("inner:", x)
print(x)
print("outer:", x) print("outer:", x)
inner() inner() inner()
print("outer:", x) print("outer:", x)
outer()
print(x) outer() outer()
print(x) print(x)

"Sparking minds, The best education"– [Link]


Python Recursion
Python Recursive Function
• igjdpy; xU rhu;ghdJ ,d;DnkhU rhu;gpid miof;f KbAk;. NkYk;> xU rhu;ghdJ
mNj rhu;gpid (jd;id) miof;f KbAk;. ,it Roy;epiy nraw;ghLfs; (Recursive
function) vd miof;fg;gLfpd;wd.

In Python, we know that a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.

66 of 87
Example 1 →
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 5
print("The factorial of", num, "is", factorial(num))

output →

Example 2 →
def fun(n):
if n == 0:

return 0

"Sparking minds, The best education"– [Link]


return n + fun(n-1)
print(fun(4))

Python String split() method

The split() method splits a string into a list.


………………………………………………………………………………………………………………
You can specify the separator, default separator is any whitespace.
………………………………………………………………………………………………………………
When maxsplit is specified, the list will contain the specified number of elements plus one.
………………………………………………………………………………………………………………

Example output

text = "Hello! I'm Sathith"


t = [Link]()
print(t)

67 of 87
Questions:

text = "Hel'lo! I'm Sathith" text = "Python,Programming,Class"


t = [Link](" '") t = [Link](',')
print(t) print(t)

text = "Pyt$hon$Pro$gram$ming,C$las$s" text = "Python, #Program#ming,Cla#ss"


t = [Link]('$') t = [Link]('#',1)
print(t) print(t)

Python String splitlines() method

"Sparking minds, The best education"– [Link]


• Line Break ,id mbg;gilahff; nfhz;L gpupj;jy;

text = "Python\n Programming\n Class"


t = [Link]()
print(t)

Python String strip() Method


The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters
(space is the default leading character to remove)
text = " Python Class " text = "Python ClassPy"
x = [Link]() x = [Link]("Py")
print(x) print(x)

text = "****Hello!****I'm Python*****" text = "****Hello!****I'm Python*****"


x = [Link]("*") x = [Link]("*He")
print(x) print(x)

68 of 87
Python File Handling
• igjdpy; Nfhg;Gf;fis ifahSk; NghJ open( ) vDk; function Kjd;ikahf fhzg;gLk;.
(The key function for working with files in Python is the open() function.)

• open( ) function MdJ ,uz;L parameter ,idf; nfhz;ljhFk;.


1. file name
2. mode

• Files are named locations on disk to store related information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses its data when the computer is
turned off), we use files for future use of the data by permanently storing them.
• When we want to read from or write to a file, we need to open it first. When we are done, it needs
to be closed so that the resources that are tied with the file are freed.

• vdNt igjdpy; gpd;tUk; tupirapy; Nfhg;G nraw;ghL eilngWfpd;wJ.


1. Open a file

"Sparking minds, The best education"– [Link]


2. Read or Write (perform operation)
3. Close the file
Mode Description
r Read - Default value. Opens a file for reading, error if the file does not exist
w Write - Opens a file for writing, creates the file if it does not exist
a Append - Opens a file for appending, creates the file if it does not exist
r+ for both reading and writing
t Opens in text mode. (default)

Read a File
[Link] ↓

code → output →
f = open("[Link]","r")
print([Link]())

69 of 87
Open a file on different location
f = open("D:\\[Link]","r")
print([Link]())

Read only part of the file


• By default the read() method returns the whole text, but you can also specify how many characters
you want to return:
• Example →
[Link] ↓

code → output →
f = open("[Link]","r")

"Sparking minds, The best education"– [Link]


print([Link](10))

Read Lines
Example 1 →

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

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

Example 2 →
f = open("[Link]","r")
for x in f:
print(x)

70 of 87
Close Files

Example →

f = open("[Link]","r")
print([Link]())
[Link]()
Python File Write

Write to an Existing File


• a - Append
• w - Write

1. Write Mode

Example 1 →

f = open("[Link]","w")
[Link]("Python Write Mode in File Handling")

"Sparking minds, The best education"– [Link]


[Link]()

Example 2 →

f = open("[Link]","w")
[Link]("Python Write Mode in File Handling")
[Link]()

#open the [Link] file after write


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

2. Append Mode

Example →

f = open("[Link]","a")
[Link]("\nHi there!")
[Link]()

#open the [Link] file after appending


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

71 of 87
Note 1 → The "w" method will overwrite the entire file.

Create a New File


• a - Append - will create a file if the specified file does not exist
• w - Write - will create a file if the specified file does not exist
• x - Create - will create a file, returns an error if the file exist

Delete a File
• To delete a file, you must import the OS module, and run its [Link]() function
• Example →

import os
[Link]("[Link]")

"Sparking minds, The best education"– [Link]


Check If File Exist
• To avoid getting an error, you might want to check if the file exists before you try to delete it.
• Example →

import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")

Delete Folder
import os
[Link]("New folder")

Note → You can only remove empty folders.

72 of 87
Nju;r;rp kl;lk;: 9.12
juTj;jsq;fspy; juT Kfhikj;Jtk; nra;thu;.

igjd; MySQL
juTj;jsg; gpuNahfq;fspy; igj;jd; nkhopiag; gad;gLj;jKbAk;. MySQL MdJ gpugy;akhd
juTj;js nkd;nghUs;fspy; xd;whFk;.
MySQL nrYj;jpapid epWTjy;
igj;jd; nkhopf;F MySQL juTj;jsj;jpid mZFtjw;F MySQL nrYj;jp mtrpakhFk;.
,jw;fhf "MySQL Connector" vd;w nrYj;jp gad;gLj;jg;gLfpd;wJ. "MySQL Connector" ,id
epWTtjw;F PIP gad;gLj;jg;gLfpd;wJ. igj;jd; nghjpfs; my;yJ modules ,w;F PIP xU nghjp
Kfhikahsu; MFk;. igj;jd; epWtg;gLk; NghNj PIP vd;gJk; mNdfkhf epWtg;gl;bUf;Fk;.
(igj;jid epWTk; NghJ, “Install Now” ,w;Fg; gjpyhf “Customize installation” vd;gijj; njupT
nra;jy; Ntz;Lk;. ,t;thwhd epiyapy; PIP jhdhfNt epWtg;gLk;.)
igj;jd; epWtg;gl;Ls;s miltpidf; fl;lis tupA+lhf mZfpg; gpd;tUk; fl;lisapid
toq;FtjD}lhf PIP epWtg;gl;Ls;sjh vd;gijg; guPl;rpf;fyhk;.
C:\Users\your name\AppData\Local\Programs\Python\Python37-32\Scripts> pip – version

"Sparking minds, The best education"– [Link]


PIP epWtg;gl;bUf;fhtpbd; [Link] Clhfg; gjptpwf;fk; nra;J epWtyhk;.
igj;jd; ,Uf;Fk; miltpidf; fl;lis tupA+lhf mZfpg; gpd;tUk; fl;lisia
toq;FtjD}lhf "MySQL Connector" I gjptpwf;fk; nra;J epWtpf;nfhs;syhk;.
C:\Users\your name\AppData\Local\Programs\Python\Python37-32\Scripts>pip install mysql-
connector
"MySQL Connector" ,idg; guPl;rpj;jy;
epWty; ntw;wpfukhf eilngw;Ws;sjh vd;gij my;yJ "MySQL Connector" Vw;fdNt
epWtg;gl;Ls;sjh vd;gijg; guPl;rpg;gjw;F gpd;tUk; cs;slf;fq;fisf; nfhz;l igj;jd; gf;fk;
xd;wpid cUthf;fTk;. fPo; fhzg;gLk; FwpKiw gpioapd;wpr; nraw;gLj;jg;gLkhap;d; , "MySQL
Connector" epWtg;gl;Lj; jahu; epiyapy; cs;sjhff; fUjyhk;.
import [Link]
MySQL juTj;js ,izg;gpid cUthf;Fjy;
juTj;js gadu;ngau; kw;Wk; flTr;nrhy; vd;gtw;iwg; gad;gLj;jp MySQL juTj;js
,izg;gpid cUthf;fyhk;.
Note → ,ay;ghf gadu; ngau; “root” MfTk;> flTr; nrhy; ntWikahfTk; fhzg;gLk;.

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password =""
)
print(dbConnect)

73 of 87
juTj;jsnkhd;wpid cUthf;Fjy;
KV vDk; ngaupy; juTj;jsnkhd;wpid cUthf;Fjy;

juTj;jsnkhd;wpid ePf;Fjy;
KV vDk; ngaiuAila juTj;jsj;jpid ePf;Fjy;

"Sparking minds, The best education"– [Link]


ml;ltiznahd;wpid cUthf;Fjy;
staffId, name, address, dob, stafftype vDk; Gyq;fisf; nfhz;l staff ml;ltizapid
cUthf;Fjy;.

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("CREATE TABLE staffga(staffId int, name varchar(255) not null, address
varchar(255), dob date, stafftype varchar(100), primary key(staffId))");

74 of 87
ml;ltiziaj; jpUj;jpaikj;jy; (Modify)
Staff ml;ltizapDs; Salary vDk; Gjpa Gyj;jpid Nru;j;jy;

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("ALTER TABLE staff ADD Salary float");

ml;ltizapid ePf;Fjy;
Staff vDk; ngaUila ml;ltizapid ePf;Fjy;

"Sparking minds, The best education"– [Link]


import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("DROP TABLE staff");

75 of 87
ml;ltiznahd;wpDs; juTfis cs;Eioj;jy;
,jw;fhf commit( ) Kiw mtrpakhFk;. ,y;iynadpy; ml;ltizapy; khw;wq;fs; Vw;gLj;jg;gl
khl;lhJ.
staff ml;ltizf;F Gjpa gjptpid cl;Nru;j;jy;

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
sql = "INSERT INTO staff (staffId, name, address, dob, stafftype, Salary) VALUES
(%s,%s,%s,%s,%s,%s)"
val = ("1001","Sathith","Thirukkovil","1999-06-21","Academic","128000")
[Link](sql,val);

"Sparking minds, The best education"– [Link]


[Link]()
print([Link], "record inserted")

ml;ltiznahd;wpDs; gy ghpTfis cs;Eioj;jy;


import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
sql = "INSERT INTO staff (staffId, name, address, dob, stafftype, Salary) VALUES
(%s,%s,%s,%s,%s,%s)"
val = [
("1002","Diloo","Akkaraipattu","1997-12-10","Academic","130000"),
("1003","Raj","Colombo","1994-4-18","Academic","96000")
]
[Link](sql,val);
[Link]()
print([Link], "record inserted")

76 of 87
juTfisj; njupT nra;jy;
ml;ltizapy; ,Ue;J midj;Jj; juTfisAk; ngWtjw;F fetchall( ) Kiw gad;gLj;jg;gLk;.
fetchone( ) Kiwiag; gad;gLj;jp xU gjptpid khj;jpuk; ngwyhk;.
Staff table structure

Staff ml;ltizapy; ,Ue;J midj;Jg; gjpTfisAk; kPsg;ngwy;

"Sparking minds, The best education"– [Link]


import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("SELECT * FROM staff")
result = [Link]()

for i in result:
print(i)

Output:

77 of 87
import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("SELECT * FROM staff WHERE stafftype = 'academic'")
result = [Link]()

for i in result:
print(i)

Output:

"Sparking minds, The best education"– [Link]


import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("SELECT * FROM staff")
result = [Link]()

print(result)

Output →

78 of 87
import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("SELECT * FROM staff")
result = [Link]()

for x in result:
print(x)

"Sparking minds, The best education"– [Link]


Output →

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
[Link]("SELECT name, address FROM staff")
result = [Link]()

for x in result:
print(x)

Output →

79 of 87
ml;ltizapYs;s juTfis ,w;iwg;gLj;jy;
Staff ml;ltizapYs;s 1004 vDk; Staff Id ,id cila Copaupd; Kftupia Kalmunai Mf
khw;wk; nra;jy;.

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
sql = "UPDATE staff SET address = 'Kalmunai' WHERE staffId='1004'"
[Link](sql)
[Link]()
print([Link], "record(s) affected")

"Sparking minds, The best education"– [Link]


ml;ltizapYs;s juTfis ePf;Fjy;
Staff ml;ltizapYs;s Staff id 1003 ,id cila Copaupd; gjptpid ePf;Fjy;.

import [Link]
dbConnect = [Link](
host = "localhost",
user = "root",
password ="",
database = "kv"
)

mycursor = [Link]()
sql = "DELETE FROM staff WHERE staffId='1003'"
[Link](sql)
[Link]()
print([Link], "record(s) affected")

80 of 87
Nju;r;rp kl;lk;: 9.13 NjLjYk; tupirg;gLj;jYk; (Searches and sorts data)
Njly; El;gq;fs;
Fwpj;j cUg;gbfspd; njhFjpapy; ,Ue;J Fwpj;j xU cUg;gbapidj; NjLtjw;Fg;
gad;gLj;jg;gLk; newpKiwr; nrad;Kiw Njly; vdg;gLk;. toikahfj; NjlyhdJ True my;yJ
False vd;gijj; NjlYf;fhd gjpyhfj; jUk;.
igj;jd; nkhopapy; Fwpj;j cUg;gbahdJ gl;baYf;Fs; cs;sjh vd;gijg; gupNrhjpg;gJ
,yFthdjhFk;. ,jw;F "in " vd;Dk; nrayp gad;gLj;jg;gLfpd;wJ.

njhlupay; Njly;
▪ gl;bay; Nghd;w njhFg;Gfspy; Nrkpf;fg;gl;Ls;s juT cUg;gbfs; njhlu;r;rpahd my;yJ

"Sparking minds, The best education"– [Link]


tupirKiwapyhd njhlu;gpidf; nfhz;bUf;Fk;.
▪ Xt;nthU cUg;gbAk; Vida cUg;gbfspd; epiyAld; njhlu;GilathW
Nrkpf;fg;gl;bUf;Fk;.
▪ igj;jdpd; gl;baypy; ,e;jj; njhlu;Gila ,lq;fs; xt;nthU cUg;gbapdJk;
Rl;Lg;ngWkhdkhFk;.
▪ ,e;jr; Rl;Lg;ngWkhdq;fs; njhlu;r;rpahff; fhzg;gLtjpdhy; tupir Kiwapy; mtw;iw
mZff;$bajhf ,Uf;fpd;wJ.
▪ ,t;tifj; Njlypy; midj;J cUg;gbfisAk; xt;nthd;whf tupirKiwapy; NjlKbAk;.
▪ xt;nthU cUg;gbAk; rupghu;f;fg;gl;L> nghUe;Jkhapd; me;j cUg;gb jpUk;gyhFk;. my;yJ
juTf; fl;likg;G KbAk; tiu Njly; eilngWk;.

tupirg;gLj;jy; El;gq;fs;
tupirg;gLj;jy; vd;gJ juTfis xU Fwpj;j xOq;fpy; tbtikg;gjhFk;. mt;nthOq;fikg;G
VWtupir my;yJ ,wq;Ftupirahff; fhzg;glyhk;.
tupirg;gLj;jy; newpKiwahdJ> juTfis xU Fwpj;j tupirapy; xOq;F gLj;Jk; Kiwiaf;
Fwpg;gpLfpd;wJ.
Fkpo; tupirg;gLj;jy; (Bubble Sort)
Fkpo; tupirg;gLj;jyhdJ> gl;baypD}lhfg; gy flj;jy;fis (passes) Nkw;nfhs;fpd;wJ. ,q;F
mLj;Js;s cUg;gbfs; xg;gplg;gl;L mit xOq;fw;Wf; fhzg;gLkhapd; ,lk;khw;wg;gLk;.
gl;baypd; xt;nthU flj;jypd; NghJk; mLj;j ngupa ngWkhdk; cupa ,lj;jpy;
epiyg;gLj;jg;gLk;. RUf;fkhff; $wpd; xt;nthU cUg;gbAk; mjw;Fupa ,lj;jpy;
epiyg;gLj;jg;gLk; (bubbles up).

81 of 87
gl;bay; xd;wpid VWtupirg;gLj;jy;
▪ KjyhtJ kw;Wk; ,uz;lhtJ epiyfspy; fhzg;gLk; $Wfis xg;gply;.
▪ KjyhtJ epiyapy; fhzg;gLk; ngWkhdk; ,uz;lhtJ epiyapy; fhzg;gLk;
ngWkhdj;jpid tplg; ngupjhapd; mtw;wpd; epiyfis khw;wy;.
▪ jw;NghJ ,uz;lhk; epiyapy; fhzg;gLk; ngWkhdk; Kd;whk; epiyapy; fhz;gLk;
ngWkhdj;Jld; xg;gplg;gl;L mtrpakhapd; epiy khw;wy;.
▪ ,t;thNw ,Wjp ,uz;L $Wfis xg;gpLk; tiu njhlu;e;J nra;jy;.
▪ jw;NghJ kpfg;ngupa $W mzpapd; ,Wjp epiyapy; fhzg;gLk;.
▪ ,t;thW> NkYk; epiykhw;wy;fs; Njit ,y;iynadf; fUJk; tiuf;Fk; ,r;nraiy
kPz;Lk; kPz;Lk; Muk;gj;jpy; ,Ue;J nraw;gLj;jy;. (cjhuzk;: gl;banyhd;iw
tupirg;gLj;jy;)
▪ mzpapDhlhf xt;nthU Kiw gazpf;Fk;NghJk; kpfg;ngupa $W ePu; Fkpop Nghy; mzpapd;
,Wjpf;Fr; nry;Yk;.

"Sparking minds, The best education"– [Link]


Python Code for bubble sort

def bubble_sort(L):
swapped = True # set flag to True to repeat sorting
while swapped:
swapped = False
for i in range(len(L) – 1):
if L[i] > L[i + 1]:
# Swap the elements
L[i], L[i + 1] = L[i + 1], L[i]
# Set the flag to True so we’ll loop again
swapped = True

82 of 87
nra;epuy; nkhop ngau;g;gfq;fs; (Program Translators)
VjhtJ fzpdp epfo;rp epuy; nkhopapid gad;gLj;jp vOjg;gl;l %yr; nra;epuiy (source
program) > nghUs; Nehf;Fila (object) ,ae;jpu nkhopf;F khw;wg;glNtz;ba gzpapid ,J
Nkw;nfhs;fpd;wJ.
%yr; nra;epuy;/ %y fl;lisj; njhFjp (Source Program)
Python, Java, C, C++, C# Nghd;w cau;kl;l nkhopfspy; vOjg;gl;l nra;epuy;fs; MFk;. ,J
Fwpj;j nkhop gw;wpa mwpTs;s kdpju;fshy; tpsq;fpf; nfhs;sf;$bajhf cs;sJ.
A source program is a text file that contains instructions written in a high level language. It can not be
executed (made to run) by a processor without some additional steps. A source program is also called a
source file, source code, or sometimes, just source.
nghUs; Nehf;Fr; nra;epuy;/ cU fl;lisj; njhFjp (Object Program)
%yr; nra;epuy;fshdJ fzpdpapdhy; Neubahf tpsq;fpf; nfhs;sf; $ba 0, 1 ,id
mbg;gilahff; nfhz;l ,ae;jpu nkhopahf (machine code) khw;wg;gl;lJk; gpd;du; mit nghUs;
Nehf;Fr; nra;epuy; vd miof;fg;gLfpd;wd.

"Sparking minds, The best education"– [Link]


MfNt> %yr; nra;epuy; xd;wpid nghUs; Nehf;Fr; nra;epuyhf khw;wk; nra;tNj nra;epuy;
nkhop ngau;g;gfq;fs; MFk;.
tupnkhopkhw;wp> njhFg;gpfs; Mfpa ,uz;L nra;epuy; nkhop ngau;g;gfq;fs; cs;sd.
A computer program which has been translated into machine language by a compiler and assembler, but not
yet linked into an executable program; sometimes called an obj file, because its file name typically has the
extension.

Source Code → Translators → Object Code

tupnkhopkhw;wp/ nghUs; Nfhlyp (Interpreter)


tupnkhop khw;wpahdJ %yr; nra;epuiy xNu Neuj;jpy; xU mwTWj;jy; / xU $w;W (Statement)
mbg;gilapy; nghUs;Nehf;F nra;epuypw;F khw;Wk;. ,jdhy; nraw;gL Neuk; (execution time)
mjpfkhff; fhzg;gLfpd;wJ.
tupnkhopkhw;wpapidg; gad;gLj;Jk; nra;epuy; nkhopfs;: BASIC, Fortran, JavaScript, Python, Ruby

83 of 87
njhFg;gpfs; (Compilers)
njhFg;gpfs; %ynray;epuiy xNu jlitapy; nghUs; Nehf;F nray;epuYf;F khw;Wk;. ,r;nray;
Kiwapd; gpd; xU epue;ju Jtpj FwpKiwahf nghUs; Nehf;F nray;epuy; cUthf;fg;gLfpd;wJ.;
,jd; nraw;gL Neuk; FiwthdjhFk;.
njhFg;gpapidg; gad;gLj;Jk; nra;epuy; nkhopfs;: Pascal, C, C++, Java

Interpreter Vs Compiler
Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it as a
whole into machine code.
Interpreters usually take less amount of time to Compilers usually take a large amount of time to
analyze the source code. However, the overall analyze the source code. However, the overall
execution time is comparatively slower than execution time is comparatively faster than
compilers. interpreters.
No Object Code is generated, hence are memory Generates Object Code which further requires
efficient. linking, hence requires more memory.

"Sparking minds, The best education"– [Link]


fzpdp nra;epuy; nkhopfspd; jiyKiwfs; (Generation Of Computer Programming Language)
1. Kjyhk; re;jjp fzpdp nkhop (First Generation Language)/ ,ae;jpu nkhop (Machine
Language) 1GL
2. ,uz;lhk; re;jjp fzpdp nkhop (Second Generation Language)/ xUq;FNru;g;G nkhop (Assembly
Language) 2GL
3. %d;whk; re;jjp fzpdp nkhop (Third Generation Language) 3GL
4. ehd;fhk; re;jjp fzpdp nkhop (Fourth Generation Language) 4GL
5. Ie;jhk; re;jjp fzpdp nkhop (Fifth Generation Language) 5GL
Kjyhk; re;jjp fzpdp nkhop (First Generation Language/ Machine Language)
nra;epuy;fs; ahTk; 0,1 id mbg;gilahf nfhz;l ,ae;jpu FwpKiwapy; vOjg;gLk;. nra;epuy;
epiwNtw;Wif kpf NtfkhdJ fhuzk; Translator mtrpakpy;iy. 3GL kw;Wk; 4GL cld;
xg;gpLk; NghJ nra;epuy; vOJjy; kw;Wk; Nrhjid nra;jy; kpfTk; fbdk;. Fwpj;j fzpdpapy; /
,ae;jpuj;jpy; jq;fpapUf;Fk; nkhopahFk;. mjhtJ xU fzpdpf;F vOjpa nra;epuy; NtW
fzpdpf;F nghUe;jhJ. (Machine dependent)

84 of 87
,uz;lhk; re;jjp fzpdp nkhop/ Assembly Language – 2GL
0,1 ,w;F gjpyhf vspa FwpaPLfs; gad;gLj;jp FwpKiw vOjg;gLk;. nra;epuy; epiwNtw;Wif
Ntfk; FiwT fhuzk; Translator gad;gLj;jg;gLk; (Assembler). 3GL kw;Wk; 4GL cld; xg;gpLk;
NghJ nra;epuy; vOJjy; kw;Wk; Nrhjid nra;jy; kpfTk; fbdk;. Fwpj;j fzpdpapy; /
,ae;jpuj;jpy; jq;fpapUf;Fk; nkhopahFk;. mjhtJ xU fzpdpf;F vOjpa nra;epuy; NtW
fzpdpf;F nghUe;jhJ. (Machine dependent)
%d;whk; jiyKiwf; fzpdp nkhop 3GL
nra;epuy;fs; ahTk; fzpj FwpaPLfs; ,aw;if nkhopapid gad;gLj;jp vOjg;gLk;. kdpjd;
tpsq;fpf; nfhs;tJ ,yF. nra;epuy; epiwNtw;Wif Ntfk; FiwT fhuzk; Translator mtrpak;.
1GL kw;Wk; 2GL cld; xg;gpLk; NghJ nra;epuy; vOJjy; kw;Wk; Nrhjid nra;jy; kpfTk;
,yF. ,J ,ae;jpuj;jpy; jq;fpapuhj nkhopahFk;. ,k; nkhopf;F nkhopngah;g;gpfs; mtrpakhFk;.
Example → C, C++, Java, Pascal, Fortran, COBOL
ehd;fhk; jiyKiwf; fzpdp nkhop 4GL
nra;epuy;fs; ahTk; fzpj FwpaPLfs; ,aw;if nkhopapid gad;gLj;jp vOjg;gLk;. kdpjd;
tpsq;fpf; nfhs;tJ ,yF. nra;epuy; epiwNtw;Wif Ntfk; FiwT fhuzk; Translator mtrpak;.
1GL,2GL cld; xg;gpLk; NghJ nra;epuy; vOJjy; kw;Wk; Nrhjid nra;jy; kpfTk; ,yF.

"Sparking minds, The best education"– [Link]


nkd;nghUl;fis kpf Ntfkhf tpUj;jp nra;jplyhk;. ,J ,ae;jpuj;jpy; jq;fpapuhj nkhopahFk;.
,k; nkhopf;F nkhopngah;g;gpfs; mtrpakhFk;.
Example → Python, PHP, SQL, Ruby, Foxpro, Focus
Ie;jhk; jiyKiwf; fzpdp nkhop 5GL
,f;fzpdp nkhopfspy; Visual Tools fis nfhz;bUg;gjdhy; nra;epuy; vOJtJ ,yF. ,J
Object Oriented Programing language (OOP) vdTk; miof;fg;gLk;. ,J nraw;if Ez;zwpT (AI)
nkhopahFk;.
Parallel Processing & superconductors are used for this type of language to make real artificial intelligence.
5GL ,d; mD$yq;fs;
1. ,ae;jpuq;fs; jPu;khdq;fis vLf;f KbAk;.
2. gpur;rpidnahd;wpidj; jPu;g;gjw;F nra;epuyhsu;fspd; Kaw;rpapidf; Fiwf;fpd;wJ.
3. fw;gjw;Fk;> gad;gLj;Jtjw;Fk; 3GL kw;Wk; 4GL I tpl ,yFthdJ.
5GL ,d; gpujp$yq;fs;
1. rpf;fyhdJ kw;Wk; mjpfstpyhd FwpKiwfs; (Long Code)
2. mjpfstpyhd tsq;fs; Njit kw;Wk; mit tpiy $bait.
Note → 1Gl kw;Wk; 2GL vd;gd jho;kl;l fzpdp nkhopfshf fUjg;gLk;. 3GL kw;Wk; 4,5 GL
vd;gd cah;kl;l fzpdp nkhopfshf fUjg;gLk;.
Note → 1GL jtpu Vida midj;jpYk; Translator mtrpak;.

85 of 87
nra;epuyhf;f fl;lis gbtq;fs; (Program Paradigms)
nra;epuy; nkhopfs; nraw;gLk; tpjj;jpd; mbg;gilapy; mtw;iw ,uz;L gpujhd tiffshf
tifg;gLj;jyhk;. ,t;tifg;gLj;jy; fl;lisg; gbtq;fs; vdg;gLfpd;wJ.
1. fl;lisapLk; nkhopfs; (Imperative Language)
2. ntspapLk; nkhopfs; (Declarative Language)

Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some
fl;lisapLk; nkhopfs;
programming language or also we can say it is a method to solve a problem using
tools and techniques
,J kpfTk; nghJthd that are available
tifapidr; rhu;e;[Link] us ,t;
following some approach.
tifapy; njhlupay; fl;lisfshf
(imperatives) nra;epuy; vOjg;gLfpd;wJ. NkYk; ,it %d;W tiffshf tifg;gLj;jg;gLfpd;wd.
▪ eilKiw (Procedural) – C
▪ nghUs; rhu;e;jJ (Object Oriented) – C++, Java, Objective-C, Python, Ruby, Simula (First OOP
Lang)
▪ rkhe;ju Kiwtopahf;fk; (Parallel Processing) – Java, NESL (One of the Oldest One)
ntspapLk; nkhopfs;

"Sparking minds, The best education"– [Link]


,J kpfTk; mupjhd tifapidr; rhu;e;jJ. ,t;tifapy; Fwpj;j njhlupay; my;yJ $w;Wf;fNsh
fhzg;glhjJld; tpj;jpahrkhd gha;r;ry;fisf; nfhz;bUf;fyhk;. NkYk; ,it %d;W
tiffshf tifg;gLj;jg;gLfpd;wd.
▪ ju;f;f nra;epuy; gbtk; (Logical programming paradigm) – Prolog
▪ rhu;Gr; nra;epuy; gbtk; (Functional programming paradigm) – Lisp, JavaScript, Scala, Erlang,
Clojure
▪ juTj;jsk; (Database) – SQL

fzpdp nra;epuyhf;fj;jpd; NghJ Vw;glf;$ba tOf;fs; (Types of Errors)


fzpdp nra;epuyhf;fj;jpd; NghJ gpujhdkhf gpd;tUk; %d;W tOf;fs; Vw;gLfpd;wd.
1. njhlupay; tO (Syntax Error)/ njhFg;gp Neu tO (Compile Time Error)
2. ,af;f Neu tOf;fs; (Runtime Errors)
3. ju;f;ftpay; tOf;fs; (Logical Errors/ Semantics Errors)
Syntax Error
,J nra;epuy; nkhopapYs;s fl;lisr; nrhw;fspy; (Key Word) Vw;gLj;jg;gLk; gpiofs; kw;Wk;
nra;epuy; nkhopapd; fl;likg;gpy; Vw;gLj;jg;gLk; gpiofshFk;. njhlhpay; tOf;fSld; $ba
nra;epuy; mjd; KbT tiu ,aq;fkhl;lhJ. mr; nra;epuypw;Fhpa ntspaPl;bidAk; ngwKbahJ.
tOf;fs; jpUj;jg;gl;L kPz;Lk; mr; nra;epuiy nraw;gLj;JtJtjd; %yk; ntspaPl;bidg; ngw
KbAk;. ,t;tOf;fs; jpUj;jg;gLk; tiu nra;epuy; ,aq;fhJ.
Example:
1. fl;lisr; nrhw;fis jtwhfg; gad;gLj;jy;. (print ,w;F gjpyhf Print ,id gad;gLj;jy;)
2. khwpapd; ngaiu gpioahf mioj;jy;.
3. fl;lis kw;Wk; rhu;Gfspd; ngaupid gpioahf mioj;jy; (Spelling Mistake)
4. ( ) ,id jtwtply;> Colon ( : ), Semi Colon ( ; ), Inverted Comma ( “ ” ) ,id jtwtply;
5. cs;js;sy; (indent) jtwtply;
6. cupa ,lq;fspy; milg;Gf;Fwpfs; njhLf;fg;gl;L Kbf;fg;glhik.

86 of 87
Runtime Error
njhlupay; tOf;fs; ,y;yhj nra;epuiy nraw;gLj;j Kaw;rpf;Fk; NghJ mJ Fwpj;j
nraw;ghl;il nra;ahJ. ,J nra;epuiy epiwNtw;Wk; NghJ cUthfpd;wJ.
Example: Devision by Zero Error, tl;by; ,y;yhj xU Nfhitapd; ngaiu jpwj;jy; my;yJ
mioj;jy;.
Logical Error
Fwpj;j igj;jd; nra;epuypy; FwpaPl;L hPjpahf vJtpjkhd tOf;fSk; ,d;wp nra;epuyhshpdhy;
,lg;gLfpd;w jtWfs; ,tw;Ws; mlq;Fk;. mjhtJ nra;epuypw;Fhpa ntspaPL ngwg;gLk;. Mdhy;
mt; ntspaPL jtwhdjhff; fhzg;gLk;. nrh ;nghUspay; tOf;fSld; $ba nra;epuyhdJ
,Wjp tiu ,aq;fp ntspaPl;bidj; jtwhfj; jUk;.
Example: NtnwhU Nfhg;gpid jpwe;J juTfis khw;wk; nra;jy;> $l;Lk; NghJ fopgly;>
ngUf;Fk; NghJ gpupgly;.

The End!

"Sparking minds, The best education"– [Link]

87 of 87

You might also like