0% found this document useful (0 votes)
17 views

Python For Beginner

Uploaded by

John Abebrese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python For Beginner

Uploaded by

John Abebrese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

PYTHON

PROGRAMMING
In This Book You Will Learn Explanation with Diagramme and
Working Exercises with Successful Execution of Exercises with Output
Readymade Solution With Step By Step Explanation

AMIT K

Contents
Beginners Guide to Learn Python Programming Step by Step

Introduction …………………………………………………………………..…. 27
Chapter 1 : Introduction …………………………………………………... 28
1 What is Python ………………………………………………………… 28
2 Important Terms You Should Know with Python ……… 29
3 Why learn Python ………………………………………………….… 31
4 Java vs Python Program ………………………………….……..… 33
5 Where can we use Python ……………………………………..… 34
6 Popular Frameworks and Libraries of Python …………… 35
Chapter 2 : Python Basic …………………..………………………………. 36
1 Tokens …………………………………………………………………..… 37
1 Example 1 …………………………………………………………….. 38
2 Reserved Keywords …………………………………….…………… 41
Description of Keywords in Python with Examples ……. 43
1 Example 1 : True ………………………………………………….… 43
2 Example 2 : Checking the Value of true …………………. 44
3 Example 1 : False ………………………………………………….. 44
4 Example 1 : None Keyword ……………………………………. 46
5 Example 1 : and ………………………………………………….…. 47
6 Example 1 : or ……………………………………………………..… 48
7 Example 1 : not ……………………………………………………… 49
8 Example 1 : in ………………………………………………………… 50
9 Example 2 : traverse over a sequence in a for loop ... 51
10 Example 1 : is ……………………………………………………..… 51
11 Example 1 : for ……………………………………………………… 52
12 Example 1 : while ……………………………………………….... 52
13 Example 1 : break …………………………………………………. 53
14 Example 1 : continue ………………………..……………….…. 54
15 Example 1 : elif …………………………………………………..… 55
16 Example 1 : def …………………………………………………..… 56
17 Example 1 : return ………………………………………………… 57
18 Example 1 : yield …………………………………………………… 58
19 Example 1 : import ……………………………………………..… 59
20 Example 1 : from …………………………………………………… 60
21 Example 1 : del ……………………………………………………… 61
22 Example 1 : global ……………………………………………….… 62
23 Example 1 : nonlocal …………………………………………..… 63
24 Example 1 : not using the nonlocal ……………………….. 65
25 Example 1 : try, except, raise, and finally ……………… 66
26 Example 1 : assert ………………………………………………… 67
27 Example 1 : pass an error message with assert …..… 68
3 Identifiers …………………………………………………………………… 69
1 Five Rules for writing Identifiers in Python …………..… 69
4 Literals ………………………………………………………………………… 71
1 Example 1 : Literals ………………………………………………… 71
2 Types of Literals in Python Language ……………………… 72
3 String Literals ……………………………………………………….… 73
4 Example 1 : Adding a black slash (\) ……………………..… 74
5 Example 1 : Multi-line string literal ………………………… 74
6 Numeric literals ……………………………………………………… 75
7 Boolean literals ……………………………………………………… 76
8 Example 1 : Boolean literals …………………………………… 76
9 Special literals ………………………………………..……………… 77
10 Example 1 : Special literals ……………………………………. 77
11 Collection literals ………………………………………………….. 78
12 Example 1 : List literals …………………………………………. 78
13 Example 2 : Printing 10 natural numbers ……………… 79
14 Dictionary Literals ………………………………………………… 79
15 Example 1 : Dictionary Literals ……………………………... 80
16 Tuple Literals ………………………………………………………… 80
17 Example 1 : Tuple Literals ……………………………………… 80
18 Set Literals …………………………………………….……………… 81
19 Example 1 : Set Literals ……………………………………….… 81
5 Delimiters …………………………………………………………………… 82
1 Delimiters ……………………………………………………….……… 82
2 Example 1 : Delimiters …………………………………….…….. 83
6 Escape Sequence …………………………………………….……….… 84
1 Escape Sequence ………………………………………………….… 85
2 Example 1 : Escape Sequence \ ………………………………. 86
3 Example 2 : Escape Sequence \t …………………………….. 86
7 Variables ………………………………………………………………..…… 87
1 Variables ………………………………………………………………… 87
2 Example 1 : Creating integer and assigning value …… 87
3 Memory Location of a Variable ……………………………… 88
4 Example 1 : Memory Location of a Variable …………… 88
5 Example 2 : Creating variable and assigning value …. 90
6 Example 3 : Creating percentage ………………………….… 91
7 Example 4 : Initializing values to different variables … 92
8 Built-in Data Types …………………………………………………… 93
1 Types of Built-in Data types in Python …………………. 94
2 Number Data types in Python ……………………………… 95
3 Int Data type ……………………………………………………..… 95
4 Example 1 : Int Data type ………………………………..…… 97
5 Example 2 : Adding two integer variables ………….… 97
6 Float Data type ……………………………………………….…… 98
7 Example 1 : Assign a float value …………………………… 98
8 Complex Data type …………………………………….………… 99
9 Example 1 : Complex Data type ……………………….…… 99
10 Boolean Data type ……………………………………………… 100
11 Example 1 : Boolean Data type …………………………… 100
12 Sequence Data type ……………………………………….…… 101
13 String Data type ……………………………………………….…. 101
14 Example 1 : String Data type ……………………………..… 101
15 List Data type …………………………………………….………… 102
16 Example 1 : List Data type ………………………….………… 102
17 Example 2 : Updating elements in the list …….……… 103
18 Tuple Data type ……………………………………….…………… 104
19 Example 1 : Tuple Data type ……………………..…….…… 104
20 Set Data type …………………………………………………….… 105
11 Example 1 : Set Data type ……………………………….…… 105
9 Global and Local Variables ………………………………………… 106
1 Global Variables ………………………………….………………… 106
2 Example 1 : Global Variables …………………………….…… 107
3 Example 2 : Global Variables …………………………….…… 108
4 Example 3 : Global Variables …………………………….…… 109
5 Example 4 : Global Variables ………………….………...…… 110
6 Local Variable …………………………………..…………………… 112
7 Example 1 : Local Variable …………………………………..… 112
10 Memory Management ……………………………………………… 114
1 Memory Management ………………………………………..… 114
2 How Python Managing Memory ………………….………… 115
3 Example 1 : Assigning value to a variable …….………… 117
4 Example 2 : Two objects with non-overlapping …..... 118
5 Example 3 : Two objects with non-overlapping …….. 119
6 Example 4 : Two objects with non-overlapping …….. 120
7 Stack and Heap Memory in RAM …………………………… 122
8 Example 1 : Stack and Heap Memory …………....……… 122

Chapter 3 : Operators ……………………………………………………… 127


1 Arithmetic Operators ……………………………………………. 129
1 Addition Operator …………………………………………….… 129
2 Example 1 : Adding two numbers ……………………….. 130
3 Example 2 : Concatenating two strings …………..…… 130
4 Example 3 : Concatenate two lists ………………………. 131
5 Subtraction Operator ………………………………………….. 131
6 Example 1 : Subtraction of two numbers …………….. 131
7 Multiplication Operator …………………………………….… 132
8 Example 1 : Multiplication of two numbers ……….… 132
2 Assignment Operators ……………………………………………… 133
1 Simple assignment ………………………………………………. 133
2 Example 1 : Adding numbers ……………………………..… 133
3 Compound assignment ………………………………………… 134
4 Example 1 : Add , Assignment Operator (+=) ……..… 134
5 Example 2 : Subtract , Assignment Operator (-=) …..135
6 Example 3 : Multiply , Assignment operator (*=) …..135
7 Example 4 : Divide , Assignment Operator (/=) …….. 136
8 Example 5 : Modulus , Assignment operator (%=) ….137
9 Example 6 : Floor Division , Assignment Operator (//=) ..137
10 Example 7 : Exponent , Assignment Operator (**=) ..…138
11 Example 8 : Bitwise AND , Assignment Operator (&=) ...139
12 Example 9 : Bitwise OR , Assignment Operator (|=) …..139
13 Example 10: Bitwise XOR , Assignment Operator (^=) ….140
14 Example 11: Bitwise Right Shift , Assignment Operator (>>=) …..140
15 Example 12: Assignment as Expression ………………… 141
3 Comparison (Relational) Operators …………………………… 144
1 Comparison (Relational) Operators …………………..….. 144
2 Types of Comparison Operators ………………………….… 144
3 Example 1 : Equal to (==) ………………………………………. 145
4 Example 2 : Not equal to (!=) ………………………………… 147
5 Example 3 : Greater than (>) …………………………….…… 148
6 Example 4 : Less than (<) …………………………………….… 149
7 Example 5 : Greater than or equal to (>=) ……………… 150
8 Example 6 : Less than or equal to (<=) …………………… 151
4 Logical Operators …………………………………………………….… 152
1 Types of Logical or Boolean Operators …………..……… 153
2 Logical AND Operator ……………………………………….…… 153
3 Example 1 : Logical AND Operator ……………..……….… 153
4 Example 2 : Logical AND Operator ………………………… 155
5 Example 3 : Logical AND Operator ………………………… 156
6 Logical OR Operator ……………………………………………… 158
7 Example 1 : Logical OR Operator …………………………… 159
8 Example 2 : Logical OR Operator …………………………… 159
9 Logical NOT Operator …………………………………….……… 161
10 Example 1 : Logical NOT Operator …………………..…… 161
11 Example 2 : Logical NOT Operator ……………………..… 161
5 Bitwise Operators ……………………………………………………… 162
1 Types of Bitwise Operators …………………………………… 163
2 Bitwise AND operator (&) ………………………………..…… 164
3 Example 1 : Bitwise AND operator (&) ……..…………… 165
4 Bitwise OR operator (|) ………………………………………… 166
5 Example 1 : Bitwise OR operator (|) ……………………… 169
6 Bitwise XOR operator (^) …………………………………….… 170
7 Example 1 : Bitwise XOR operator (^) ……….…………… 171
8 Bitwise NOT operator (~) …………………………………….… 171
9 Example 1 : Bitwise NOT operator (~) ………….………… 171
10 Bitwise Left Shift Operator (<<) ………………………….… 171
11 Example 1 : Bitwise Left Shift Operator (<<) …….…… 172
12 Bitwise Right Shift Operator (>>) ………………….……… 172
13 Example 1 : Bitwise Right Shift Operator (>>) ……… 175
Chapter 4 : Conditional Statements in Python ( Control Flow )177
1 Conditional Statements ……………………………………….… 178
1 Sequential Control Flow Statements …………….……… 179
2 Example 1 : Sequential Control Flow Statements …..180
3 Conditional Statements in Python ………………………… 180
4 Example 1 : Conditional Statements in Python ……… 181
5 Loop Control Flow Statements ……………………………… 183
6 Example 1 : Loop Control Flow Statements ……..…… 184
2 If Statement ……………………………………………………………… 186
1 If Statement …………………………………………………….…… 187
2 Example 1 : Calculating area of a circle ……………….… 189
2 Example 2 : Checking number is divisible or not .….. 190
3 Example 3 : Displaying message ………………………….… 191
4 Example 4 : Calculating percentage of marks ………… 192
5 Example 5 : To check even or odd …………………………. 193
6 Use of Logical Operators in If Statement ………………. 194
7 Example 1 : Use of logical AND (and) operator ……… 196
8 Example 2 : Use of logical OR (or) operator …………… 197
9 Example 3 : Use of logical NOT (not) operator ………. 197
3 If-else Statement ……………………………………………………… 198
1 If-else Statement …………………………………………………. 199
2 Example 1 : If-else Statement ………………………………. 203
3 Example 2 : If-else Statement ………………………………. 203
4 Example 3 : Checking a number is even or odd …….. 204
5 Example 4 : Calculating the percentage ………………… 205
6 Example 5 : Checking number is divisible or not …… 206
7 Example 6 : Checking number is Buzz number ……… 206
8 Example 7 : Checking greater than ……………………….. 207
9 Example 8 : Checking greater than ……………………….. 207
4 If-elif-else Statement ………………………………………………… 209
1 Example 1 : Checking the number ………………………… 213
2 Example 2 : Checking number is greater ………………. 214
3 Example 3 : Checking greatest among three numbers .215
4 Example 4 : Checking user ……………………………………. 216
5 Example 5 : Checking vowel or consonant ……………. 217
6 Example 6 : Checking the shape …………………………… 218
7 Example 7 : Checking numbers …………………………….. 219
8 Example 8 : Calculating percentage ……………………… 221

5 Nested If-else Statement …………………………………………. 223


1 Example 1 : Nested If-else Statement ………………….. 224
2 Example 2 : Nested If-else Statement ………………….. 225
3 Example 3 : Nested If-else Statement ………………….. 226
4 Example 4 : Checking number is divisible or not ….. 227
5 Example 5 : Checking numbers ……………………………. 228
6 Example 6 : Checking leap year ……………………………. 230
7 Nested If-elif-else Statement in Python ……………….. 235
8 Example 1 : Checking numbers ……………………………. 236
6 Loops ……………………………………………………………………….. 238
1 Loops ………………………………………………………………….. 238
2 Loop Control Structure in Python ……………………….. 239
3 Steps to Process Loops in Python ……………………….. 240
2 Types of Loops (Iterations) in Python …………………. 240
7 While Loop ……………………………………………………………… 242
1 While Loop …………………………………………………………. 243
2 While Loop working Flow in Python ……………………. 244
3 Example 1 : Printing the first 5 natural numbers …. 247
4 Example 2 : Printing your name ………………………….. 248
5 Example 3 : Display numbers ………………………………. 248
6 Example 4 : Calculating the average of n natural … 249
7 Example 5 : Calculating the sum …………………………. 251
8 Example 6 : Finding the sum of digits …………………. 252
9 Example 7 : Calculating the numbers …………………. 253
10 Example 8 : Finding Fibonacci series of numbers … 255
11 Example 9 : Displaying the pattern ……………………… 256
12 Example 10: Displaying the pattern ……………………. 257
13 Example 11: Displaying the mathematical table …. 258
8 For Loop …………………………………………………………………… 259
1 For Loop ……………………………………………………………… 259
2 For loop Working Flow in Python ………………………… 260
3 Example 1 : For Loop …………………………………………… 261
4 Example 2 : For Loop …………………………………………… 262
5 For Loop with range() Function in Python ……………. 263
6 Example 1 : For Loop with range() Function ………… 264
7 Example 2 : Calculating the sum of numbers ………. 265
8 For loop with String in Python …………………………….. 266
9 Example 1 : Iterate over each character ……………… 267
10 Example 2 : Iterate over list ………………………………. 268
11 Example 3 : Iterate over tuple …………………………… 269
12 Example 4 : Else block with for loop ………………….. 270
13 Example 5 : Calculating sum even , odd numbers … 271
14 Example 6 : Finding the factorial of a number ……. 272
15 Example 7 : Printing a list of numbers ………………… 273
16 Example 8 : Printing a list of numbers ………………… 273
9 Nested Loops …………………………………………………………… 274
1 Nested Loops ………………………………………………………. 275
2 Example 1 : Nested Loops ……………………………………. 276
3 Example 2 : Nested While loops ………………………….. 277
4 Example 3 : Printing multiplication tables ……………. 281
5 Example 4 : Displaying a triangle …………………………. 282
6 Example 5 : Displaying triangle of numbers …………. 283
7 Example 6 : Displaying right triangle pattern ……….. 284
8 Example 7 : Displaying following number pattern … 285
9 Example 8 : Displaying alphabet pattern ………………. 286
10 Example 9 : Displaying alphabet pattern ……………… 287
11 Example 10: Displaying reverse right triangle ……… 288
10 Infinite Loop …………………………………………………………….. 289
1 Infinite Loop …………………………………………………………. 290

11 Break Statement ……………………………………………………… 291


1 Break Statement ………………………………………………….. 293
2 Use of Break Statement in Python ……………………….. 294
3 Example 1 : Use of Break Statement …………………….. 294
4 Example 2 : Use of Break Statement …………………….. 295
5 Example 3 : Use of Break Statement …………………….. 295
6 Example 4 : Use of Break Statement …………………….. 296
12 Continue Statement …………………………………………………. 297
1 Continue Statement ……………………………………………… 297
2 Use of Break Statement in Python ………………………… 297
3 Example 1 : Use of Break Statement …………………….. 298
4 Example 2 : Use of Break Statement …………………….. 301
3 Example 3 : Use of Break Statement …………………….. 302
4 Example 4 : Use of Break Statement …………………….. 304
4 Example 5 : Use of Break Statement …………………….. 304
4 Difference between Break and Continue in Python . 305
13 Pass Statement …………………………………………………………. 306
1 Pass Statement ……………………………………………………… 307
2 Example 1 : Pass Statement ………………………………….. 308
3 Example 2 : Pass Statement ………………………………….. 308
4 Example 3 : Pass Statement in ‘while loop’ …………… 309
5 Example 4 : Pass Statement in ‘for loop’’ ……………… 309
6 Example 5 : Pass Statement in creating an empty class . 310
14 Switch Statement ……………………………………………………… 312
1 Switch Statement ………………………………………………….. 312
2 Example 1 : Switch Statement ………………………………. 313
3 Implementing Switch Statement using Dictionary … 314
4 Example 1 : Switch Statement using Dictionary …….. 314
5 Example 2 : Switch Statement using Dictionary …….. 316
6 Example 3 : Switch Statement using Python Class …. 317
Chapter 5 : Functions ………………………………………………………… 319
1 Functions in Python Types ………………………………………. 320
1 Why do we need to use functions in Python …………. 321
2 Components of Python Functions …………………………. 323
3 Rules for defining User defined Function in Python . 326
4 Types of Functions in Python ………………………………… 326
5 Built-in Functions in Python ………………………………….. 327
6 Example 1 : abs(value) ………………………………………….. 327
7 Example 2 : bin(n) …………………………………………………. 328
8 Example 3 : float(n) ………………………………………………. 328
9 Example 4 : int(n) ………………………………………………… 329
10 Example 5 : sqrt(x) ……………………………………………… 329
11 Example 6 : pow(x, y) …………………………………………. 330
12 Example 7 : factorial(x) ………………………………………. 330
13 Example 8 : len(iterable) ……………………………………. 331
14 Example 9 : print(object) ……………………………………. 331
15 Example 10: input(prompt) ………………………………… 332
16 Example 11: max(iterable) …………………………………. 332
17 Example 12: min(iterable) ………………………………….. 333
18 Example 13: range(stop) or range(start, stop) ……. 333
19 Example 14: round(f, n) ……………………………………… 334
20 Example 15: log10(x) ………………………………………….. 334
2 User defined Function in Python ……………………………… 335
1 Example 1 : User defined Function ………………………. 335
2 Example 2 : User defined Function ………………………. 335
3 Example 3 : User defined Function ………………………. 336
4 Example 4 : User defined Function ………………………. 337
3 Calling a Function in Python …………………………………….. 339
1 Execution Style of Calling a Function in Python ……. 339
2 Example 1 : Execution Style of Calling a Function … 339
3 Example 2 : Execution Style of Calling a Function … 340
4 Calling a Function from another Function ……………. 342
5 Example 1 : Calling a Function from another Function 342
6 Example 2 : Calculating area of the rectangle ……….. 344
7 Example 3 : Calculating addition, subtraction ……….. 346
8 Example 4 : Calculating the square of a number ……. 347
9 Example 5 : Swapping two numbers ……………………… 348
10 Example 6 : Checking number is even or odd ………. 349
11 Example 7 : Testing whether a year is leap ………….. 350
12 Example 8 : Checking a number is prime or not …… 351
13 Example 9 : Square of numbers between 1 to 10 … 353
14 Example 10: Find and print the total marks …………. 354
4 Function Arguments in Python Types ……………………….. 355
1 Function Arguments in Python ……………………………… 355
2 Example 1 : Function arguments , parameters ………. 356
3 Types of Function Arguments in Python ……………….. 358
4 Default Arguments in Python ……………………………….. 358
5 Example 1 : Default Arguments …………………………….. 359
6 Example 2 : Default Arguments …………………………….. 360
7 Required Arguments in Python …………………………….. 361
8 Example 1 : Required Arguments …………………………. 362
9 Example 2 : Required Arguments …………………………. 362
10 Keyword Arguments in Python ……………………………. 363
11 Example 1 : Keyword Arguments ………………………… 364
12 Example 2 : Keyword Arguments ………………………… 365
13 Variable length Arguments …………………………………. 367
14 Example 1 : Variable length Arguments ……………… 368
15 Example 2 : Variable length Arguments ……………… 369
5 Pass by Value in Python Pass by Reference ……………… 370
1 Function Arguments in Python …………………………….. 370
2 Call/Pass by Value in Python ………………………………… 371
3 Call/Pass by Reference in Python …………………………. 371
4 Key Points about Pass by Object Reference …………. 372
5 Example 1 : Pass mutable objects (list) to the function 373
6 Example 2 : Pass immutable objects (string) ………… 375
7 Example 3 : Pass mutable objects (List) to function 377
8 Example 4 : Pass mutable objects (List) to function 379
6 Return in Python Return Statement …………………………. 380
1 Key Points of Python Return Statement ……………….. 380
2 Example 1 : Return Statement ……………………………… 381
3 Example 2 : Return Statement …………………………….. 383
4 Example 3 : Return the sum of two numbers ………. 384
5 Example 4 : Cube of a number …………………………….. 386
6 Example 5 : Compute area , circumference of circle … 388
7 Example 6 : Compute area , circumference of circle … 389
8 Python Function Return Multiple Values ……………… 390
9 Example 1 : Return Multiple Values …………………….. 390
10 Example 2 : Return Multiple Values ……………………. 391
7 Void Function in Python …………………………………………… 393
1 Example 1 : Calculate the sum of two numbers …… 395
2 Example 2 : Find even and odd numbers ……………… 396
3 Example 3 : Check whether it is a palindrome ……… 397
4 Example 4 : Check whether number perfect number 398
5 Example 5 : Calculate the total marks, percentage 399
8 Scope in Python Variable Scope, Lifetime ………………… 400
1 Example 1 : Variable Scope ………………………………….. 401
2 Types of Scope of Variables …………………………………. 402
3 Global Scope ……………………………………………………….. 403
4 Example 1 : Global Scope …………………………………….. 404
3 Local Scope ………………………………………………………….. 405
4 Example 1 : Local Scope ……………………………………….. 406
5 Example 2 : Local Scope ……………………………………….. 407
9 Global in Python Global Keyword …………………………….. 409
1 Example 1 : Global Keyword …………………………………. 410
2 Rules used for Global Keyword in Python ……………… 411
3 Example 1 : Access a global variable ……………………… 412
4 Example 2 : Modify the global variable …………………. 412
5 Example 3 : Using global statement ……………………… 413
6 Local Variable having same name as Global Variable … 414
7 Example 1 : Local Variable having the same name … 414
8 Example 2 : Local Variable having the same name … 415
9 Example 3 : Global in Nested Functions ………………… 417
Chapter 6 : Strings in Python ……………………………………………. 418
1 Mutable and Immutable in Python ………………………… 419
1 Mutable and Immutable Object’s Value in Python … 421
2 Mutable Data type in Python ………………………………… 422
3 Example 1 : List of a mutable data type in Python … 423
4 Example 2 : Changing the value of a list ……………..… 425
5 Example 3 : Concatenating a new list into old list …. 426
6 Example 4 : Set of a mutable data type in Python … 427
7 Immutable Data types in Python …………………………… 428
8 Example 1 : Immutable Data types ……………………….. 429
2 Strings in Python Accessing ……………………………………….. 431
1 Accessing String Characters in Python …………………… 432
2 Example 1 : Access the characters of a string ………… 433
3 Example 2 : Access the characters of a string ………… 435
4 Strings are immutable objects in Python ………………. 436
5 Example 1 : Strings are immutable objects …………… 437
3 Python String Length len() Function …………………………. 438
1 Example 1 : Find the length of a string …………………. 438
2 Example 2 : Find the number of characters ………….. 439
3 Example 3 : Find Length of List, Tuple, Set, Directory 439
4 String Concatenation in Python ……………………………….. 441
1 Example 1 : String Concatenation ………………………… 442
2 Ways to Concatenate Strings in Python ……………….. 443
3 Example 1 : Adding multiple strings together ………. 343
4 Example 2 : Adding multiple strings together ………. 344
5 Example 3 : Concatenating integer number with string 446
6 Example 4 : Concatenating integer type with string ….. 447
7 Example 5 : Using multiplication operator (*) ………. 447
8 Example 6 : Using multiplication operator (*) ……… 448
9 String Concatenation using join() Method …………… 449
10 Example 1 : String Concatenation join() Method … 450
11 Example 2 : String Concatenation join() Method … 451
12 Example 3 : Concatenating integer number ……….. 451
13 Joining Strings using Formatting Operator (%) ……. 451
14 Example 1 : Joining Strings Formatting Operator (%) 452
15 Concatenating String using format() function …….. 452
16 Example 1 : Concatenating String using format() … 453
17 String Concatenation using f-string …………………….. 453
18 Example 1 : String Concatenation using f-string ….. 453
5 String Comparison in Python ……………………………………. 454
1 String Comparison using Relational Operators …….. 454
2 Example 1 : String Comparison Relational Operators 455
3 Example 2 : String Comparison Relational Operators 456
4 Example 3 : String Comparison Relational Operators 456
5 Example 4 : String Comparison Relational Operators 457
6 Comparing String using Identity Operators …………. 458
7 Example 1 : Comparing String Identity Operators … 459
8 Example 2 : Comparing String Identity Operators … 459
9 Example 3 : Comparing String Identity Operators … 460
10 Comparing String User-defined Function …………….. 461
11 Example 1 : Comparing String User-defined Function 461
6 String Slicing in Python ……………………………………………… 462
1 Example 1 : String Slicing in Python ………………………. 462
2 String Slicing by slice() Function ……………………………. 464
3 slice() function ……………………………………………………… 464
4 Example 1 : slice() function …………………………………… 465
5 String Slicing using slice operator …………………………. 467
6 Example 1 : String Slicing using slice operator ………. 468
7 Iterate over a String in Python ………………………………….. 472
1 Example 1 : Iterate a string using for loop …………….. 472
2 Example 2 : Iterate a string using for loop …………….. 474
3 Example 3 : Iterate a string using while loop …………. 475
4 Example 4 : Traversing string , enumerate() ………….. 476
5 Example 5 : Traversing string , enumerate() ………….. 476
6 Iterating over Words in a String in Python …………….. 478
7 Example 1 : Iterate string , split() function …………….. 478
8 Example 2 : Iterate string , re.findall() function ……… 480
8 String Formatting in Python ……………………………………… 481
1 String Formatting with % Operator ………………………. 482
2 Example 1 : Use of %s operator ……………………………. 483
3 Example 2 : Use of %s operator ……………………………. 483
4 Example 3 : Usage of %i and %d …………………………… 484
5 Example 4 : Usage of %f or %F ……………………………… 485
6 Example 5 : Usage of %x and %o ………………………….. 485
7 String Formatting using format() Method …………….. 486
8 Example 1 : String Formatting format() Method …… 486
9 Example 2 : String Formatting format() Method …… 487
10 Example 3 : String Formatting format() Method …… 487
11 Example 4 : String Formatting format() Method …… 488
12 Example 5 : String Formatting format() Method …… 489
13 Formatting String Literals using f-strings ……………… 490
14 Example 1 : String formatting using f-strings ……….. 491
15 Example 2 : String formatting using f-strings ……….. 491
16 Example 3 : Arithmetic operations f-strings …………. 492

Introduction
Learning Python Programming step by step.
Python is a powerful language.It is also the easiest language to learn.Python has found preference in a variety of technology fields like Machine Learning,Deep Learning, and Data Science.With the rate at which
Python is finding preference among many technological fields, it's the best time to learn the language.
We want to make it easy to start that journey, no matter what your skills and knowledge arenite does not matter if you know nothing about programming as a whole.
Each chapter of this book builds on the previous chapters in an easy to understand step-by-step process.You will learn theory and also practice what you learn.

Chapter 1 :
Introduction

Here, you will learn all the fundamental concepts of Python step by step.
And at last, you will be comfortable in creating projects in Python.
If you are a beginner to learn Python, In this book you will learn easily.
In each Python topic, you will get programming exercises to test your understanding.
Even if you have no prior knowledge of any programming language, you won’t face any difficulty understanding these topics.

1 What is Python
Python is a simple, general purpose, dynamic, high level, interactive, interpreted, and object-oriented programming language. It is one of the most popular computer programming languages in the world.

2 Important Terms You Should Know with Python


Please see some important terms that can make the Python easier to understand. They are:

1. Python is a general-purpose language, which means we can use it for building a wide variety of application softwares across a multitude of hardware configurations and operating systems.
A general purpose language is a programming language that is the ability to build all kinds of programs. For example, Python is a good example of a general-purpose programming language.

2. Python is a high-level language, which means it enables the programmer to write programs that are not specific to a particular type of computer or designed for a specific task.
A high-level language is easier to understand. It is closer to human language and far to machine language. Some examples of high-level languages are BASIC, C, C++, COBOL, FORTRAN, Java, Pascal, Perl,
PHP, Python, Ruby, and Visual Basic.

3. Python is a dynamically typed language. This means that the Python interpreter does type checking of variable at the runtime. Interpreter assigns the type of variable based on the value of variable at the
runtime.

4. Python is really interactive. This means that we can write the program directly on the Python prompt and interact with the interpreter to generate immediate output.

5. Python is both compiled and interpreted language. Python is an interpreted language because interpreter converts codes into machine-readable byte codes before it can execute them.
It is also a compiled language because bytecode compiler automatically compiles the codes into byte code (to .pyc) when modules imported. But, we can also compile codes explicitly.

6. Python is an object-oriented programming language. This means that it emphasizes the use of objects over functions, in contrast with procedure-oriented languages.
Everything is done through classes and objects. It supports user-defined classes and objects, constructors, encapsulation, inheritance, multiple inheritance, abstraction, polymorphism as well as methods binding at
runtime.

3 Why learn Python


There are many high-level programming languages available, such as C, C++, and Java. All high-level programming languages are very similar to one another.
What differs is mainly its syntax, libraries available and the mode we access those libraries.
A library is simply a collection of resources and pre-written codes we use when we write our programs.

Here are some important reasons that why Python’s so useful.


1. Easy to Read, Write, and Understand
Unlike some other programming languages, Python is a text-based computer programming language. It doesn’t use complicated symbols.
We write the code using a mixture of English words, characters, symbols, and numbers. This makes Python code easy to read, write, and understand – just like a book.
2. Works Everywhere
Python is portable. It means we can write and run Python code on lots of different computers. The same Python code will work on PCs having different operating systems such as Windows, Macs, Linux
machines, and Raspberry Pi, etc.

3. Packed with Handy tools


Python comes with lots of useful tools and pre-written code that we can use in writing our programs right away. The pre-written code is called Standard Library.
4. Python is Free and Open Source
Python is free and open source. This makes Python popular and successful. We can install it on our computer and never need to pay a penny.
5. Python Is Object-Oriented language
Object-oriented programming (OOP) is a modern programming approach to design a computer program using classes and objects. Like C++, C#, and Java, Python is also an object-oriented programming
language.
6. Python is a “Integrated” Language
We can integrate Python with other languages such as C, C++, and Java. It means that we can take benefit of work already done in another language while using Python.
7. Length of code
We require writing fewer lines of code in Python to perform the same task compared to other languages such as C++, Java. From which we get fewer programming errors and also reduces the development time
needed.

4 Java vs Python Program


Unlike the other programming languages such as Java, Python provides the facility to write the fewer lines of code to do the same task.
From which you get fewer programming errors and reduces the development time needed. For example, suppose we want to print the “Hello World” in the Java.
So, we need to write three lines to print it. Let’s write the code for it.
Java Program
public class HelloWorld {
public static void main(String[ ] args)
{
// Prints "Hello, World" to the console.
System.out.println("Hello World");
}
}

Python Program
On the other hand, we can perform the same task this using one statement in Python.
print("Hello World")
As you can see that both programs are printing the same result, but Python takes only one statement without using a semicolon or curly braces.
5 Where can we use Python
Python is a simple and popular high-level general-purpose programming language. We can use it in the almost every technical field.

For example, we can use Python on a server to create web applications, to connect to database systems, and to handle big data and perform complex mathematics.
Various areas of Python use are as below:

Data Science
Date Mining
Desktop Applications
Console-based Applications
Mobile Applications
Software Development
Artificial Intelligence
Web Applications
Enterprise Applications
3D CAD Applications
Machine Learning
Computer Vision or Image Processing Applications.
Speech Recognitions
Video games
Mathematics
Science
Business
Media, etc.

6 Popular Frameworks and Libraries of Python


Python has a wide range of frameworks and libraries widely used in many fields, such as web applications, machine learning, artificial intelligence, gaming, science, etc.
We have defined some popular frameworks and libraries of Python as below.

Web development (Server-side) – Pyramid, Django Flask, CherryPy


GUIs based Applications – Tk, PyGTK, PyQt, PyJs, etc.
Machine Learning – TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
Mathematics – Pabdas, Numpy, etc.

Chapter 2 :
Python Basic

1 Tokens
2 Reserved Keywords
3 Identifiers
4 Literals
5 Delimiters
6 Escape Sequence
7 Variables
8 Built-in Data Types
9 Global and Local Variables
10 Memory Management

1 Tokens
Tokens are the various elements in the Python program that are identified by Python interpreter.
A token is the smallest individual unit, or element in the Python program, which is identified by interpreter. They are building blocks of the source code.
Python language supports the different types of tokens that are as follows:
Keywords (Reserved words) : True, False, None, class, continue, break, if, elif, else, from, or, def, del, import, etc.

Identifier : User-defined names


Literals : String, Numeric, Boolean, Collection,
Delimeters : ( ), { }, [ ], :, ., =, ;, +=, -=, *=, /=, %=, etc.
Operators : +, -, *, **, /, %, <<, >>, etc.
The following diagram shows you different tokens used in Python.

Python interpreter scans written text in the program source code and converts it into tokens during the conversion of source code into machine code.

How to Identify Tokens in Python Program


Example 1 :

# Python program to find the subtraction of two numbers.


x = int(input("Enter your first number = "))
y = int(input("Enter your second number = "))
sub = x - y
print("Result = ", sub)

Output

Enter your first number = 30


Enter your second number = 20
Result = 10

Explained in Detail
Let us consider the first statement, which consists of nine tokens that are as follows:

x
=
int
(
input
(
“Enter your first number = “
)
)

The second statement in the above code contains the following tokens that are as:

y
=
int
(
input
(
“Enter your second number = “
)
)
Tokens in the third statement in the above code is as:

sub
=
x

y
Note that the Python interpreter ignores # comment symbol and text follows it. Interpreter uses the tokens to detect errors, mainly syntax errors.

Character Set Used in Python


The character set included in Python comprises the following characters:
1. Alphabet: It includes the uppercase and lowercase alphabet
letters of English, i.e., {A, B, C, D, E, . . . . } and {a, b, c, d, e, f, .
. . . }.
2. Digits: It includes the numeric digits, i.e., {0, 1, 2, . . . . 9}.
3. White Spaces: It includes spaces, enters, and tabs.
4. Special Characters: It includes the special symbols, such as
{, !, ?, #, <, >, (, ), %, “, &, ^, *, <<, >>, [, ], +, =, /, -, , _, :, ;, }.

2 Reserved Keywords
Keywords in Python are unique reserved words that Python reserves for defining the syntax and structure of Python language.
We can’t use these keywords as an ordinary identifier in a Python program while naming variables, functions, objects, classes, and similar items.

List of Reserved Keyword in Python Language


To retrieve the keywords in Python, write the following code at the prompt. All keywords except True, False, and None are in the lowercase letter.

import keyword
print(keyword.kwlist)

['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']

Table: Python Keywords

Description of Keywords in Python with Examples


a) True and False
True: This keyword represents a true boolean value. If a statement is true, Python interpreter returns a “True” value.
Example 1 :

print( 5 == 5 )
print( 10 > 9 )
print( True or False )
print( 9 <= 28 )

Output

True
True
True
True

Explained in Detail
Since all statements in the above code are true, the interpreter returns True value. In Python, the boolean value “True” is equivalent to 1.

Consider the following code to understand this statement.


Example 2 :

print( True == 1 )
print( True + True + True)
Output

True
3

False: This keyword represents a false boolean value. If a statement is false, interpreter returns “False” value.
Example 1 :

print(10 > 20)


print(50 <= 30)
print(False == 1)
print(False == 0)
print(False + False + 1)

Output

False
False
False
True
1

Explained in Detail
Since the first, second, and third statements are false, interpreter returns “False” boolean value.
While the fourth statement is true, the result of comparison is “True” value.
In Python, False is equivalent to 0 value, the last statement is 1 because 0 + 0 + 1 = 1.

Note : that both “True” and “False” boolean values are the results of comparison operations or logical (Boolean) operations in Python.

None Keyword
This is a special constant in Python used to represent a null value or void (that means nothing). It has own data type. We consider “None” as nil, null, or undefined in different programming languages.

None is not equivalent to False, 0, or empty string, etc. If we compare “None” to anything other than “None” will always return False.
Example 1 :

print(None == False)
print( None == 0 )
print( None == " " )

Output

False
False
False

Python Operator Keywords – and, or, not, in, is


a) and: It is a logical operator in Python that returns True value only if both operands on left-hand and right-hand sides are true.
The truth table for and operator is as follows:

Example 1 :

print(True and True)


print(True and False and True)
print(True and 1)

Output

True
False
1

b) or: It is a logical operator in Python that returns “True” value if any of the operands are True.
The truth table for or operator is as follows:
Example 1 :

print(True or True)
print(False or False or True)
print(True or False)
print(True or 1)

Output

True
True
True
True

c) not: This is a logical operator that inverts the truth value. The truth table for not operator is as follows:

Example 1 :

print(not True)
print(not False)

Output

False
True

d) in: This is an operator used to check if a value exists in a sequence or not. It evaluates True if the value is present in the sequence otherwise; it returns False.
Example 1 :

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


print(50 in num)
print(15 in num)

Output

True
False

Another use of in keyword is to traverse over a sequence in a for loop.


Example 2 :

for i in 'keyword':
print(i)

Output

k
e
y
w
o
r
d

e) is: This keyword is an operator used to test object identity. It returns True if both objects point to the same memory location, i.e. if two variables point to the same object.

If both objects are not the same, it returns False.


Example 1 :

print( True is True )


print( False is True )
print( None is None )
print((2 + 4) is (3 * 2))

Output

True
False
True
True
Python Iteration Keywords – for, while, break, continue
a) for: We use this keyword for looping. Generally, we use “for loop” in the program when we know exactly how many times we want to run a block of code.
Example 1 :

for count in range(1, 4):


print("abd, Dhanbad")

Output

abd, Dhanbad
abd, Dhanbad
abd, Dhanbad

b) while: We use while keyword for looping in Python. A statement or group of statements inside a while loop continue to execute until the test condition for the while loop evaluates to False or encounters
a break statement.
Example 1 :
count = 0
while(count < 3):
print("The current count is: ", count)
count = count + 1
print("While loop ended!")

Output

The current count is: 0


The current count is: 1
The current count is: 2
While loop ended!

c) break: The break keyword in Python is used to end the loop statement and transfer the control of execution to the statement following immediately after the end of loop.
Example 1 :

for i in range(1, 5):


if i == 3:
break
print(i)

Output

1
2

d) continue: This is another useful keyword for loops in Python. When we use continue keyword, the rest of the loop after the keyword is skipped for that iteration and immediately re-evaluates its
condition prior to reiterating the loop.
Example 1 :

for i in range(1, 6):


if i == 4:
continue
print(i)

Output

1
2
3
5

Python Conditional keywords – if, else, and elif


We use if, else, and elif keywords for conditional branching or decision making in Python.
When we want to evaluate a certain test condition and execute a block of code only if the condition is true, then we use if and elif. elif is the abbreviation of “else if”.
else is the block that executes if the condition is false.
Example 1 :

i = 10
if (i == 5):
print ("Hello")
elif (i == 10):
print ("Python keywords")
else:
print ("Hello Python")

Output
Python keywords

def keyword
We use def keyword for declaring a user-defined function in Python. A user-defined function is a block of code that performs together some specific tasks.
Example 1 :

# Declaring a user-defined function.


def func():
print("Inside Function")
func()

Output
Inside Function

Python Return Keywords – Return, and Yield


a) return: We use the return keyword inside a user-defined function to exit it and return a value. If we do not return a value explicitly, the interpreter automatically returns None by default.
Example 1 :

# Declaring user-defined functions with return keyword.


def func_return():
x = 20
return x

def func_no_return():
y = 50
print(func_return())
print(func_no_return())

Output

20
None

b) yield: We use yield keyword inside a function like a return statement but yield returns a generator object to the caller rather than a data value.
Example 1 :

# Yield Keyword
def func():
x=0
for i in range(5):
x += i
yield x
for i in func():
print(i)

Output

0
1
3
6
10

class Keyword
We use class keyword to declare a user-defined class in Python. In any programming language, a class is a collection of as many as objects.
A class is basically a user-defined data type that consists of data members, functions, etc. According to OOPs, a class is a template of an object that provides state and behaviour for an object.
We can define a class anywhere in a Python program. But it is a good practice to declare a single class in a module.

class ClassExample:
def func1(parameters):
....
def func2(parameters):
....

import Keyword
The import keyword is used to import all attributes of a module in the current program.

import math
print(math.sqrt(25))

Output
5.0

from Keyword
Generally, we use from keyword with the import statement to include only a specific attribute from the module.
Example 1 :

from math import sqrt


print(sqrt(625))
Output
25.0

del Keyword
Everything is an object in the real world of Python. We use del keyword to delete a reference to an object. We can delete any variable or list value from memory location using del keyword. Example 1 :

my_var1 = 200
my_var2 = "abd"

# check if my_var1 and my_var2 exists.


print(my_var1)
print(my_var2)
# delete both the variables.
del my_var1
del my_var2

# check if my_var1 and my_var2 exists


print(my_var1)
print(my_var2)

Output

200
abd
NameError: name 'my_var1' is not defined

global Keyword
In Python, global keyword allows the programmer to declare a global variable outside the function globally. A variable defined outside the function or in global scope is called global variable.
It is necessary to write the global keyword to use global variable inside the function. But, there is no need to use global keyword outside the function.
Example 1 :

g_var = 50
def func_read():
print(g_var)
def func_write():
global g_var
g_var = 100

func_read()
func_write()
func_read()

Output

50
100

Explained in Detail
In this example, the func_read() function is just reading the value of g_var variable. Therefore, we do not need to declare it as global.
But the func_write() function is modifying the value of the variable, so we need to declare the variable with a global keyword. You can observe in the output that the modification took place (50 is changed to
100).

nonlocal Keyword
The nonlocal keyword functions similarly to the global keyword. Generally, we use nonlocal keyword to declare a variable inside a nested function (function inside a function) which is not local to it.
It means that the scope lies in the outer inclosing function. To modify the value of a nonlocal variable inside a nested function, we must declare it with a nonlocal keyword.
Else, a local variable with that name will define inside the nested function.
Example 1 :

def outer_func():
x = 50
def inner_func():
nonlocal x
x = 100
print("Inner function: ",x)
inner_func()
print("Outer function: ",x)

outer_func()

Output

Inner function: 100


Outer function: 100

Explained in Detail
In this example, the inner_func() is nested inside the outer_func(). The variable x is in the outer_func(). So, if we modify it in the inner_func(), we must declare it as nonlocal. Note that here, x is not a global
variable.
You can observe in the output that we have successfully modified the value of variable inside the nested inner_func() function.

The outcome of not using the nonlocal keyword is as:


Example 1 :
def outer_func():
x = 50
def inner_func():
x = 100
print("Inner function: ",x)
inner_func()
print("Outer function: ",x)

outer_func()

Output

Inner function: 100


Outer function: 50

Python Exception Handling Keywords – try, except, raise, and finally


Python allows to programmer to handle exception or errors in the code using try-except keywords. We place the code inside the try block.
If there is an error inside try block, except block is executed. The except block executes when an exception occurs inside the try block.
The finally block always gets executed whether or not an exception occurs inside the try block. We can raise an exception explicitly with the raise keyword in Python.
Example 1 :

# initializing the value of variables.


x = 10
y=0
# No exception raised in try block
try:
z = x // y # raises divide by zero exception.
print(z)
# handles zero division exception
except ZeroDivisionError:
print("Cannot divide by zero")

finally:
# this block always gets executed regardless of exception produced.
print('finally block always gets executed')

Output

Cannot divide by zero


finally block always gets executed

assert Keyword
In Python, we use assert keyword for debugging purpose. Sometimes, we need to debug the internal state of some assumptions.
In this case, assert keyword helps us to find bugs more conveniently. assert is followed by a condition. If the condition evaluates to true, nothing happens.
But if the condition evaluates to false, AssertionError is raised.
Example 1 :

x = 10
assert x >= 10
assert x < 10

Output

Traceback (most recent call last):


File "string", line 3, in
assert x < 10
AssertionError

We can also pass an error message with assert to be displayed with AssertionError.
Example 1 :

x = 10
assert x < 10, "x is not less than 10"

Output

Traceback (most recent call last):


File "string", line 2, in
assert x < 10, "x is not less than 10"
AssertionError: x is not less than 10

3 Identifiers
An identifier in Python is the user-defined name given to identify a variable, function, class, string, list, dictionary, module, or another object.
It helps to differentiate one entity (or object) from another.
In Python programming language, an identifier starts with an alphabetic uppercase letter (A to Z) or lowercase letter (a to z) or an underscore (_) followed by zero or more letters, underscores and
digits (0 to 9).
Python does not allow us to use special characters, such as @, $, /, and % within identifiers.
Five Rules for writing Identifiers in Python
There are following rules for writing identifiers in Python programming language that should keep in mind. They are:
1. Identifiers can be a combination of alphabetic letters in uppercase (A to Z) or lowercase (a to z), or digits (0 to 9) or an underscore (_). Here are some valid identifier examples in Python.

C
c
myClass
my_variable,
my_var1
UPPERCASE
lowercase
CollegeName
schoolName
UPPERCASE_WITH_UNDERSCORES
lowercase_with_underscores
max_marks

2. An identifier cannot start with a numeric digit. For example, 1person is invalid, but person1 is a valid name.
3. We cannot use keywords as identifiers.
4. Identifier may not include special symbols like !, @, #, $, % etc.
5. An Identifier can be of any length in Python.

4 Literals
A literal in Python is a way to represent a fixed value or raw data in the source code. It directly appears in the program and does not change during the execution of a program.
Literals can be either numbers, text, boolean, or any other form of data.
In Python program, we use literals to create fixed values that are assigned to variables, constants, used in expressions, or passed to functions.
Example 1 :
Suppose we want to setting a variable with a specific value in a Python program.
x = 10

Explained in Detail
This statement creates an integer object containing a literal value 10. Literal means simply a value.

Types of Literals in Python Language


Literals can be any of the primitive data types in Python language. The way of using literals depends on its type. The various types of literals used in the Python program are as follows:

String literals
Numeric literals
Boolean literals
Literal Collections
Special Literals
Let’s look at the following diagrammatic representation of the classification of Python literals.
String Literals
A string literal in Python is a consecutive sequence of characters used to store and represent messages, heading, and other text-based information.
It is enclosed within a pair of double quotation marks and single quotation marks. Both are applicable to define the string literals.
“Hello”, ‘World’, “123”, ‘The area of rectangle is: ‘, etc are some examples of string literals. We use quotation marks to start and end the string.
Strings in Python are immutable, meaning that when we perform an operation on strings, the Python interpreter always creates a new string object in the memory, rather than mutating an existing string object.

Types of Strings
Python language supports two types of string objects.
1) Single-line String: A string created in a single line is called single-line string. An example of a single-line string object is as below:
single_line_string = ‘abd # Here, literal is abd.

2) Multi-line String: A piece of statement written in multiple lines is called multiple lines string. In Python, there are two ways to create multi-line string objects.
a) Adding a black slash (\) at the end of each line.
Example 1 :

multi_line_string = 'Welcome \
to \
Python'
print(multi_line_string)

Output
Welcome to Python

b) We can also create a multi-line string literal using triple quotation marks.
Example 1 :
multi_line_string = '''Welcome \
to \
Python, \
Dhanbad'''
print(multi_line_string)

Output
Welcome to Python, Dhanbad
Numeric literals
Numeric literals in Python consists of numbers or digits from 0 to 9. They may be preceded by a positive (+) or negative (-) sign.
All numeric literals in Python are immutable (unchangeable) objects, meaning that when we perform an operation on a number object, the Python interpreter always creates a new number object.
Operation performed on numbers are called arithmetic operations.We can classify numeric literals in Python into three types that are as follows:

Integer literals
Floating point literals
Complex literals

Boolean literals
A boolean literal is a logical value that can have any of the two values: True or False. True represents the value 1 whereas False represents the value 0.
We use boolean literal in certain operations in which need a boolean value. We use boolean value to test whether a condition is true or false.
Example 1 :

# boolean literals
a = (9 == 9)
b = (5 == False)
c = True + 5
d = False + 5

print("a is ", a)
print("b is ", b)
print("c is ", c)
print("d is ", d)

Output

a is True
b is False
c is 6
d is 5

Special literals
Python language contains only one special literal, i.e., None. It is a special constant in Python that specifies the null value or the absence of a value. We use None to specify a field that is not constructed. We also
use None at the end of lists in Python.
Example 1 :

# Special literals
a = None
print(a)

Output
None
Collection literals
A collection literal is a syntactic representation that is used to work with more than one value. Python language provides the four types of collection literal tokens, such as List, Tuple, Dictionary, and Set.

List literals
A list is a collection of mutable data or values of different types. To create a list in Python, place data or values in within square brackets ([ ]) and separating them by commas (,).
You can consider the Python lists similar to arrays in C, C++, or Java.
<name of list> = [ <value1>, <value2>, <value3>, . . . . ]

Example 1 :

# List literals
address = ['Python, 'Joraphatak Road', 'Dhanbad']
print(address)

Output
['Python', 'Joraphatak Road', 'Dhanbad']

Example 1 :
Printing 10 natural numbers and print the numbers in a list called num.

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


print(num)

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

Dictionary Literals
Python dictionary is a collection of data that stores value in a key-value pairs. They are enclosed in curly braces ({ }) and separated by the commas (,).
Dictionary literals in Python are mutable (changeable) and can also contain different types of data or values.

Example 1 :

# Dictionary literals
fruits_dict = {'a': 'apple',
'o': 'orange',
'b': 'banana'}
print(fruits_dict)

Output
{'a': 'apple', 'o': 'orange', 'b': 'banana'}

Tuple Literals
Tuple in Python is a collection of different data-type, similar to a list. It is immutable, which means we cannot change it after creation. It performs the same operation as a list does.
The parentheses ( ( ) ) enclose it and the comma separates each element of tuples.
Example 1 :

# tuple literals
even_numbers = (2, 4, 6, 8, 10, 12)
vowels = ('a','e','i','o','u')
direction = ('North', 'South', 'East', 'West')

print(even_numbers)
print(vowels)
print(direction)

Output

(2, 4, 6, 8, 10, 12)


('a', 'e', 'i', 'o', 'u')
('North', 'South', 'East', 'West')

Set Literals
Set literals in Python are a well-defined collection of unordered data that cannot be changed. The elements of a set are enclosed within curly brackets separated by commas (,).
Example 1 :

# Set literals
fruits = {'Apple', 'Mango', 'Banana', 'Orange', 'Grape'}
print(fruits)

Output
{'Orange', 'Apple', 'Grape', 'Banana', 'Mango'}

5 Delimiters
A delimiter in Python is a sequence of one or more characters that specifies the boundary between various sections in plain text or other data streams.
Python uses symbols and combinations of symbols as delimiters in expressions, literals, tuples, lists, dictionaries, strings, and various parts of a statement.

List of Delimiters in Python Language


A below table shows a list of delimiters with their classification are as:
Example 1 :

# A string literal with a single quote delimiter.


msg = 'Welcome to Python, Dhanbad'

# A list with a square braces delimiter ([ ]).


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

# A tuple with parenthesis delimiter ( () ).


fruits = ('Banana', 'Orange', 'Mango', 'Apple')
# A dictionary with curly braces ({ }) delimiter.
emp_profile = {"Name" : "John",
"Age" : 25,
"Salary" : 50000}

print(msg)
print(num)
print(fruits)
print(emp_profile)

Output

Welcome to Python, Dhanbad


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
('Banana', 'Orange', 'Mango', 'Apple')
{'Name': 'John', 'Age': 25, 'Salary': 50000}

6 Escape Sequence
An escape sequence in Python is a group or sequence of characters that does not represent its own literal meaning when used inside a character or string.
It starts with a single backslash (\) followed by some characters that have some specific tasks to do.
In Python, the backslash (\) is known as escape character. It tells the Python interpreter to interpret the next character(s) in a specific way and ignores its usual meaning.

Python Escape Sequences in Table


Here, we have listed all valid escape sequences used in Python program that are in the below table:
Example 1 :
Program based on the escape sequence \’:

# \': Used for printing the text string with a single quotation mark.
print('Good Morning \'Python\'')

Output
Good Morning 'Python'

Example 2 :
Program based on the escape sequence \t:

# \t: It gives a tab between two words.


print("Welcome to\tPython")

Output
Welcome to Python

7 Variables
Variables in Python are nothing but the reserved memory locations to store values, such as numbers, some text string, objects, or anything.
Basically, a variable is a symbolic name given to a physical location in the computer’s memory and that memory location contains a value or data.
It tells the computer to store some data in the memory location or to retrieve that data from that memory location.
In simple words, whenever we create a variable in the Python program, we are allocating some space in the memory to store data values.

Example 1 :
we are creating an integer variable and assigning a value to it.
num = 20 # an integer variable.

Explained in Detail
Here, num = 20 will store the value 20 in the computer’s memory location named num, as shown in the below figure. We have used an assignment operator (=) to assign a value to the variable.

Memory Location of a Variable in Python


In the above code, 20 is an integer object stored in heap memory and “num” is a reference variable created in the main stack memory, containing the memory address of the integer object and is pointing to this
integer object.
We can retrieve the memory address of integer object by using id() function. Look at the below example code.
Example 1 :

num = 20
print(id(num))

Output
1449404138320

Explained in Detail
The id() function generates a unique identification number for the integer object 20. This unique identification number is an integer value which will remain unique and constant for the Python object during its
lifespan, as shown in the below figure. The id for integer object 20 is 1449404138320.
So, a variable is simply a reference to a value stored in the particular memory location. The size of memory reserved by the variable depends the type of value it is going to store. However, its value may vary
during the time of execution, but at a time, only one value can be stored in it.
Example 2 :
Creating variable and assigning value

# Integer assignments.
x = 20
y = 50
z = 100
# Print the values of variables on the console.
print(x)
print(y)
print(z)

Output

20
50
100

Example 3 :
Create a program where we will add marks of three subjects: physics, chemistry, and maths and print the marks obtained and percentage.

phy = 89
chem = 86
maths = 90
# Adding the marks of three subjects.
marks_obtained = phy + chem + maths

# Calculating the percentage.


per = (marks_obtained * 100) / 300
# Displaying the marks obtained and percentage.
print("Marks obtained in three subjects: ", marks_obtained)
print("Percentage: ", per)

Output

Marks obtained in three subjects: 265


Percentage: 88.33333333333333

Example 4 :
Initializing different values to different variables.

x = 80 # an integer assignment.
y = 99.99 # a floating point assignment.
name = 'Radhika' # a string assignment.
print(x); print(y); print(name);

Output

80
99.99
Radhika

8 Built-in Data Types


A data type in Python defines a specific type of value that a variable can store.
In other words, the type of data value we can store in an identifier such as a variable, is called its data type.
In the Python language, every value has a data type and everything is an object, meaning that Python represents all its data or value as objects. So, every value in Python is an object with a data type.
Types of Built-in Data types in Python
Like any other programming language, Python language allows us to work with the eight built-in standard data types. A list of all core data types are as follows:

Number
Boolean
None
String
List
Tuple
Dictionary
Set

These data types are further categorized into fundamental, sequence, and set data types.

Fundamental data types or native data types: int, float, and complex.
Sequence data types: string, list, and tuple.
Mapping data type: dictionary

Number Data types in Python


Number represents the numeric data or value (also called numeric literal) to perform mathematical operations. In Python, the number data types stores numeric values, such as integers, floating-point number, and
complex number.
When we assign a value to a variable, the Python interpreter automatically creates a number object. The general syntax to assign a value to a number object is as:
<numeric literal name> = <numeric literal value>

Example 1 :

num1 = 10
percentage = 80.50

Explained in Detail
From the above assignment,

By default, Python will treat num1 as an integer because we have assigned one integer value to a variable num1.
Python will treat percentage as float because we have assigned one float value to a variable percentage.

Python supports three fundamental numerical data types. They are:

int (signed integer values)


float (floating point real values)
complex (complex numbers)
All three fundamental data types have been defined as int, float, and complex class in Python.

Int Data type


A Python object of int data type represents an integer number (without any decimal point or fractional part). It can be a positive, negative, or zero. The range of numbers is -2147483648 to 2147483647.
Example 1 :
num1 = 10
num2 = 20
num3 = 30
print(num1)
print(num2)
print(num3)

Output
10
20
30

Example 1 :
Adding two integer variables and assign the result of them in an integer variable.
num1 = 100
num2 = 200
result = num1 + num2
print(result)

Output
300

Float Data type


A float data type can store the floating type number. A floating-point number is a real number that contains a decimal point. For example: 0.59, -2.4125, 555.789, etc. are the floating-point numbers. It can be
accurate up to 15 decimal places.
Example 1 :
Creating a variable and assign a float value to it.

num1 = 10.555
num2 = 20.99
result = num1 + num2
print(result)

Output
31.544999999999998

Complex Data type


A complex number is a number that we write in the form of “a + bj”. Here, a stands for the real part of a number and b represents the imaginary part of a number.
The lower case letter j after b refers to the square root of -1. The part a and b may have integer or float numbers. For example, 5 + 5j, 2.5 + 4j are the complex numbers.
Example 1 :

num1 = 2 + 5j
num2 = 3.5 + 7.5j
result = num1 + num2
print(result)

Output
(5.5+12.5j)

Boolean Data type


Python provides two built-in Boolean data types: True or False, which internally represents 1 or 0 in a numeric context. The two values True and False are only boolean objects. Boolean data type is defined
as a bool class in Python.
Example 1 :

a = (10 >= 4)
b = (25 == 5 * 5)
c = (18 != 2 * 9)
# Use the print function to see values stored in each variable.
print(a, b, c)

Output
True True False

Sequence Data type in Python


Sequence data type represents a group or collection of elements or items. For example, a group of integer numbers, a group of strings, etc.
A variable of sequence data type may have different values of the same data type or values of different data types.

String
List
Tuple
Set
Dictionary

String Data type in Python


String is the most popular and useful data types in Python. A string literal is a group or sequence of characters. It is immutable in nature.
In Python, strings are created using single, or double quotation marks.
Example 1 :
str1 = "Hello Python"
str2 = 'Happy birthday to you'
print(str1)
print(str2)
print(type(str1))

Output

Hello Python
Happy birthday to you
<class 'str'>

List Data type


List is the most versatile and flexible data types of Python language. It is defined as a class list in Python. List is an ordered sequence of heterogeneous elements (i.e. does not need to be of the same
data type). It is similar to an array in C, C++, or Java.
The major difference between a list and an array is that an array is a group of homogeneous elements (i.e. of same data type) while the list is a collection of elements of heterogeneous or different
data types.
Example 1 :

list = [10, 20.50, "Python", True]


print(list)
print(type(list))

Output

[10, 20.5, 'Python', True]


<class 'list'>

Example 2 :
Updating elements in the list.

num_list = [10, 20, 30, 40]


print(num_list)
num_list[2] = 50 # updating element.
print(num_list)

Output

[10, 20, 30, 40]


[10, 20, 50, 40]

Tuple Data type


Tuple data type is the same as list data type. It has been defined as a class tuple in Python. A tuple is an ordered sequence of heterogenous elements separated by commas.
The only difference between tuple and list is that a list is mutable while tuple is immutable, i.e. tuples once created, we cannot modify elements inside the tuple. It is used to protect the data and also faster
than list.
We create the tuple in Python using the parentheses ( ) and separate elements in the tuple using commas.
Example 1 :

t = (10, 20, "Python", 2 + 10j)


print(t)
print(type(t))

Output

(10, 20, 'Python', (2+10j))


<class 'tuple'>

Set Data type


A set is an unordered collection of unique heterogeneous elements separated by commas inside curly braces ({ }). It does not maintain the order of elements in the set. It means that elements may not
appear in the same order as they have entered.
Moreover, the set does not contain duplicate elements. The set data type is defined as a class set in Python.
Example 1 :

s = {1, 2, 'Hello', 4 + 50j}


print(s)
print(type(s))

Output

{1, 2, (4+50j), 'Hello'}


<class 'set'>

9 Global and Local Variables


Depending upon their scope, there are two types of variables in Python that are as:

Global variable
Local variable

Global Variable in Python


A global variable is a variable that is defined in the main part of the code, but outside any function. In other words, a variable defined outside all functions in a program is called global variable in
Python.
It will be visible everywhere in the entire Python code. That is, we can access a global variable throughout the Python program.
We can use them anywhere, even inside function or outside the function or also inside any file which imports that file.

Example 1 :
Creating a Python program in which we will create a global variable in the main code, and access it inside the function and outside the function.

x = 20 # a global variable.
# Creating a user-defined function named my_function.
def my_function():
# Accessing the global variable inside the function.
print("Inside function: ", x)

# Calling the function.


my_function()
# Accessing the global variable from outside the function.
print("Outside function: ", x)

Output

Inside function: 20
Outside function: 20

Explained in Detail
In the above code, we have created a global variable x in the main code area and assigned it with a value 20. After that, we have defined a function named mu_function(). Inside the function, we have accessed
the global variable to print the value of x.
Outside the function, we again accessed the global variable x and called the function. You can see that a global variable can be accessed successfully inside a function and outside the function.
If we create a variable with the same name as the name of global variable inside a function, Python interpreter will treat this variable as local.
In this case, we can only access it inside the function, not outside the function. However, the global variable will remain with the same name and the original value as it is.

Example 2 :
Creating a variable inside a function with the same name as the global variable.

x = 20 # a global variable.
def my_function():
# Creating a variable with the same name as the name of global variable.
x = 20 * 30 # Here, interpreter will treat as a local variable.
print("Inside function: ", x)

# Calling the function.


my_function()
# Accessing the global variable from outside the function.
print("Outside function: ", x)

Output

Inside function: 600


Outside function: 20

Explained in Detail
Here, Python creates a new local variable with the same name as a global variable name inside the function. That’s why when we accessed it from inside and outside the function, we gained two different values,
as you can see in the output.

Global Keyword in Python


Python provides a global keyword to create a global variable inside a function. If we declare a variable with a global keyword inside the function, the variable belongs to the global scope.
We can also use the global keyword if we want to change a value of global variable inside the function.
To declare a global variable, we need to write a global keyword before the variable name inside the function.
Example 3 :

name = 'John' # a global variable.


def my_function1():
global name
name = 'Bob' # Here, changing the value of global variable inside the function.
print("Inside function: ", name)
def my_function2():
print("Inside another function: ", name)

# Calling the functions.


my_function1()
my_function2()

# Accessing the global variable from outside the functions.


print("Outside function: ", name)

Output

Inside function: Bob


Inside another function: Bob
Outside function: Bob

Explained in Detail
As you can see in the output, the preceding code printed the changed value of global variable name, which is defined inside the function, and accessed inside functions and also outside function.
Example 4 :

city = 'New York' # a global variable.


def my_function1():
global city
city = 'Dhanbad'
print("Inside my_function1: ", city)
def my_function2():
global city
city = 'Sydney'
print("Inside my_function2: ",city)
# Calling the function.
my_function1()
my_function2()
print("Outside function: ", city)

Output

Inside my_function1: Dhanbad


Inside my_function2: Sydney
Outside function: Sydney

Local Variable in Python


A local variable is a variable that is defined inside the body of the function or in the local scope. It is accessible only within the function where it is defined and exists in the memory as long as the function is
executing.
In other words, local variables inside a function have a local scope and destroyed from the memory as the execution of the function completes.
Example 1 :
Writing a Python program in which we will declare both local and global variables, access them, and display their messages.

# Declare a global variable and assign it a value.


message1 = "This is a global variable, and we can access it anywhere in the program."
# Create a function named display.
def display():
# Declare a local variable and assign it a value.
message2 = "This is a local variable, and we can access it only inside the function body."
print(message2) # Accessing local variable from inside the function.

print(message1); # Accessing the global variable.


display() # Calling function.

Output

This is a global variable, and we can access it anywhere in the program.


This is a local variable, and we can access it only inside the function body.

10 Memory Management
Memory management in Python is the process by which the computer system reserves a part or complete section of memory for the process and execution of programs.
It allows the application programs to read and write data. We know that there is an enormous size of memory in the computer system.
It is essential to allocate some free space in the memory and make it available for the execution of the program.
This way of allocating (i.e. providing) memory for the execution of a program is called memory allocation.
Also, when data is no longer in use, must be removed or erased from the memory after being execution of code. Knowledge of memory management helps developers to write the efficient code.

How Python Managing Memory


In C and C++, we may need to allocate and de-allocate memory dynamically during runtime of a program. Dynamic memory allocation is a term for it.
Basically, dynamic memory allocation is the allocation of the memory at runtime as the program executes. For example, to allocate memory, we can use malloc() function and to de-allocate the memory, we can
use the free() function.

However, Python handles memory allocation and de-allocation at runtime automatically. We do not need to allocate while creating objects or de-allocate memory when deleting objects.
Python interpreter is the responsible for dynamically allocation and de-allocation of the memory. In other words, the Python interpreter takes care of memory management.
In Python, everything is considered as an object. For example, numbers, strings, functions, dictionary, lists, modules, and user-defined classes are considered objects in Python.
We can access them with the help of identifier. Python’s memory manager allocates the memory to the objects as per requirement. It uses a private heap space for memory management, which is not accessible by
the programmer.
All the Python objects and data structures are allocated in this heap space. The memory manager through Python API functions internally manages this private heap space for Python objects.
Python has also an in-built garbage collector, which recycles all the unused memory so that free space is available in heap memory.
Example 1 :
Suppose we assign a value of 10 to a variable x:
x = 10
print(id(x))

Output
2248409678352

Explained in Detail
In this example, the id() function generates a unique identification number for an object. This unique identification number is an integer value which will remain unique and constant for the Python object during its
lifespan, as shown in the below figure. The id for integer object 10 is 2248409678352.

Example 2 :
Two objects with non-overlapping lifetimes can have the identical id value.
x = 10
print(id(x))
y = 10
print(id(y))

Output

2070047162896
2070047162896

Explained in Detail
As you can observe in the output, both reference variables x and y are pointing to the same integer object 10 because of the same unique identification number. Look at the below figure that x and y have
reference to the same object.

Example 3 :
x = 10
print(id(x))

y = 10
print(id(y))

z=y
print(id(z))

Output
2070047162896
2070047162896
2070047162896

Explained in Detail
As you can see in the output, the id() function generated the same identification number for the integer object 10. Therefore, z is also pointing to the same object.

Example 4 :
x = 10
print(id(x))
y = 10
print(id(y))

z=y
print(id(z))
x=x+1
print(id(x))

Output
1887578292752
1887578292752
1887578292752
1887578292784

Explained in Detail
Now, as you can see in the output, the id() function has generated the different identification number for this operation x = x + 1. Therefore, x is not equal to 11 and now refers to the different integer object 11.

Stack and Heap Memory in RAM


The memory management in Python is divided into two parts mainly.
Stack memory:

In the stack memory, all methods are executed.


References to Python objects in the heap memory are produced in the stack memory.
Heap memory:

All Python objects are created in the heap memory.

Example 1 :

def func(x):
value = (x + 5) * 10
return value
x = 10
final_value = func(x)
print("Final value = ", final_value)

Output
Final value = 150

Explained in Detail
The execution of program code begins from the main which in this case is:

x = 10
final_value = func(x)
print("Final value = ", final_value)
Step 1: Execute x = 10
This statement creates an integer object 10 in the heap memory and the reference variable x is created in the main stack memory that is pointing to this integer object, as shown in the below figure.

Step 2: Execute final_value = func(x)


This statement will call func(x).

def func(x):
value = (x + 5) * 10
return value

In order to execute func(x), Python interpreter adds a new stack frame in the memory. Till the time, func(x) is being executed, the interpreter put on hold the value 10 referenced by x of the lower stack frame.
The integer value 10 is passed as an argument to this function.

Now, value = (x + 5) * 10 = (10 + 5) * 10 = 150 (refer below figure). The func() function assigns the value of 150 to the value.

Now, the func() function will return the value 150, and the interpreter will assign it to the final_value in the main stack memory. Look at the following figure below.
Chapter 3 :
Operators

1 Arithmetic Operators
2 Assignment Operators
3 Comparison (Relational) Operators
4 Logical Operators
5 Bitwise Operators
6 Special Operators
1 Identity Operators
2 Membership Operators

Like other programming languages such as C++ or Java, Python also offers a rich set of many operators for working with and comparing types of data or information.
The definition of an operator is simply a special symbol that tells the interpreter to perform a specific operation or action, usually on numbers (operands).
For example, when we add two values, e.g. (10 + 20 = 30). Here, 10 and 20 are numbers also called operands. The plus (+) sign is an arithmetic operator and (10 + 20) is a numeric expression.
The operand in the expression can be a literal, variable, or any expression that has to be calculated.
Programmers extensively use operators in Python program to perform some sort of calculation, comparison, or assignment on one or more values.

1 Arithmetic Operators
Operators that are used to perform the most common mathematical calculations or arithmetic operations are called arithmetic operators in Python.

All arithmetic operators are binary operators because they do operations on two operands (two or more values). Python supports seven types of arithmetic operators. They are:

Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Floor division (//)
Exponential (**)

Addition Operator (+)


This operator is the most commonly used operator in Python. We can use it to add two or more numbers of any type, or to join two objects when applied to two strings, lists, tuples, or dictionaries.

Example 1 :
To add two numbers using (+) operator and display its result.

# Declare variables x and y with values.


x = 20
y = 30
sum = x + y # Adding two numbers with + operator.
print("Sum: ", sum) # Displaying the result.

Output
Sum: 50
Example 2 :
Concatenating two strings using + operator.

firstName = "John"
lastName = "Michael"
fullName = firstName + lastName # Joining two strings with + operator.
print("Full name: ", fullName) # Displaying the result.

Output
Full name: John Michael

Example 3 :
Concatenate two lists using + operator.

x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
result = x + y # Adding the lists x and y.
print(result)

Output
[1, 2, 3, 4, 5, 6, 7, 8]

Subtraction Operator (-)


The minus operator (-) subtracts one number from another. That is, it subtracts the right value from the left.
Example 1 :
Subtraction of two numbers.
x = 20
y = 30.60
sub = x - y
print("Subtraction: ", +sub)

Output
Subtraction: -10.600000000000001

Multiplication Operator (*)


The multiplication operator multiplies the values on either side of the operator. When the values on either side of the expression are integer or float numbers, they multiplied together.
Example 1 :
Multiplication of two numbers.

x = 20
y = 20.20
result = x * y # Two variables multiplied using multiplication operator.
print("Multiplication: ", result)

Output
Multiplication: 404.0

2 Assignment Operators
An operator that is used to store/assign a value to a variable is called assignment operator in Python.
The most common assignment operator is equal operator “=”, which assigns the right-hand value to the left-hand variable.

Classification of Assignment Operators in Python


We can classify assignment operators in Python into three basic categories. They are ​as:

Simple assignment
Compound assignment
Assignment as expression

Simple assignment
Example 1 :
Adding numbers.
x = 20
y = 50
z=x+y+2
print("Result = ", z)

Output
Result = 72

Compound Assignment Operators in Python


Compound assignment operators in Python comprise a simple assignment operator with another binary operator.
Here, the op signifies the basic binary operator. It may be +, –, *, /, %, etc. variable_name and expression are the same as explained in the simple assignment.

1. Add and Assignment Operator (+=)


This operator adds the value of right operand to the value of the left operand and assigns the result to left operand.
Example 1 :

x = 20
y=5
z = 10
x += y
print("Result of (x = x + y) = ", x)
z += x + y
print("Result = ", z)

Output

Result of (x = x + y) = 25
Result = 40

2. Subtract and Assignment Operator (-=)


This operator subtracts the value of right operand from the value of left operand and assigns the result to left operand.
Example 2 :

x = 20
y=5
z = 10
x -= y
print("Result of (x = x - y) = ", x)
z -= x + y
print("Result = ", z)

Output

Result of (x = x - y) = 15
Result = -10

3. Multiply and Assignment operator (*=)


This operator multiplies the value of right operand with the value of left operand and assigns the result to left operand. Example 3 :

x=2
y=5
z=3
x *= y
print("Result of (x = x * y) = ", x)
z *= x * y
print("Result = ", z)

Output

Result of (x = x * y) = 10
Result = 150

4. Divide and Assignment Operator (/=)


This operator divides the value of left operand with the value of right operand and assigns the result to left operand.
Example 4 :

x = 20
y=5
z = 100
x /= y
print("Result of (x = x / y) = ", x)
z /= x * y
print("Result = ", z)

Output

Result of (x = x / y) = 4.0
Result = 5.0

5. Modulus and Assignment operator (%=)


This operator takes modulus on the values using two operands and assigns the result to the left operand.
Example 5 :

x = 211
y=5
z = 100
x %= y
print("Result of (x = x % y) = ", x)
z %= x + y
print("Result = ", z)

Output

Result of (x = x % y) = 1
Result = 4

6. Floor Division and Assignment Operator (//=)


This operator performs floor division on the operands and assigns the result to the left side operand.
Example 6 :

x = 211
y=5
z = 100
x //= y
print("Result of (x = x // y) = ", x)
z //= x + y
print("Result = ", z)

Output

Result of (x = x // y) = 42
Result = 2
7. Exponent and Assignment Operator (**=)
This operator performs exponential (i.e. power) calculation on the operands and assigns the result to the left side operand.
Example 7 :

x=2
y=5
z=2
x **= y
print("Result of (x = x ** y) = ", x)
z **= x + y - 30
print("Result = ", z)

Output
Result of (x = x ** y) = 32
Result = 128

8. Bitwise AND and Assignment Operator (&=)


This operator performs bitwise AND calculation on the operands and assigns the result to the left side operand.
Example 8 :

x = 20
y=5
x &= y
print("Result of (x = x & y) = ", x)

Output
Result of (x = x & y) = 4

9. Bitwise OR and Assignment Operator (|=)


This operator performs bitwise OR calculation on the operands and assigns the result to the left side operand.
Example 9 :
x = 10
y=5
x |= y
print("Result of (x = x | y) = ", x)

Output
Result of (x = x | y) = 15

10. Bitwise XOR and Assignment Operator (^=)


This operator performs bitwise XOR calculation on the operands and assigns the result to the left side operand.
Example 10 :

x = 20
y = 10
x ^= y
print("Result of (x = x ^ y) = ", x)

Output
Result of (x = x ^ y) = 30

11. Bitwise Right Shift and Assignment Operator (>>=)


This operator performs the bitwise right shift calculation on the operands and assigns the result to the left side operand.
Example 11 :
x=6
y=2
x >>= y
print("Result of (x = x >> y) = ", x)

Output
Result of (x = x >> y) = 1

Assignment as Expression
In Python, we can also treat an assignment operation as an expression because the operation has a result. The outcome (or result) of an expression is a value that stored in a variable.
Example 12 :

a, b, c = 19, 31, 50
a += 1
b -= 1
c *= 2

x = (10 + a)
y = x + 100
z=x+y+c

print("Value of a: ", a)
print("Value of b: ", b)
print("Value of c: ", c)

print("Value of x: ", x)
print("Value of y: ", y)
print("Value of z: ", z)

Output
Value of a: 20
Value of b: 30
Value of c: 100
Value of x: 30
Value of y: 130
Value of z: 260

Explained in Detail
The following steps involved to evaluate the above expressions of the Python program.
1. Evaluation of expression: a += 1

a=a+1
a = 19 + 1
a = 20

2. Evaluation of expression: b -= 1

b=b–1
b = 31 – 1
b = 30

3. Evaluation of expression: c *= 2

c=c*2
c = 50 * 2
c = 100

4. Evaluation of x = (10 + a)

x = 10 + 20 # Here, the value of x will be 20, not 19.


x = 30

5. Evaluation of y = x + 100

y = 30 + 100 /# Here, value of x will be 30.


y = 130

6. Evaluation of z = x + y + c

z = 30 + 130 +100 # Here, value of c will be 100.


z = 260

3 Comparison (Relational) Operators


In other words, comparison operators compare values stored in two variables and return a boolean value.
They determine the relationship between them by comparing operands (or values). Therefore, we also know the comparison operators as relational operators in Python.

Types of Comparison Operators in Python


Python supports six types of relational or comparison operators. We have listed them below:

Equal (==)
Not equal (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)

1. Equal to (==)
This operator evaluates that the value of left and right operands is equal or not. If the left operand’s value is equal to the right operand’s value, the condition becomes true, i.e. the equality operator returns
true. Otherwise, returns false.
In other words, the equality operator compares and returns true if two objects are equal to each other.
Example 1 :

# Comparison between two numeric values using equal operator.


x = 20
y = 20
print("Returned value of (x == y): ", x == y)

# Comparison between two string values using equal operator.


p = 'My name is John'
q = 'My name is John'
print("Returned value of (p == q): ", p == q)
r = 'Text'
s = 'text'
print("Returned value of (r == s): ", r == s)

# Comparison between two lists using equal operator.


t = [1, 2, 3, 4]
u = [1, 2, 3]
print("Returned value of (t == u): ", t == u)

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


List2 = List1
print("Returned value of (List1 = List2): ", List1 == List2)

Output
Returned value of (x == y): True
Returned value of (p == q): True
Returned value of (r == s): False
Returned value of (t == u): False
Returned value of (List1 = List2): True

Explained in Detail
a) In the above code, the string “Text” is not equal to the string “text” because they are not exactly the same; one starts with uppercase letter ‘T’ and the other with lowercase letter ‘t’. Therefore, both reference
variables r and s are pointing to different objects ‘Text’ and ‘text’.
b) The statement (t == u) returned False because both reference variables t and u are pointing to different lists.
c) The statement (List1 == List2) returned True because both reference variables List1 and List2 are pointing to the same object.

2. Not equal to (!=)


This operator checks that the left side operand is not equal to the right side operand. If the values on both sides of the operator are not equal to each other, the not equal operator returns true.
In other words, the not equal operator compares and returns true if two objects are not equal else returns false.
Example 2 :

x = 50
y = 90
print("Returned value of (x != y): ", x != y)

str1 = 'My name is John'


str2 = str1
print("Returned value of (str1 != str2): ", str1 != str2)
a = True
b=1
print("Returned value of (a != b): ", a != b)

p = False
q=0
print("Returned value of (p != q): ", p != q)

r = '50'
s = 50
print("Returned value of (r !=s ): ", r != s)

Output

Returned value of (x != y): True


Returned value of (str1 != str2): False
Returned value of (a != b): False
Returned value of (p != q): False
Returned value of (r !=s ): True

3. Greater than (>)


This operator checks that the value of the left operand is greater than the value of the right operand. If the value on the left side of operator is greater than the value on the right side, the operator returns
true. Otherwise, it returns false.
In other words, the greater than (>) operator compares and returns true if the first object is greater than the second object, else returns false.
Example 3 :

num1 = 60
num2 = 50
print(num1 > num2)
print(num1 + 20 - 20 > num2 + 20)

n1 = 20
n2 = n1
print(n1 > n2)

Output

True
False
False

4. Less than (<)


This operator evaluates whether the value of the left operand is less than the value of the right operand. If the value on the left side of operator is less than the value on the right side, the outcome
becomes true.
In other words, the less than operator (<) compares and returns true if the first object is less than the second object else returns false.
Example 4 :
num1 = 20
num2 = 20.05
print(num1 < num2)

exp1 = 20 * 20 % 20
exp2 = 20 + 20 / 20
print(exp2 < exp1)

Output
True
False

5. Greater than or equal to (>=)


This operator checks whether the value of the left operand is greater than or equal to the value of the right operand. If the value on the left side of the operator is greater than or equal to the value on the
right side, then it returns true. Otherwise, returns false.
Example 5 :

num1 = 20.20
num2 = 20.0200
print(num1 >= num2)

x = True + 2
y = False + False + False
print(x >= y)

p = 'abcd'
q = 'abcde'
print(p >= q)

Output

True
True
False

6. Less than or equal to (<=)


This operator checks whether the value of the left operand is less than or equal to the value of the right operand. If the value on the left side of the operator is less than or equal to the value on the right
side, then it returns true. Otherwise, returns false.
Example 6 :

num1 = 40.40
num2 = 40.400
print(num1 <= num2)

x = True + 2
y = False + False + False
print(x <= y)

p = 'A'
q = 'B'
print(p <= q)

Output

True
False
True

4 Logical Operators
Logical operators in Python are binary operators which are used to combine two or more simple conditions or relational expressions.
In other words, logical operators combine one or more comparison into one condition group.
It is useful when we want to check more than one condition at a time and use the result.
A simple example of a logical operator that combines two relational expressions, or conditions.

Types of Logical or Boolean Operators in Python


In the Python language, there are three types of logical operators. We have listed them in the below table:

Logical AND Operator (and) in Python


The logical AND operator combines two relational expressions (or conditions) together into one condition group. It uses ‘and’ as a symbol.
The Python interpreter evaluates separately both expressions and then the logical and operator compares the result of both.
If the conditions on both sides of logical and operator are true, the operator returns true. If one or both conditions on either side of the operator are false, then it returns false.
Let’s take some examples in which we have combined two relational expressions by logical and operator.

print(20 > 10 and 30 < 40) # True.


print(10 == 10 and 88 >= 78) # True.
print(10 == 20 and 50 <= 40) # False.

Explained in Detail
From the above statements, it is clear that the logical and operator returns true only if all the expressions (or operands) are true. Otherwise, it returns false value.

Example 1 :
x, y = 10, 5
result = (x == 10 and y == 5)
print(result)

result = (x == 10 and y > x)


print(result)

result = (x < y and y > x)


print(result)

Output
True
False
False

Explained in Detail
a) In the first result statement, there are two conditions or relational expressions; (x == 10) and (y == 5). The result of both conditions are true. Therefore, the logical and operator returns true value.
b) In the second result statement, the condition (x == 10) is true, but the condition (y > x) is false. Therefore, the logical and operator returns false value.
c) In the third result statement, both conditions (x < y) and (y > x) are false. Therefore, the logical and operator returns false value.

Example 2 :

x, y, z = 20, 10, 25
# Use of logical and operator in the if statement.
if(x > y and y > z):
print("Hello")

if(z > y and y < x):


print("Python")

if((y+200) < x and (y+150) < z):


print("Hello Python")

Output
Python

Explained in Detail
a) In the first if statement, there are two conditions: x > y and y > z. The condition x > y is true, but y > z is not true. Therefore, the statement “Hello” is not displayed on the console.
b) In the second if statement, both conditions z > y and y < x are true. Therefore, the statement “Python” is displayed on the console.
c) In the third if statement, both conditions are false. Therefore, the statement “Hello Python” is also not displayed.
Example 3 :

x = (15 < 20) and ("pen" < "pencil")


y = ("Big" < "bigger") and (True != 1)
z = ("A" <= "A") and ("a" != "a")
print("x: ", x)
print("y: ", y)
print("z: ", z)

Output
x: True
y: False
z: False

Explained in Detail
a) In the preceding example code, x returns true because comparison on both sides is true. 15 is less than 20 and the string pen is less than pencil on the basis of ASCII values.
b) Similarly, y returns false because the condition (“Big” < “bigger”) is true, but the condition (True != 1) is false.
c) While, z returns false because the comparison on the right side is false.

Logical OR Operator (or) in Python


The logical or operator in Python combines two or more expressions or conditions together into a single condition group.
The or operator returns true if one or both of the conditions returns true. If the conditions on both sides of the operator are false, the logical or operator returns false.
Here are some simple examples in which we have combined two conditions by logical or operator.
print((2 == 2) or (3 > 5)) # It will return true because comparison on the left side is true.
print((5 > 18) or (3 != 9)) # It will return true because comparison on the right side is true.
print((4 == 4) or (5 < 9)) # It will return true because comparison on both sides is true.

print((4 < 2) or (2 == 1)) # It will return false because both comparisons are false.
print((3 != 3) or (3 >= 9)) # It will return false because both comparisons are true.

Explained in Detail
From the above example codes, it is clear the logical or operator returns true only if at least one expression (or operand) is true.

Example 1 :

x, y, z = 20, 10, 5
if(x > y or y > z):
print("Python")

if(z > y or y < x):


print("JavaScript")
if((y+20) < x or (z+15) < y):
print("Java")

Output

Python
JavaScript

Explained in Detail
a) In the first if statement, both conditions are true. Therefore, the interpreter displays ‘Python’ on the console.
b) In the second if statement, one condition on the right side of or operator is true. Therefore, the interpreter displays ‘JavaScript’ on the console.
c) In the third if statement, both conditions are false. Therefore, the interpreter does not display ‘Java’ on the console.

Example 2 :

x, y, z = 10, 5, 20
if((x > y) or ( y == z)):
print("One")
if((x == y) or (y < z )):
print("Two")
if((x != y) or (y != z)):
print("Three")
if((x < y) or (y > z)):
print("Four")
Output

One
Two
Three

Example 3 :

a = ("big " != "bigger") or False


print("a: ", a)
b = True or False
print("b: ", b)

c = "a" or D
print("c: ", c)
d = ("ABc" > "abC") or False
print("d: ", d)

Output

a: True
b: True
c: a
d: False

Logical NOT Operator (not)


The logical not operator is something different from the logical ‘and’ and ‘or’ operators. We use it for a single comparison. It is mainly used to reverse the result.
That is, if the condition evaluates true, the result of the condition returns false. If the expression evaluates false, the result of the condition returns true.
Example 1 :

a = not("ABc" > "ABC") or False


print("a: ", a)
b = not(True) or not(False)
print("b: ", b)

c = (True >= 0) or not(20 == 20)


print("c: ", c)
d = not("5" == 10) and not(False and (10 != 20))
print("d: ", d)

Output

a: False
b: True
c: True
d: True

5 Bitwise Operators
Bitwise operators in Python are binary operators that work on the bits comprising ones and zeros (i.e., binary numbers) rather than decimals or hexadecimals.
Here, the term bitwise means to operate on a binary number (0 or 1). Python bitwise operator works on each bit of number.
They operate in the following steps:
1. When we use bitwise operators on the operands (i.e. integer numbers), they firstly convert operands to bits, perform the operation on each bit directly.
2. Then, bitwise operators convert binary output to a decimal number, and give the output in the decimal number.
In bitwise operations, the Python interpreter internally converts the integer numbers into the binary number system that is represented by two digits, 0 or 1.
Bitwise operators may be binary operators or unary operators that work on two operands or one operand.

Types of Bitwise Operators in Python


Python supports six bitwise operators to work on individual bits. We list them in the table below:
Bitwise AND operator (&)
Bitwise AND is a binary operator that performs AND operation on each bit of two operands (i.e., numeric values). It compares the corresponding bits of both binary numbers and sets the output to 1 if
both bits are 1.
If both or one of the corresponding bits is 0, it sets the output to 0. The syntax is as follows:
A & B # Here, A and B are operands.

We listed the truth table for this operator in the below table:

Example 1 :

A= 2
B= 6
result = A & B
print("Result of (2 & 6): ", result)

Output
Result of (2 & 6): 2

Explained in Detail
In this example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise AND operator will take each bit of both binary numbers and perform AND operation as follows in the below figure.

Bitwise OR operator (|)


The bitwise OR operator is a binary operator that performs a boolean OR operation on each bit of its integer numbers. It is represented by a symbol | called pipe symbol.
In OR operation, each bit of the first operand (number) is compared with the corresponding bit of the second operand. If both or any of the compared bits are 1, then the OR operator sets the output to 1.
Otherwise, it sets the output to 0. The syntax is as below:

A| B

The truth table for bitwise OR operator is as below:


Consider the preceding truth table of bitwise OR operator. If both compared bits are 0, the output is 0. If anyone bit is 1 in both bits; the output is 1.
Example 1 :

A= 2
B= 6
result = A | B
print("Result of (2 | 6): ", result)

Output
Result of (2 | 6): 6

Explained in Detail
In this example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise OR operator will take each bit of both binary numbers and perform OR operation as follows in the below figure.

Example 1 :

A = 25
B = 45
result = A | B
print("Result of (25 | 45): ", result)

Output
Result of (25 | 45): 61

Explained in Detail
In this example, the binary conversion of 25 is 011001 and that of 45 is 101101. Bitwise OR operator will take each bit of both binary numbers and perform OR operation as follows below:
25 & 45 => 011001 & 101101 => 111101 => 61 (in decimal number system).

Bitwise XOR operator (^)


The bitwise XOR is a binary operator that performs a boolean exclusive OR (XOR) operation on each bit of its integer numbers. It is represented by a symbol ^ called cap. The general syntax to use XOR
operator is as:
A^ B

Look at the below truth table to understand more clearly.


Example 1 :

A= 2
B= 6
result = A ^ B
print("Result of (A ^ B): ", result)

Output
Result of (A ^ B): 4

Explained in Detail
In the preceding example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise XOR operator will take each bit of both binary numbers and perform XOR operation as follows below:
2 ^ 6 => 0010 & 0110 => 0100 => 4. The decimal conversion of 0100 is 4.

Bitwise NOT operator (~)


The bitwise NOT is a unary operator that returns the reverse of its operand or value. It works basically as an inverter that converts all 1s to 0s, and all the 0s to 1s. Therefore, it is also called bit flip operator.
The truth table of bitwise NOT operator is as below:

Example 1 :

A = ~3
print("Result of (~3): ", A)

Output
Result of (~3): -4

Explained in Detail
The bitwise NOT operator will take each bit of binary number and convert all 1s to 0s and all 0s to 1s. The NOT operator also reverses the sign bit of binary number.

Thus, the positive number becomes negative and the negative number becomes positive. Therefore, the signed binary number of 3 is 0011.
~3 => ~0011 => 1100 => -4. The decimal conversion of 0011 is -4.

Bitwise Left Shift Operator (<<)


The bitwise left shift is a binary operator that shifts the number of bits to its left position. It shifts all bits to the left according to the values specified on the right-hand side of the operator.
After performing the left shift operation on the bits, the operator fills the rightmost bits by 0. The general syntax to use bitwise left shift operator is as:
A << B

Example 1 :

A= 3
B= 1
result = A << B
print("Result of (A << B): ", result)

X=3
Y= 2
result = X << Y
print("Result of (X << Y): ", result)

Output

Result of (A << B): 6


Result of (X << Y): 12

Explained in Detail
a) The working of bitwise left shift operator to shift one bit of 3 to the left side is as follows:
3 << 1 => 0011 << 1=> 0110 => 6 (shifted all bits by 1 position to the left and filled the rightmost one bit by 0).
b) The working of bitwise left shift operator to shift two bits of 3 to the left side is as follows:
3 << 2 => 0011 << 2 => 1100 => 12 (shifted all bits by 2 positions to the left and filled the rightmost two bits by 0).
Bitwise Right Shift Operator (>>)
The bitwise right shift is a binary operator that shifts the number of bits to its right position. It shifts all bits to the right according to the values specified on the right-hand side of the operator.
After performing the right shift operation on the bits, the operator fills the leftmost bits by 0. The general syntax to use bitwise right shift operator is as:
A >> B

Example 1 :

A= 6
B= 1
result = A >> B
print("Result of (A >> B): ", result)
X=6
Y= 2
result = X >> Y
print("Result of (X >> Y): ", result)

Output

Result of (A >> B): 3


Result of (X >> Y): 1

Explained in Detail
a) The working of bitwise right shift operator to shift one bit of 6 to the right side is as follows:
6 >> 1 => 0110 >> 1 => 0011 => 3 (shifted all bits by 1 position to the right and filled the leftmost one bit by 0).
b) The working of bitwise right shift operator to shift two bits of 6 to the right side is as follows:
6 >> 2 => 0110 >> 2 => 0001 => 1 (shifted all bits by 2 position to the right and filled the leftmost two bits by 0).
The conversion of 0011 in decimal number system is 3 and that of 0001 is 1.

Chapter 4 :
Conditional Statements in Python ( Control Flow )

1. Conditional Statements
2. If Statement
3. If-else Statement
4. If- elif-else Statement
5. Nested If-else Statement
6. Loops
7. While Loop
8. For Loop
9. Nested Loops
10. Infinite Loop
11. Break Statement
12. Continue Statement
13. Pass Statement
14. Switch Statement
1. Conditional Statements
Here , we will learn about conditional statements or decision-making statements in Python with the help of general flowchart diagram.
A simple program written in Python consists of a set of statements that contain expressions. An expression is a statement (or logical line) that comprises an operand and operator.

When we execute a Python program, at a time, only one statement executes by the Python interpreter. We call these statements as sequential statements.
Sequential statements are those statements that execute from top to bottom one by one (sequentially). The flow of execution takes place from top to bottom in the same order in which they appear in the
program.
However, if we want to change the flow of execution of a program, we can use control flow statements in Python.

Types of Control Flow Statements in Python


Python programming language supports three kinds of control flow statements.

Sequential control flow statements


Conditional control flow statements
Loop control flow statements
The further classification of control flow statements in Python has shown in the below figure.
Sequential Control Flow Statements
This refers to line by line execution in which Python executes a series of statements in a sequence appearing in the program. Basically, it uses the default mode because the program control moves line by line in
the program.
Example:

# Python program to calculate the area of a triangle.


x=4
y=5
z=6
# Calculating the semi-perimeter.
s = (x + y + z) / 2
# Calculating the area of triangle.
area = (s * (s -x) * (s -y) * (s - z)) ** 0.5
print('Area of triangle = %0.2f'%area)

Output
Area of triangle = 9.92

In this example, Python starts to execute from the first statement of the program. Python executes sequentially each statement. When the last statement is executed, the execution of program is complete.

Conditional Statements in Python


A conditional control statement is also known as selection control statements, decision control statements, or branching statements. It is based on the condition or decision. It executes a block of
statements depending on the outcome of a decision.
If the condition is true, then the block of statements will execute. If the condition is false, the block of statements will not execute. We also use it for checking and testing purpose.
Look at the below general form of a typical decision making structure in Python programming language.

In Python programs, we use conditional control flow statements to perform different actions based on different conditions. Python supports conditional control flow statements. They are:

if statement
if-else statements
Nested if statements
if-elseif-else statements

These conditional statements, known as decision making statements in Python because they execute a block of statements based on a decision.
They use the boolean expression for conditional test. The boolean expression may be either a single expression or multiple expressions.
When Python evaluates this boolean expression, it generates a boolean value either TRUE or FALSE as a result. Based on the result, the conditional control flow statement executes the block of statements.

Loop Control Flow Statements


A loop control statement allows us to execute or repeat a statement or a group of code multiple times. We call it as looping or iteration in Python. Looping simply means repetition of a block of code
depending on a condition test.
As long as the test condition is true, a block of code is repeated again and again. As soon as the test condition becomes false, the repetition stops.
Look at the below general form of a loop control flow structure in Python programming language.

A set of statements that are repeated again and again is called loop body. We can use the loop control statement when we need to execute a block of code several number of times according to a particular
condition.

Types of loop control statements


Python programming language supports three types of loops to handle iteration requirements. They are:

for loop
while loop
nested loops
For loop is a counting loop that repeats a block of statements a certain number of times.
While loop is a conditional loop that keeps repeating a set of statements as long as some test condition is true.

Unconditional Statements in Python


An unconditional statement in Python is a statement in which the control of execution jumps to another part of the code without carrying out any conditional test. It is also called unconditional execution in Python.
Python programming language supports two types of unconditional statements. They are as follows:

Break statement
Continue statement

2. If Statement
An if statement in Python is the simplest decision-making statement that allows the programmer to execute a block of statements only if some condition is true.
We use if statement in the Python program to compare data and to make a decision based on the result of comparison.
If statement has one test condition and one action. If the test condition is true, the statements followed by a condition will execute and skip them if the condition is false.
It is also called a conditional statement or single selection statement in Python because it either selects or ignores the action.

if test_condition:
Python statement(s) to be executed if condition is true.
or,
if(test_condition):
statement(s)

Explanation in Detail
a) The test condition consists of a boolean expression that returns a boolean value, either true or false.
b) The test condition may contain any relational comparison that comprises relational or comparison operators like <, >, <=, >=, etc. A relational operator compares two values, variables, or complex
expressions.
c) If the test condition is true, the block of statements inside the if statement executes. If the test condition is false, the block of statements skips or bypass.
d) It is optional to enclose the test condition with a pair of braces ().
e) A block of if statement (also called a body of if statement) is a sequence of statements. All the statements must be intended with the same number of white spaces (called indentation).
The indentation in Python shows the body of if statement. IDLE adds indentation automatically after a colon ‘:’.
f) However, you can choose how many white spaces to use when intending the block of if statement. Generally, we use two or four white spaces for intending, but you can use one space or several spaces if you
prefer.

Example 1:
Let’s write a Python program to calculate the area of a circle if the radius is greater than 0.

radius = 2.5
pi = 3.14
if radius >= 0:
area = radius * radius * pi
print("Area of circle: ", area)

Output
Area of circle: 19.625

Explanation In Detail
In the preceding example, if the boolean expression or condition evaluates to true, intended statements inside the block of if statement executes.
In other words, if the value of radius is greater than or equal to 0, the Python interpreter computes the area of circle, and displays the result on the console.
Otherwise, the interpreter will skip two intended statements in the block, not execute, and continue with the rest of program.

Example 2:
Let’s write a program in Python in which we will prompt the user to enter a number and check that the number is divisible by 2 or not. If the number is divisible by 2, the program prints a message “number is
divisible by 2”.

# Prompt the user to enter a number.


num = int(input("Enter a number that you want to check it is divisible by 2 or not: "))
if num % 2 == 0:
print(num, " is divisible by 2.")
if num % 2 != 0:
print(num, " is not divisible by 2.")

Output

Enter a number that you want to check it is divisible by 2 or not: 24


24 is divisible by 2.

Example 3:
Let’s write a program in Python in which we will display a “You are eligible to cast a vote” message if the age is greater than or equal to 18. If the age is not greater than or equal to 18, we will display “You are
not eligible to cast a vote!” on the console.

# Prompt the user to enter your age.


age = int(input("Enter your age to check you are eligible to cast a vote or not: "))
if age >= 18:
print("You are eligible to cast a vote.")

if age < 18:


print("You are not eligible to cast a vote")

Output

Enter your age to check you are eligible to cast a vote or not: 19
You are eligible to cast a vote.

Example 4:
Let’s write a Python program in which we will take marks for three subjects, such as math, chemistry, and physics from the user. Then, we will calculate the percentage of three subject marks and print “Grade A”
if the percentage is greater than or equal to 90. Look at a glance at the script code to understand better.

# Prompt the user to enter marks of three subjects.


phy = int(input("Enter your physics marks: "))
chem = int(input("Enter your chemistry marks: "))
maths = int(input("Enter your math marks: "))
totalMarks = phy + chem + maths

myPer = totalMarks / 3
print("Total marks obtained: ", totalMarks)
print("Your percentage: ", myPer)

if(myPer >= 90.0): # if the condition is true, then the statement will be displayed.
print("Grade A")
if(myPer < 90.0): # if the condition is true, then the statement will be displayed.
print("Grade B")

Output

Enter your physics marks: 89


Enter your chemistry marks: 87
Enter your math marks: 67
Total marks obtained: 243
Your percentage: 81.0
Grade B

Example 5:
Let’s write a program to check even or odd.

# Read the number from the user to check even or odd.


num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, 'is an even number')
if num % 2 != 0:
print(num, 'is a odd number')

Output

Enter a number: 5
5 is a odd number

Use of Logical Operators in If Statement


if you want to check multiple conditions together. There are three types of logical operators in Python that are as follows.

and
or
not

Example 1: Use of logical AND (and) operator

x, y, z = 20, 40, 50
if((y > x) and (y < z)): # True
print("y is greater than x but smaller than z")
if((x > y) and (y < z)): # False
print("z is greater than x, y")
if(y % x == 0 and x != 0): # True
print("y is divisible by x")

Output

y is greater than x but smaller than z


y is divisible by x

Explanation In Detail
In the preceding example, the first and third if statements evaluates true as both conditional expressions joined by logical and operator are true.
The second if statement evaluates false as the first conditional expression is false. In this example, if statement will produce true only if both expressions are true.
If any of the expressions is false or both expressions are false, if statement will produce false and skip the intended statement.
Example 2: Use of logical OR (or) operator

x, y, z = 2, 1, 4
if(value := x > y or y < z):
print(value)
if(value := x > y or y > z):
print(value)

if(value := x < y or y < z):


print(value)
if(value := x < y or y > z):
print(value)

Output

True
True
True

Explanation In Detail
In the preceding example, if any of the expression is true or both expressions are true, if statement evaluates true. If both expressions are false, the if statement evaluates false and the block of statements does not
execute.

Example 3: Use of logical NOT (not) operator

x, y = 2, 1
if(value := (x == 2) and not(y == 2)):
print(value)

Output
True

3. If-else Statement
If else in Python is a two-way conditional statement or double selection statement. It tests a conditional expression and executes one of two blocks of code, depending on the result.
In other words, an if else statement first evaluates the ‘if test condition/expression’.
If the test condition is true, Python executes the statements inside the block of the ‘if statement’. Otherwise, if the condition is false, Python executes the statements inside the else block.
Python if…else statement decides the execution path based on whether the condition is true or false.

When to use If-else Statement in Python


A one-way if statement in Python executes a statement if and only if the specified test condition is true. If the condition is false, Python will do nothing.
But, assume we need to take an alternative action when the specified test condition is false. In this case, we will use a two-way selection if-else statement.

num = 11
if num % 2 == 0:
print(num, "is divisible by 2.")
else:
print(num, "is not divisible by 2.")

Output
10 is not divisible by 2.

Explanation In Detail
In the above code, the specified test condition is false. Therefore, Python execute else block statement and print the message “10 is not divisible by 2”.
Thus, a two-way selection if else statement in Python routes the execution through two different paths based on the result of the condition.

if condition or expression:
statement to be executed if the condition is true.
else:
statement to be executed if the condition is false.

Explanation In Detail
In the above syntax, an optional else statement can follow an if statement. The if condition is a boolean expression that may be any comparison or logical expression that returns the boolean value either true or
false.
Each statement represents a single statement or a block of statements intended by two or four white spaces.
If the boolean expression in the if statement returns true, Python interpreter executes the statements inside the if block. If it returns false value, the interpreter executes statements inside else block.
The else block is an optional part. It means that else block part can be omitted if not required. You can follow this convention in ​all control statements in Python.
Flowchart Diagram of If else Statement
The flowchart for two-way if-else statement in Python is as shown below in the figure.

Let’s understand with the help of a flowchart diagram how two-way if-else statements work in the Python language.
If the test condition is true, then the if code will execute. If the condition is false, the else code will execute. In no case, both statements will execute at a time.
For example, consider the following below code.

passMarks = 40
if passMarks >= 40:
print("Passed")
else:
print("Failed")

Output
Passed

Explanation In Detail
In the above code, if the boolean expression evaluates to true, i.e., if the passMarks is greater than or equal to 40, is true, and it will print a message “Passed” on the console. If it evaluates to false, the message
“Failed” will print.

Example 1:

x, y = 20, 40
if x > y:
print(x, "is greater than ",y)
else:
print(y, "is greater than ", x)

Output
40 is greater than 20

Explanation In Detail
In the above code, Python evaluates the conditional expression x > y to false. Therefore, it executes else block statement and print the message “40 is greater than 20”.

Example 2:
gender = 'F'
if((gender == 'M') or (gender == 'm')):
print("You are a male")
else:
print("You are a female")

Output
You are a female
Explanation In Detail
In the above code, Python evaluates the conditional expression to false. Therefore, it executes else block statement and print the message “You are a female”.

Example 1:
Let’s write a program to check a number is even or odd using if…else statement.

# Taking an integer number from the user.


number = int(input('Enter a number: '))
if number % 2 == 0:
print(number, "is an even number.")
else:
print(number, "is an odd number.")

Output
Enter a number: 20
20 is an even number.

Explanation In Detail
In the above code, we have entered an integer number 20 as a user and store it into a variable number. Python evaluates the if conditional expression (number % 2 == 0) to true. Therefore, it executes if block
statement and print the message “20 is an even number”.
Example 2:
Let’s write a Python program in which we will take marks of three subjects from the user and then calculate the total marks, percentage, and grade using if else statement.

chem = int(input('Enter your chemistry marks: '))


phy = int(input('Enter your physics marks: '))
maths = int(input('Enter your maths marks: '))

total = chem + phy + maths


per = total / 3
print("Total marks obtained: ", total)
print("Percentage: ", per)

if per >= 85:


print("Grade A")
else:
print("Grade B")

Output

Enter your chemistry marks: 67


Enter your physics marks: 89
Enter your maths marks: 80
Total marks obtained: 236
Percentage: 78.66666666666667
Grade B

Example 3:
Let’s write the Python code to check whether a number is divisible with another number or not. Print appropriate message on the console.

num1, num2 = 20, 7


if num1 % num2 == 0:
print(num1, "is divisible by", num2)
else:
print(num1, "is not divisible by", num2)

Output
20 is not divisible by 7

Example 4:
Let’s write a Python program to take a number from the user and check whether it is a Buzz number. A number is a buzz number when it ends with 7 or is divisible by 7.

num = int(input('Enter an integer number to check buzz: '))


if (num % 10 == 0) or (num % 7 == 0):
print(num, "is a Buzz number")
else:
print(num, "is not a Buzz number")

Output

Enter an integer number to check buzz: 777


777 is a Buzz number

Example 5:
Let’s write Python code in which we will increment the salary of employee 10% if the salary is greater than 8000. If the salary of employee is less than 8000, will increment 15%.

salary = 7500
if salary >= 8000:
salary = salary + (salary * 0.1)
print("Employee salary: ", salary)
else:
salary = salary + (salary * 0.15)
print("Employee salary: ", salary)

Output
Employee salary: 8625.0

Explanation In Detail
In the above code, the variable salary has initialized with the value 7500. Then, the if else statement will check that the salary is greater than 8000 or not.
If the salary is greater than 8000, it will increment by 10% and display the increment salary on the console. However, if the condition does not satisfy, the else block will execute. In this case, salary will increment
by 15% and display increment salary on the console.
Since the employee’s salary is 7500, which is less than 8000, Python executes else block statements and displays the increment salary.

4. If- elif-else Statement


If elif else in Python is a multi-way decision control statement, which is a combination of if, else if, and else statements.
When we need to choose one of several possible alternatives, we use elif statement along with if statement.
In Python, the keyword elif represents an else-if statement and is useful to avoid excessive indentation.
It allows the programmer to check multiple conditions/expressions for true value and executes a set of code as soon as one of the conditions evaluates to true. Like else, elif statement is also an
optional.
if condition-1:
if block # It will execute if condition-1 is true.
elif condition-2:
elif block # It will execute if condition-2 is true.
elif condition-3:
elif block # It will execute if condition-3 is true.
.....
.....
elif condition-N:
elif block # It will execute if condition-N is true.
else:
else block # It will execute if none of the above conditions is true.

Explanation In Detail
In the above syntax, if, elif, and else are keywords. The condition-1, condition-2 . . . . . condition-N is the boolean expression that returns either true or false. It consists of any relational or logical operators.
There can be only one if statement, and one else statement, however an arbitrary number of elif statements following if statement as per requirement.
The else statement must always come at last and take the default statement. Sometimes, it is also called if-elif-else ladder statement in Python.

Execution Process of If elif else Statement


Python interpreter evaluates a ladder of if-elif-else conditions from top to down. It executes if-elif-else decision control statement as follows:
a) In the if-elif-else structure, the interpreter first evaluates the “if condition-1” to true. If it comes true, Python executes the statements inside if block.

b) If Python “if condition-1” evaluates to false, it tests the “elif condition-2”. If the condition-2 is true, Python executes statements inside the elif block.
c) If the condition-1 and condition-2 are false, Python evaluates condition-3 to true. If it is true, then Python executes statements in the elif block. If it is false, Python checks for the next elif condition-4 and so on.
d) If none of the above conditions is true, the interpreter goes to execute statements inside the else block. If the condition of any ‘if’ or ‘elif’ returns true value, all ‘elif’ and ‘else’ will skip.
e) An if block can have as many elif blocks as needed, but it can have only one else block. However, it is not mandatory for else block to be present.
If else block is absent and none of the above conditions in the ladder are true, the interpreter goes to execute the next statement outside the ladder.

Flowchart Diagram of If-elif-else Ladder Statement


The flowchart diagram for if-elif-else ladder has shown in the below figure.

Example 1:
Let’s write a Python program in which we will take a number from the user and check the number is zero, positive, or negative using if-elif-else ladder.
# This statement takes a number from the user and store it into a variable number.
number = int(input('Enter any number: '))
if number <= -1:
print(number, 'is a negative number.')
elif number == 0:
print(number, 'is a zero number.')
else:
print(number, 'is a positive number.')

Output
Enter any number: 89
89 is a positive number.

Explanation In Detail
In the above example, we have entered a number 89 as a user. Python evaluates the if condition. Since the condition is not true, then Python does not execute statement in the if block and goes to check elif
condition.

As the condition is not true, Python executes the default statement inside the else block and prints the message ’89 is a positive number’.
Example 2:
Let’s write a Python program to find the greater between the two numbers using if elif else ladder.

# These statements take two numbers from the user and store it into variables num1 and num2.
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
if num1 == num2:
print('Numbers are equal.')
elif num1 > num2:
print('First number is greater than second number.')
elif num1 < num2:
print('Second number is greater than first number.')

Output

Enter your first number: 25


Enter your second number: 20
First number is greater than second number.

Example 3:
Let’s write a program in Python to find the greatest among three numbers using if elif else statement.

# These statements take three numbers from the user and store it into variables n1, n2, and n3.
n1 = int(input('Enter your first number: '))
n2 = int(input('Enter your second number: '))
n3 = int(input('Enter your third number: '))
if n1 > n2 and n1 > n3:
print(n1, 'is the greatest number among the three numbers.')
elif n2 > n1 and n2 > n3:
print(n2, 'is the greatest number among the three numbers.')
else:
print(n3, 'is the greatest number among the three numbers.')

Output

Enter your first number: 20


Enter your second number: 15
Enter your third number: 12
20 is the greatest number among the three numbers.

Example 4:
Let’s write a program in Python to take the age of the user as input and find whether he is a child, adult, or senior on the basis of age. Using if-elif-else ladder statement.

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


if age < 18:
print("You are a child")
elif age >= 18 and age <= 60:
print("You are an adult")
elif age >= 60:
print("You are a senior")
else:
print("You have entered an invalid age.")

Output

Enter your age: 68


You are a senior

Example 5:
Let’s write the Python code to enter a character and check it is vowel or consonant.

# Take a single character as input from the user.


ch = input("Enter a single character: ")
if ch == 'a' or ch == 'A':
print(ch, 'is a vowel.')
elif ch == 'e' or ch == 'E':
print(ch, 'is a vowel.')
elif ch == 'i' or ch == 'I':
print(ch, 'is a vowel.')
elif ch == 'o' or ch == 'O':
print(ch, 'is a vowel.')
elif ch == 'u' or ch == 'U':
print(ch, 'is a vowel.')
else:
print(ch, 'is a consonant.')

Output

Enter a single character: A


A is a vowel.

Example 6:
Let’s write the code in Python to check whether it is a Scalene triangle, Isosceles triangle, or Equilateral triangle. Note that:

Scalene triangle: A triangle that has no equal sides is a scalene triangle.


Isosceles triangle: A triangle that has two equal sides is an isosceles triangle.
Equilateral triangle: A triangle that has three equal sides is an equilateral triangle.
# Take the three sides of triangle as input from the user.
sideA = int(input("Enter the side A: "))
sideB = int(input("Enter the side B: "))
sideC = int(input("Enter the side C: "))
if((sideA != sideB) and (sideB !=sideC) and (sideC != sideA)):
print('It is a scalene triangle.')
elif((sideA == sideB) and (sideB == sideC)):
print('It is an equilateral triangle.')
else:
print('It is an isosceles triangle.')

Output
Enter the side A: 5
Enter the side B: 5
Enter the side C: 2
It is an isosceles triangle.
Example Program for Best Practice

Example 7:
Let’s write code in Python to make a simple calculator to find addition, subtraction, multiplication, and division of two numbers. The math calculator menu is as follows:
Math Calculator Menu
––––––––––––––––––

+ => Addition
– => Subtraction
=> Multiplication
/ => Division

print('Math Calculator Menu')


print(' - - - - - - - - - - ')
print('+ => Addition')
print('- => Subtraction')
print('* => Multiplication')
print('/ => Division')

opt = input('Enter an operator [+, -, *, or /]: ')


n1 = int(input("Enter your first number: "))
n2 = int(input("Enter your second number: "))
if(opt == '+'):
sum = n1 + n2
print('Sum of', n1, 'and', n2,'=', sum)
elif(opt == '-'):
sub = n1 - n2
print('Subtraction of', n1,'and', n2, '=', sub)
elif(opt == '*'):
multiply = n1 * n2
print('Multiplication of', n1,'and',n2,'=', multiply)
else:
div = n1 / n2
print('Division of', n1,'and', n2, '=', div)

Output

Math Calculator Menu


----------
+ => Addition
- => Subtraction
* => Multiplication
/ => Division
Enter an operator [+, -, *, or /]: /
Enter your first number: 50
Enter your second number: 5
Division of 50 and 5 = 10.0

Example 8:
Let’s create an application in Python to calculate percentage and grade according to percentage of marks of three subjects. Use Python if-elif-else ladder statement.

# Take marks of three subjects as input from the user.


eng = int(input('Enter the marks of English: '))
sci = int(input('Enter the marks of Science: '))
maths = int(input('Enter the marks of Mathematics: '))
total = eng + sci + maths
per = total / 3
print("Total marks obtained in three subjects: ",total)
print("Percentage: ", per)

if(per >= 90.0):


print("Grade A")
elif(per >= 80.0):
print("Grade B")
elif(per >= 70.0):
print("Grade C")
elif(per >= 60.0):
print("Grade D")
else:
print("Grade F")

Output

Enter the marks of English: 89


Enter the marks of Science: 90
Enter the marks of Mathematics: 99
Total marks obtained in three subjects: 278
Percentage: 92.66666666666667
Grade A

Explanation In Detail
Since the percentage 92.66 is greater than 90, the first condition will be true. Therefore, Python will not go to check other conditions. As the percent 92.66 is greater than 90%, Grade A will display and the rest
of the elif ladder will skip.

5. Nested If-else Statement


When we place an ‘if statement’ inside another ‘if statement’, it is a nested if statement in Python.
It is a very common to use in Python programming. Python nested if statement is useful when we want to check for another condition after a condition evaluates to true.
An inner if statement can also contain another if statement. Indentation plays an important role in figuring out the level of nesting.

# Outer if statement.
if condition-1:
# Inner if statement declared inside the outer if statement.
if condition-2:
statement to be executed when the condition-1 and condition-2 are true.

Explanation In Detail
In the above syntax, if the condition-1 in the outer if statement is true, Python will follow to check another inner if condition-2. If it is true, the statement inside inner if block will execute. Otherwise, the statement
inside inner if block will not execute if the condition-2 evaluates to false.

If condition-1 in the outer if statement is false, Python will not go to check the condition-2 in the inner if statement.
Example 1:

x = 20
y = 10
z=5
# Outer if statement.
if x > y:
if y > z: # Nested inner if statement.
print('Hello')

Output
Hello

Explanation In Detail
In this example, we have placed an if statement inside another if statement to check for another condition. Python first evaluates the condition x > y to true. Since x is greater than y, the condition x > y is true.
Then, Python will check the inner condition y > z to true.
Since y is greater than z, the condition is true. Hence, Python will execute the statement inside inner if block and display the message ‘Hello’.

Example 2:

x = 20
y = 10
z=5
# Outer if statement.
if x > y:
if y < z: # Nested inner if statement.
print('Hello')
print('Hi')

Output
Hi

Explanation In Detail
In this example, Python first check the outer if condition x > y. Since x is greater than y, so the condition is true. Then, Python goes to check the inner condition y < z.
Since the condition is false, therefore, the statement inside the inner if block will not execute. However, the outer if condition is true, so Python will print the message ‘Hi’ on the console because the print
statement belongs to the outer if block.

Nested If else Statement in Python


When we place an ‘if else’ statement inside another ‘if statement’ or ‘if else’ statement, it is called nested if else statement in Python. In fact, we can nest any number of ‘if else’ statement inside one another.

# Outer If else statement.


if condition-1:
statements to be executed if condition-1 is true.
# Inner if else statement.
if condition-2:
statements to be executed when the condition-1 and condition-2 are true.
else:
statements to be executed when the condition-1 is true and condition-2 is false.
else:
statements to be executed when the condition-1 is false.

Example 1:
x = 20
y = 10
z=5
# Outer if else statement.
if x > y:
print('Outer if block')
if y < z: # Nested inner if else statement.
print('Inner if block')
else:
print('Inner else block')
else:
print('Outer else block')

Output

Outer if block
Inner else block

Explanation In Detail
In this example, we have placed an if-else statement inside another if-else statement to check for another condition. The outer if condition x > y evaluates to true. Therefore, Python prints the message ‘Outer if
block’ and skips the execution of outer else block statement.

After checking the outer if condition, Python evaluates the inner if condition y < z. The condition y < z is false, the inner if block will not execute. Python will execute the statement inside the inner else block and
prints the message ‘Inner else block’.

Example 2:
Let’s write a Python program to check whether a number is divisible by 2 and 3.

# Take a number as input from the user.


num = int(input('Enter a number that you want to check divisible: '))
# Outer if else statement.
if num % 2 == 0:
if num % 3 == 0: # Nested inner if else statement.
print('The number is divisible by 2 and 3.')
else:
print('The number is divisible by 2, but not divisible by 3.')
else:
if num % 3 == 0:
print('The number is divisible by 3, but not divisible by 2')
else:
print('The number is not divisible 2 and 3.')

Output

Enter a number that you want to check divisible: 8


The number is divisible by 2, but not divisible by 3.
Enter a number that you want to check divisible: 15
The number is divisible by 3, but not divisible by 2
Enter a number that you want to check divisible: 12
The number is divisible by 2 and 3.
Enter a number that you want to check divisible: 5
The number is not divisible by 2 and 3.

Explanation In Detail
In this example, we have placed two if-else statements inside another if-else statement, one in the if block and another in the else block.

Example 3:
Let’s write a program in Python using nested if else statement to check whether a number is zero, positive, or negative.

num = int(input('Enter a number that you want to check: '))


# Outer if else statement.
if num >= 0:
if num == 0: # Nested inner if else statement.
print('Number is zero.')
else:
print('Number is positive.')
else:
print('Number is negative.')

Output

Enter a number that you want to check: 2


Number is positive.
Enter a number that you want to check: -2
Number is negative.

Explanation In Detail
In this example, Python first tests the expression num >= 0. If it is true, Python follows the inner if condition num == 0 and evaluates to true.

If the inner if condition num == 0 is also true, the inner if block message will display as ‘Number is zero’, otherwise, display as ‘Number is positive’.
Python evaluates the expression num >= 0 to false, it follows its own else block without checking the inner if condition and display as “Number is negative”. This is because the number is neither zero nor positive.

Example 4:
Let’s write a program in Python using nested if statement, check the following:

If age < 18; display ‘You are minor and not eligible to cast vote.’
If age >= 18 and age < 60; display ‘You are young and eligible to cast vote.’
Otherwise, display ‘You are a senior citizen person and will be given special care to cast vote.’
age = int(input('Please enter your age: '))
# Outer if else statement.
if age < 18:
print('You are minor and not eligible to cast vote.')
else:
if age >= 18 and age < 60:
print('You are young and eligible to cast vote')
else:
print('You are a senior citizen person and will be given special care to cast vote.')

Output

Please enter your age: 17


You are minor and not eligible to cast vote.
Please enter your age: 42
You are young and eligible to cast vote

Explanation In Detail
In this example, we have nested else block by placing another if-else statement inside the else block. If Python evaluates the if condition (age < 18) to true, the statement inside the if block will execute and else
block of if part will not execute.
If Python evaluates to false, else block of if part will execute. Inside the else block, Python will check the inner if condition (age >= 18 and age < 60) to true.
If the condition is true, if block statement will execute otherwise, else block statement will execute.

Example 5:
Let’s write a program in Python to check whether a year is a leap year.

# Program to check a year is leap year or not.


year = int(input('Please enter a year: '))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year,'is a leap year.')
else:
print(year,'is not a leap year.')
else:
print(year,'is a leap year.')
else:
print(year, 'is not a leap year.')

Output

Please enter a year: 1968


1968 is a leap year.
Please enter a year: 2024
2024 is a leap year.
Please enter a year: 2023
2023 is not a leap year.

Explanation In Detail
In this example, we have checked many leap years using nested if statement. A year which is perfectly divisible by 4 is leap years. For example, years such as 2024, 2012, 2004, 1968, etc. are leap years.
Century year ending with 00 is a leap year when it is divisible by 400. For example, 2000, 1200, 1600, 2400, etc. are leap years but 1700, 1800, 1900, etc. are not leap years.

Nested If-elif-else Statement in Python


When we place an ‘if elif else’ statement inside another ‘if elif else’, then it is called nested if elif else statement in Python. We can nest any number of these statements inside one another.
The general syntax to nest if-elif-else statement inside another if-elif-else statement is as follows:

# Outer if-elif-else statement.


if condition-1:
statement to be executed when the condition-1 is true.
# Inner if-elif-else statement.
if condition-2:
statement to be executed when the condition-1 and condition-2 are true.
elif condition-3:
statement to be executed when the condition-1 is true and condition-3 is true.
......
else:
statement to be executed when the condition-1 is true and none of the above is true.
# Outer elif statement.
elif condition-4:
statement to be executed when the condition-1 is false and condition-4 is true.
# Outer else statement.
else:
statement to be executed when the condition-1 and condition-4 are false.

Example 1:
Let’s write a program in Python to make a simple calculator to calculate the addition, subtraction, multiplication, and division of two numbers. Take two numbers as input from the user.

# Program to make a simple mathematical calculator.


opr = input('Please enter an operator [+, -, *, or /]: ')
if(opr == '+' or opr == '-' or opr == '*' or opr == '/'):
n1 = int(input('Please enter your first number: '))
n2 = int(input('Please enter your second number: '))
if(opr == '+'):
sum = n1 + n2
print("Sum of",n1,'and', n2,'=', sum)
elif(opr == '-'):
if(n1 > n2):
diff = n1 - n2
else:
diff = n2 - n1
print('Difference between',n1,'and',n2,'=', diff)
elif(opr == '*'):
multiply = n1 * n2
print('Multiplication of',n1,'and',n2,'=', multiply)
elif(opr == '/'):
if(n1 == 0 or n2 == 0):
print('Numbers must be positive.')
else:
div = n1 / n2
print('Division of',n1,'by',n2,'=', div)
else:
print('Sorry, you have entered an invalid operator. Please choose any of these +, -, *, or /.')

Output

Please enter an operator [+, -, *, or /]: +


Please enter your first number: 20
Please enter your second number: 50
Sum of 20 and 50 = 70

Please enter an operator [+, -, *, or /]: /


Please enter your first number: 50
Please enter your second number: 10
Division of 50 by 10 = 5.0

6. Loops
A loop in Python is a control structure that repeatedly executes a statement or a group of statements until a specific condition is true.
In other words, a loop is a control flow statement that allows the repetitive execution of a statement or group of statements repeatedly until a termination condition met. It facilitates the complicated execution
paths easy.
Looping is also called a repetition structure in Python. The block of code can execute many times from zero to infinite number depending on the need.
One complete execution of all statements within a loop is called iteration in Python.
A loop simply tells the Python interpreter to execute a bit of code multiple times if the condition is true and exits the loop when the condition becomes false.

Loop Control Structure in Python


A block of code runs sequentially in the loop until a specific condition for the termination of the loop met. In Python, a loop control structure comprises two parts:

Control statement
Body of the loop
The function of a control statement is to test or evaluate a given condition, also called boolean expression, before the execution of body of the loop. If the given condition satisfies, then the body of loop will
execute.
As long as the test condition evaluates to true, the statements in the loop body continue to execute. If not satisfied, then the body of loop will not execute. This type of loop is called an entry-controlled loop.
The general flowchart diagram for loops in Python is as below:

In all types of entry-controlled loops, there is a control variable called loop counter. You must initialize it with an initial value. The increment or decrement of the control variable modifies each time the iteration of
loop occurs. The loop condition or expression determines the continuation of loop body.

Steps to Process Loops in Python


Basically, there are four steps to process loops in Python. They are as:

Setting and initialization of a control variable.


Execution of statements sequentially in the loop body.
Evaluation of a specified condition for the execution of statements inside the loop body.
Incrementing or decrementing of the counter.
Types of Loops (Iterations) in Python
Python programming language supports four types of loops to handle the loop operations. They are:

for loop
while loop
nested loops
infinite loops

Explanation In Detail
♦ The while loop is an entry-controlled loop statement that executes a statement or a group of statements inside the loop body repeatedly as long as the conditional expression evaluates to true.
It evaluates the conditional expression each time it executes the loop body and exits the loop when the conditional expression becomes false.
♦ A for loop is an entry-controlled loop statement that executes a statement or a group of statements a certain number of times.
♦ When we place a loop inside another, then it is called nested loops in Python. It allows us to loop over two variables. The outside loop is an outer loop, while the inside loop is an inner loop.
♦ An infinite loop is a loop statement that repeats forever. We also known it as endless loop because the specified condition is always true and the loop body executes repeatedly as long as the program is
running, and never ends.

7. While Loop
While loop in Python is the most fundamental loop statement that repeatedly executes a statement or a group of statements, as long as the specified test condition or expression evaluates to true.
In other words, a while loop repeats the body of the loop as long as a given condition is true.
It evaluates the condition each time it executes the loop body, and it exits the loop when the condition becomes false.
Each repetition of the body of loop is called iteration of loop.
Python while loop is the simplest of all the looping structures. It is an entry-controlled loop statement.
In the entry-controlled loop, Python first evaluates the test condition. If the specified condition is true, then the loop body executes.
If the condition is false, then the loop body does not execute. In this way, the while loop statement executes a block of code repeatedly while the test condition is true.
You can use the while loop statement in Python when you don’t know how many times you want to repeat the code.

Initialization
while test condition:
# Loop body
statement(s)

Explanation In Detail
In the above syntax, the while loop starts with a while keyword that creates a loop. It is followed by test condition or expression, then a colon (:) character.
The test condition or expression consists of boolean expression that produces either true or false value depending on the counter control variable. A while loop doesn’t have a loop variable that sets a range of
values. It has a loop condition.
In the syntax, statement(s) may be a single statement or a group of statements with uniform indentation.

While Loop working Flow in Python


1. Python first evaluates the test condition or expression in the while() loop before the execution of statements in the while loop block.
2. When the test condition is true, then the loop body (i.e. a block of statements) executes. After the execution of loop body, the test condition once again evaluates to true.
3. If the specified condition is true, the loop body executes once again. This process of repeated execution of loop body continues by the Python interpreter until the condition or expression finally becomes false.
4. Once the test condition is false, the loop terminates and the program control immediately transfers out of the loop.
5. On exit, the program continues to execute the next statement immediately after the while loop. Each execution of the loop body refers to as an iteration (or repetition) of loop.

The flowchart for while loop in Python has shown in the below diagram.
# Initialization: The variable count has defined outside the loop and will update inside the loop.
count = 0
# Declare the while loop statement.
# Loop continuation condition expression that must ends with a colon (:).
while count < 5:
# Body of the loop.
print('Hello Python') # This statement will execute as long as the condition is true.
count += 1 # It counts the number of executions, and increments count by 1.
print('Loop finished.') # Continue program if the condition is false.

Explanation In Detail
Here, the body of loop will execute 5 times for count = 0, 1, 2, 3, 4. Each time a statement “Hello Python” will print on the console.
When the count is equal to 5, the condition becomes false and the loop ends. The program control will transfer out of the loop to execute the rest of the code inside the program.
In the above example, count is a control variable that controls the number of executions. It increments by 1 after each repetition or loop. This kind of loop is called counter-controlled loop in Python.

Example 1:
Let’s write a simple Python program to print the first 5 natural numbers by using while loop statement.

# Program to display numbers from 1 to 5.


i = 1 # Initialization.
while i <= 5:
print('Current value of i is ',i)
i = i + 1 # Increment by 1.

Output

Current value of i is 1
Current value of i is 2
Current value of i is 3
Current value of i is 4
Current value of i is 5

Explanation In Detail
In this example, we have assigned the value 1 to the variable i. The while loop block consists of print and increment statements and executes repeatedly until the variable i is greater than 5.
With each iteration, the current value of i is printed and then increased by 1. This process continues until the condition in the while statement evaluates to false.

Example 2:
Let us write a program in Python to print your name five times using while loop.

# Program to display your name five times.


i = 0 # Initialization.
name = input('Enter your name: ')
while i < 5:
print(name)
i = i + 1 # Increment by 1.

Output

Enter your name: Tripti


Tripti Tripti . . Tripti

Example 3:
Let’s write a Python program to display numbers from 5 to 1 by using while loop statement.

# Program to display numbers from 5 to 1.


i = 5 # Initialization.
while i >= 1:
print(i)
i = i - 1 # decrement by 1.
print('Loop finished')

Output

54321
Loop finished

Explanation In Detail
In the preceding example, the while loop prints number starting from 5 and going down to 1, until the specified condition i >= 1 evaluates to true. As the value of i is less than 1, the condition is false and the loop
ends.

Example 4:
Let us write a program to calculate the average of n natural numbers where n is an input taken from the user.
# Program to display the average of n natural numbers.
num = int(input('Enter a number up to which you want to calculate average: '))
i= 0
sum = 0
count = 0 # Initialization.
while i < num:
i = i + 1 # Increment by 1.
sum = sum + i
count = count + 1
average = sum / count
print('Average of', num,'natural numbers = ', average)
Output

Enter a number up to which you want to calculate average: 5


Average of 5 natural numbers = 3.0

Explanation In Detail
In this example, we have assigned the variable i, sum, count with a value 0. Python evaluates the expression i < num. Since it is true for the first iteration, the body of while loop executes.
The variable i increments by the value of 1 and it produces the required natural numbers. Variable sum adds the value of sum with the value of i. The variable count keeps the track of number of times the loop
body gets executed.
Python repeats the loop until the test expression becomes to false. We calculated the average as sum/count and printed it on the console.

Example 5:
Let us write a program to calculate the sum of first 10 natural numbers using while loop. That is, 1 + 2 + 3 + . . . + 10 = 55.

# Program to display the sum of first 10 natural numbers.


sum = 0
count = 0 # Initialization.
while count <= 10:
sum = sum + count
count = count + 1
print('Sum of 10 natural numbers = ', sum)

Output
Sum of 10 natural numbers = 55

Example 6:
Let’s write a program in Python to find the sum of digits in a number.

# Program to display the sum of digits in a number.


num = int(input('Enter a number: '))
sum = 0
remainder = 0
while num != 0:
remainder = num % 10
sum = sum + remainder
num = int(num / 10)
print('Sum of all digits in number = ', sum)

Output

Enter a number: 123456


Sum of all digits in number = 21

Explanation In Detail
In this example, we have used a function named input() to read an integer number from the user and stored it in a variable num. We have assigned the variables sum and remainder with value 0.

Then, we need to calculate the last digit of the number. To get the last digit of a number, we have used the modulus division by 10 and assigned it in the variable remainder.
Now we have added the obtained last digit with the sum variable. We removed the last digit from the number by dividing the number by 10 and cast it as int. This logic will continue until the variable num becomes
0. Finally, we will get the sum of digits in a variable sum.

Example 7:
Let’s write a program in Python to calculate the GCD of two positive numbers.
# Program to find the GCD of two +ve numbers.
n1 = int(input('Enter the first positive number: '))
n2 = int(input('Enter the second positive number: '))
if(n1 == 0 and n2 == 0):
print('Invalid input')
if(n1 == 0):
print('GCD = ',n2)
if(n2 == 0):
print('GCD = ',n1)
while(n1 != n2):
if(n1 > n2):
n1 = n1 - n2
if(n2 > n1):
n2 = n2 - n1
print('GCD of two numbers = ',n1)
Output

Enter the first positive number: 8


Enter the second positive number: 12
GCD of two numbers = 4

Explanation In Detail
In this program, we have read two numbers using the function input() from the user and stored them into variables n1 and n2. We have used if statement to check the conditions.
If both n1 and n2 are zero, it is invalid input because zero cannot be divided by zero, which is indeterminate. If n1 or n2 is zero, the other one is gcd.
When the value of n1 > n2, then n1 = n1 – n2, or n2 > n1, then n2 = n2 – n1. This logic will continue repeatedly until the value of n1 is equal to the value of n2. Finally, the GCD will be n1.

Example 8:
Let’s write a program in Python using while loop to find the Fibonacci series of numbers till 30. The Fibonacci series is: 0, 1, 1, 2, 3, 5, 8, 13, . . . .

# Program to find the Fibonacci series of numbers till 30.


num1 = 0
num2 = 1
print('Fibonacci series of numbers till 30 are: ')
print(num1, num2, end = ' ')
while num2 < 21:
num1, num2 = num2, num1 + num2
print(num2, end = ' ')

Output

Fibonacci series of numbers till 30 are:


0 1 1 2 3 5 8 13 21

Example 9:
Let’s write a program in Python using while loop to display the following pattern.
*****
****
***
**
*

# Program to print pattern.


nrows = int(input('Enter the number of rows: '))
while nrows >= 0:
x = '* ' * nrows
print(x)
nrows = nrows - 1

Output

*****
****
***
**
*

Example 10:
Let’s write a program in Python to display the following pattern using while loop statement.
*
**
***
****
*****

# Program to print pattern.


nrows = int(input('Enter the number of rows: '))
n=1
while n <= nrows:
x = '* ' * n
print(x)
n=n+1

Output

*
**
***
****
*****

Example 11:
Let’s write a program in Python using the while loop to display the mathematical table of an input number.

# Program to print table of an input number.


num = int(input('Enter a number to find table: '))
count = 1
t=1
while count <= 10:
t = num * count
print(num,'*',count,'=',t)
count = count + 1
Output

Enter a number to find table: 5


5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20

8. For Loop
For loop in Python is a basic conditional looping structure that executes a statement or a block of statements a certain number of times.
We use a for loop in the program when we know exactly how many times we have to repeat a loop.

for iterating_var in sequence:


statement(s)

In the above syntax, the for loop starts with for keyword and ends with a colon (:) character. The iterating_var after for keyword is a loop variable that keeps the track of how many times the loop has to run so
far.
The block of statements that gets repeated in a loop is called the loop body. It may contain any sequence of Python statement. You must follow the indentation in the body with four spaces from the beginning of
the line that begins the for loop.

For loop Working Flow in Python


a) The first element in the sequence gets assigned to the iteration variable called iterating_var. After that, the statement block (i.e. loop body) executes.
b) Assigning elements from the sequence to the iterating_var and then executing the statement block continues until all the elements in the sequence execute.
The flowchart diagram of a for loop statement has shown in the below figure.

If the sequence contains an expression list, Python first evaluates it. If it is true, then the Python assigns an element from the sequence to the iterating_var. Next, the block of statement executes.

Example 1:

# Program to print the statement two times.


for count in 1, 2:
print('I love to code in Python')

Output

I love to code in Python


I love to code in Python

Explanation In Detail
In this example, Python first assigns the first item 1 from the sequence to the iteration variable count, like count = 1. Then, it executes the statement inside the block of for loop.
Similarly, Python assigns the second item 2 to the iteration variable count, like count = 2, and then again executes the statement inside the for loop body. Thus, the interpreter displays the statement ‘I love to code
in Python’ two times on the console.
Example 2:

# Program to print the sequence.


for count in 1, 2, 3, 4:
print('count = ',count)

Output

count = 1
count = 2
count = 3
count = 4
For Loop with range() Function in Python
Python provides a very useful in-built function named range(). It allows us to define a set of numbers over which the ‘for loop’ iterates the numbers in sequential order.
In other words, the range() function produces a sequence of values which can be iterated through using for loop. The general syntax for range() function is as:
range([start], stop [, step])

Explanation In Detail
Here, both start and step arguments are optional and the range of argument values must be an integer value.
start: This argument value indicates the starting of the sequence. If you do not specify the start value, then the sequence of numbers starts from the zero by default.
stop: The stop value produces numbers up to this value, but does not include the number itself. That is, the range of numbers is 0 to n-1. For example, range(1, 4) means the number 1, 2, and 3 but not 4.
step: The step value indicates the difference between every two consecutive numbers in the sequence. It can be both negative and positive, but not zero. However, it is optional.

Example 1:

print('Only stop argument values specified in the range function: ')


for x in range(3):
print(x)
print('Start and stop argument values specified in the range function: ')
for x in range(2, 5):
print(x)
print('Start, stop, and step argument values specified in the range function: ')
for x in range(1, 9, 3):
print(x)

Output

0
1
2
Start and stop argument values specified in the range function:
2
3
4
Start, stop, and step argument values specified in the range function:
1
4
7

Explanation In Detail
In the above Python code, the function range(3) produces numbers 0, 1, and 2. During the first iteration, Python assigns the value 0 to the iteration variable x and executes the statement inside the for loop block.
This process continues to execute until Python assigns all the numbers generated by the range() function to the variable x. The function range(2, 5) generates a sequence of numbers 2, 3, and 4.
The function range(1, 9, 3) generates a sequence of numbers 1, 4, and 7 with the difference between each number 2.

Example 2:
Let’s write the Python code to calculate the sum of numbers from 1 to 10.

sum = 0
for num in range(1, 11):
sum = sum + num
print('Sum of numbers between 1 to 10 = ',sum)

Output
Sum of numbers between 1 to 10 = 55

For loop with String in Python

Example
Let’s write a Python program to iterate over each character in the string using for loop conditional statement.

for ch in 'Python':
print('Current character is ',ch)

Output

Current character is P
Current character is y
Current character is t
Current character is h
Current character is o
Current character is n

Explanation In Detail
In this example, we have created an iteration variable ch that iterates through each character of the string and prints each character in the separate line.

For loop with List in Python

A list is a collection of elements or items. We can use for loop to iterate over the elements of a list.
Example
There is a list of fruit items we will iterate it.

fruits = ['Apple', 'Banana', 'Orange', 'Mango']


for item in fruits:
print(item)
print('Loop finished...')

Output

Apple
Banana
Orange
Mango
Loop finished...

Explanation In Detail
In this example, we have created an iteration variable called item that holds a single item in the list. The value of variable item is updated each time when the loop iterates over the elements of list.

Thus, the variable item holds Apple, Banana, Orange, and finally Mango. Once it reaches at the end of list, the for loop stops.

For loop with a Tuple


Let’s write a Python program to iterate through each item in the tuple using for loop.

color = ('Red', 'Green', 'Blue', 'Orange')


for item in color:
print(item)
print('Loop finished...')

Output

Red
Green
Blue
Orange
Loop finished...

Else Statement with For loop in Python


Python supports having an else statement associated with a for loop. If we use an else block with a for loop, the else block will execute only if the loop ends normally, not by encountering a break statement.
Consider the following example code in which we have used an else block with for loop that searches for an even number in the given list.

num = [3, 5, 7, 9, 11]


for n in num:
if n % 2 == 0:
print('List contains an even number.')
else:
print('List does not contain any even number.')

Output
List does not contain any even number.

Explanation In Detail
As you can see, that else block is executed when the loop has stopped iterating the list. Since there is no any even number in the list, therefore, statement inside the else block executes.

Example 1:
Let’s write a program in Python to calculate the sum of all even and odd numbers up to a number entered by the user.

num = int(input('Enter a number: '))


even = 0
odd = 0
for x in range(num):
if x % 2 == 0:
even = even + x
else:
odd = odd + x
print('Sum of even numbers = ',even)
print('Sum of odd numbers = ',odd)

Output
Enter a number: 10
Sum of even numbers = 20
Sum of odd numbers = 25

Explanation In Detail
In this example, we have generated a range of numbers using range() function. We have used the modulus operator to check even or odd numbers.
Then, we added up all even numbers and assigned to the variable even. Similarly, we added up all odd numbers and assigned to the variable odd. Then, we printed the result on the console.
Example 2:
Let’s write a program in Python to find the factorial of a number entered by the user.

# Python program to find the factorial of a number.


num = int(input('Enter a number: '))
fact = 1
if num < 0:
print('Please enter a positive number because factorial does not exist for negative number.')
elif num == 0:
print('The factorial of 0 is 1.')
else:
for x in range(1, num + 1):
fact = fact * x
print('The factorial of number', num,'=', fact)

Output

Enter a number: 6
The factorial of number 6 = 720

Explanation In Detail
The factorial of a positive integer number n is denoted by n! which is the product of all positive integers less than or equal to n. i.e. n! = n * (n – 1) * (n – 2) * (n – 3) . . . 3 * 2 * 1. For example, 6! = 6 * 5 * 4 *
3 * 2 * 1 = 720. The factorial of 0! is always 1.
In the above code, first we have used the input() function to take a number from the user. Then, we have cast the entered number to int and stored it into a variable num.
We have assigned the value 1 to the variable fact. To find the factorial of a number, we need to check the entered number is positive or negative.
If the user enters a zero, then the factorial of zero is always 1. We have used the range() function to produce to numbers from 1 to the user entered number.
Every number will be multiplied by the fact variable and is assigned to the fact variable itself within the for loop. The for loop will iterate over all numbers starting from 1 to the user entered number. At last, the
final factorial value is printed on the console.

Example 3:
Let’s write a program in Python to print a list of numbers in reverse order using for loop.

# Python program to print a list of numbers in reverse order.


nlist = [2, 4, 6, 8, 10, 12]
print('List of original numbers: ')
for x in nlist:
print(x, end= ' ')
num = len(nlist) # Here, function len() returns the number of items in the container.
i= 0
j = -1
print('\nList of numbers in reverse order: ')
while i <= num - 1:
print(nlist[j], end=' ')
j -= 1
i += 1

Output

List of original numbers:


2 4 6 8 10 12
List of numbers in reverse order:
12 10 8 6 4 2

9. Nested Loops
Nested loops in Python mean one loop inside another loop. Like nested if, Python allows us to place one loop inside another loop.
When we put one or more complete loop(s) within the body of another loop, then we call it as nested loops.
We can place many loops within a loop. But, it is advice that you do not go beyond three levels of nested loops, as it will make the program look clumsy.
In Python, we can construct a nested loop by using while, or for loop statement, or with their combinations.

Nested For loops in Python


When we place a for loop inside another for loop, it is called nested for loops. A nested for loops comprises an outer for loop and one or more inner for loops.
Both for loops execute depending on its test conditional expression. Each time the outer for loop repeats its execution, the program control re-enters inside the inner for loop and starts a new execution.
That is, each time the program control will enter inside the inner for loop when the outer for loop repeats the loop. When the inner for loop completes its execution, then it ends and then the outer for loop ends.

# Outer for loop


for iterating_var in sequence:
statement-1 # Outer block statement.
# Inner for loop
for iterating_var in sequence:
statement-2 # Inner block statement.
statement-3 # Outer block statement.
statement-4

Example

# Outer for loop.


for x in 1, 2:
print('Value of x = ',x) # It will execute two times.
# Inner for loop.
for y in 1, 2:
print('Value of y = ',y) # It will execute four times.
print('Nested loops ends here...')

Output
Value of x = 1
Value of y = 1
Value of y = 2
Value of x = 2
Value of y = 1
Value of y = 2
Nested loops ends here...

Explanation In Detail
a) In this example, the execution will start from the outer for loop. Python first assigns the value 1 to the iteration variable x and prints the value of x on the console.
b) Now, the program control enters the inner for loop. During the first iteration, Python assigns the value 1 to the iteration variable y and prints the value of y on the console.
Similarly, for the second iteration, Python assigns the value 2 for the iteration variable y and prints the value of y.
c) After the complete iteration of the inner loop, Python assigns the value 2 to the iteration variable x and prints the value of x on the console.
d) Then, the program control enters to the inner loop for the second iteration. Now, Python starts the iteration by assigning the value 1 to the iteration variable y and prints the value of y on the console.
e) Similarly, Python assigns the value 2 to the iteration variable y and displays the value of y.
Thus, the values of x and y will change like this:
When x = 1, y = 1, 2
When x = 2, y = 1, 2

In the above sequence, the outer for loop will execute a total 2 times, and the statement inside the loop body will execute 2 times. But, the inner for loop will execute 2 times for each x value and hence the
statement inside the loop body will execute 4 times.
Nested While loops in Python
Like nested for loop, when we place a while loop inside another while loop body, then we call it as a nested while loop statement.

while test_condition-1: # Outer while loop


statement(s)
while test_condition-2: # Inner while loop
statement(s)
statement(s)
statement(s)

Example

x = 1 # Initialization for outer while loop.


y = 1 # Intialization for the inner while loop.
# Outer while loop.
while x < 3:
print('Outer while loop') # This statement will execute two times.
# Inner while loop.
while y < 3:
print('Inner while loop') # This statement will execute two times for the first outer loop.
y=y+1
x=x+1
print('Nested while loops end here...')

Output

Outer while loop


Inner while loop
Inner while loop
Outer while loop
Nested while loops end here...

Explanation In Detail
a) In this example, initially, the counter variable x and y set with the value 1.
b) Python first evaluates the outer while loop condition x < 3 to true. Since the condition x < 3 is true, the statement inside the outer while loop executes.
c) The program control enters to the inner while loop and checks the condition y < 3. Since it is true, the statement inside the inner while loop executes. Then, the value of y increments by 1.
d) Now Python again checks the condition y < 3. Since the value of y is less than 3, the statement inside the inner for loop again executes. Then, the value of y again increments by 1.
e) Since the inner while loop condition is now false, the program control comes outside the inner while loop, and increments the value of x by 1.
f) Now, Python again evaluates the outer while loop condition x < 3 to true. Since it is true, the statement inside the outer while loop again executes. But, the program control does not enter the inner while loop
statement because the condition y < 3 is false.
g) Once the Python evaluates the outer while loop condition to false, the program control comes outside the outer while loop and executes the next statement that follows it.

Flowchart Diagram of Nested loops

The general flowchart for nested loops in Python has shown in the below figure.

As you can see in the flowchart diagram of nested loops, when the outer loop condition is true, the program control enters to the inner loop and checks the condition.
If the inner loop condition evaluates to true, the block of statements inside the inner loop executes. If the inner loop condition evaluates to false, the program control goes to execute the statements inside the outer
loop body.
After the complete execution of the outer loop body, the outer loop condition again checked. This process continues until the outer loop condition is false.

Example 1:
Let’s write a program in Python to print a table of 2 using nested for loops.

# Outer for loop.


print('Math table of 2: ')
for x in range(2, 3): # This loop will only repeat 1 time.
for y in range(1, 11): # Inner for loop will repeat 10 times.
t=x*y
print(x,'*',y,'=',t)
print()
print('Nested for loops ends here...')

Output
Math table of 2:
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Nested for loops ends here...

Example 3:
Let’s write a program in Python to print multiplication tables from 1 to 5 using nested for loop.

# Outer for loop.


print('Multiplication tables from 1 to 5: ')
for x in range(1, 6):
for y in range(1, 11): # Inner for loop.
t=x*y
print(t, end=' ')
print()
print('Nested for loops ends here...')

Output

Multiplication tables from 1 to 5:


1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
Nested for loops ends here...

Explanation In Detail
In this example, we have used end=’ ‘ in the print function that adds a space instead of default newline. Hence, the numbers will look in one row. The last print() function will execute at the end of the inner for
loop.

Example 4:
Let’s write a Python program to display a triangle of * using nested for loop.

# Outer for loop.


print('Displaying a triangle of *: ')
for x in range(1, 6):
for y in range(1, x + 1): # Inner for loop.
print('* ',end='')
print()
print('Loops end here...')

Output

Displaying a triangle of *:
*
**
***
****
Loops end here...

Example 5:
Let’s write a Python program to display a triangle of numbers.

# Outer for loop.


print('Displaying a triangle of numbers: ')
for x in range(1, 6):
for y in range(1, x + 1): # Inner for loop.
print(y,' ',end='')
print()
print('Loops end here...')

Output

Displaying a triangle of numbers:


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Loops end here...

Example 6:
Let’s create a program in Python to display a right triangle pattern of numbers.

print('Displaying a right triangle pattern of numbers: ')


z=1
for x in range(1, 6):
for y in range(1, x + 1): # Inner for loop.
print(z,' ',end='')
z += 1
print()
print('Loops end here...')

Output

Displaying a right triangle pattern of numbers:


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Loops end here...

Example 7:
Let’s create a program in Python to display the following number pattern.
12345
1234
123
12
1

# Outer for loop.


for x in range(6, 1, -1):
for y in range(1, x): # Inner for loop.
print(y,' ',end='')
print()
print('Loops end here...')

Output

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Loops end here...

Example 8:
Let’s write Python code to print the following alphabet pattern using nested for loops.
A
AB
AB C
AB C D
AB C D E

print("Displaying a right triangle of characters ")


# Outer for loop.
for x in range(65, 70):
for y in range(65, x + 1): # Inner for loop.
print(chr(y),' ',end='')
print()
print('Loops end here...')

Output
Displaying a right triangle of characters
A
A B
A B C
A B C D
A B C D E
Loops end here...

Example 9:
Let’s create a Python program to display a reverse right triangle of alphabet characters pattern using nested for loops.
AB C D E
AB C D
AB C
AB
A

print("Displaying a reverse right triangle of characters ")


# Outer for loop.
for x in range(70, 65, -1):
for y in range(65, x): # Inner for loop.
print(chr(y),' ',end='')
print()
print('Loops end here...')

Output
Displaying a reverse right triangle of characters
A B C D E
A B C D
A B C
A B
A
Loops end here...
10. Infinite Loop
An infinite loop (also called endless loop) in Python is a sequence of statements in a program which executes endlessly.
It occurs when the loop condition always evaluates to true. In other words, a loop becomes an infinite loop if a loop condition never becomes false.
Usually, it is an error in the program when an infinite loop occurs. This is because it takes place only when there is some logical disconnection between the loop body (program code) and the test condition.
Example

count = 1
while count == 1: # Creates an infinite loop.
num = int(input('Enter a number: '))
print('Your entered number = ',num)
print('Good bye!')

In this example, we have assigned the value 1 to the variable count. The count variable does not increment its value and continuously executing statements because the condition always produces the true result.

Look at the flowchart diagram of this program.

When you will run the above program code, it produces the following result:
Output
Enter a number: 29
Your entered number = 29
Enter a number: 30
Your entered number = 30
Enter a number: t
Traceback (most recent call last):
File "C:\Python Project\InfiniteLoop.py", line 3, in
num = int(input('Enter a number: '))
ValueError: invalid literal for int() with base 10: 't'

11. Break Statement


A break statement in Python is a loop control statement that ends the present loop statement and instructs Python to execute the next statement immediately following the loop.
It provides a greater control over the execution of statements in a loop.
When Python encounters a break statement inside a loop body, the loop immediately ends at a specified condition if the test condition is true.
Python then transfers the control to execute the next line of code (if any) immediately outside the loop, even if the loop condition has not become false or the sequence of elements has not been completely iterated
over.
We can use the break statement in all types of loops, such as for loop, while loop, and nested loops.

# Jump statement
break;

The flowchart diagram of break statement in Python has shown in the below figure.

From the above flowchart diagram, it is clear that if the Python evaluates the test condition within a loop to true, then the loop ends immediately and the execution control jumps to the next statement following the
loop.
Use of Break Statement in Python
There are three important uses of break statement in Python programming language that is as:
1. We can use the break statement inside the loop body to come out of it. Look at the below figure to understand clearly.

2. We can also use it inside the nested loops. In nested loops, a break statement ends the innermost loop and instructs the Python to execute the statement that follows the immediately terminated block.

3. A break statement is commonly used to prevent the execution of the else statement.
Example 1:
Let’s take a simple program in which we will use a break statement inside the for loop for breaking the loop.

# Use of break statement inside the for loop.


for x in range(1, 11):
if x == 5:
break # Breaking a loop.
print("X = ",x)

Output

X= 1
X= 2
X= 3
X= 4

Explanation In Detail
In the above code, when x == 5, then the for loop automatically breaks. Therefore, the program only prints the current values from 1 to 4.

Example 2:
Let’s write a program in which we will use break statement inside while loop to exit from loop.

# Use of break statement inside the while loop.


i= 1
while i <= 10:
if i == 5:
break # Breaking a loop.
print("I = ",i)
i= i+ 1

Output
I = 1
I = 2
I = 3
I = 4

Example 3:
for letter in 'Python':
if letter == 't':
break
print('Current letter is ',letter)

Output
Current letter is P
Current letter is y

Example 4:
Let’s write a program in which we will use break statement inside the inner for loop to exit from loop.

# Use of break inside the inner for loop.


# Outer for loop.
for x in range(1,4):
for y in 0, 1, 2, 3: # Inner for loop.
if(x == 2 and y == 2):
break # Using break statement inside inner for loop.
print(x,y)

Output

10
11
12
13
20
21
30
31
32
33

12. Continue Statement


Continue in Python is a loop control statement similar to the break statement.
It breaks the current execution (iteration) of loop and transfers the program control back to the beginning of the loop for the next execution without exiting the loop.
In other words, the continue statement tells the Python to stop the current execution of loop and to begin a new execution of loop.
When the continue statement encounters in a loop, the remaining statements in the current iteration skips (i.e. not executed) in a specified condition, and the control of execution continues with the next repetition
of the loop.
In simple words, when encountered, the control jumps to the beginning of the loop without executing the remaining statements in the current iteration and continues with the next iteration.
We can use continue statement in both while and for loops.

Example

for letter in 'Technology':


if letter == 'n':
print('Skipping the loop at', letter)
continue
print(letter)

Output

T
e
c
h
Skipping the loop at n
o
l
o
g
y

As you can see in the above output, the continue statement does not break out of the loop entirely. It just jumps back to the beginning of the loop by skipping the rest of code in the loop body for the next
iteration without exiting the loop.

Look at the below figure to understand more clearly the continue statement in the for loop.

Flowchart Diagram of Continue Statement in Python


Look at the below flowchart diagram of the continue statement in Python.
Example 1:
Let’s write a program in Python to use the continue statement inside the for loop.

for x in range(1, 6):


if x == 3:
print('Continue without 3')
continue # It will skip the rest iteration and go back in the for loop with the next iteration.
print(x)

Output

1
2
Continue without 3
4
5

Explanation In Detail
As you can see in the output, 3 is not displayed on the console because when x == 3, the loop is continued and redirected to the control of execution back to the next iteration of the loop. As a result, the value 3
of x will not print.

Example 2:
Let’s write a program in Python to use the continue statement inside the while loop.

# Displaying numbers using continue statement.


# while loop.
x = 1 # Initialization.
while x <= 6:
if x == 3:
x=x+1
continue
print(x)
x=x+1

Output

1
2
4
5
6

Explanation In Detail
As you can see in the output, the number 3 is skipped when x is equal to 3.

Example 3:
Let’s write a program to use the continue statement inside the nested for loop.

# Outer loop.
for x in range(1, 4):
# Inner loop.
for y in range(1, 4):
if x == 2 and y == 3:
continue # continue statement inside the inner for loop.
print(x,y)

Output

11
12
13
21
22
31
32
33
Example 4:

for x in range(1, 7):


if x < 2:
continue
print(x)
if x < 4:
continue
print(10 * x)

Output

2
3
4
40
5
50
6
60

Explanation In Detail
In this program code, we have created a loop that iterates the value of variable x from 1 to 6. If x is less than 2, then the loop is continued and do nothing.
Once x is 3 or higher, Python prints the values. Once x is greater than 5, Python prints 10 * x. So, the above program code will print the values as shown in the output.

Difference between Break and Continue in Python


Both break and continue are loop control statements that change from its normal sequence. We can use both in for, while, and nested loops. But there are also a few basic differences between them. They are as
follows:
1. Break statement is used to terminate or break the loop, whereas continue statement is used to escape from the current iteration.
2. Break statement transfers the control to the statement (if any) immediately following the loop. On the other hand, continue transfers the control back to the start of the loop for the next iteration.

13. Pass Statement


The pass statement in Python is a simple statement that tells the Python interpreter to ‘do nothing’.
The interpreter simply continues with the execution of program whenever the pass statement is executed.
This amazing feature makes it a good placeholder whenever Python needs to form an empty sub-statement block.
The pass statement is very useful when we are creating a program and want to hold the place of a specific code that is not ready or incomplete code.
In Python, the pass statement is also called a null statement or empty statement.
The major difference between pass and comment is that the interpreter ignores the comment entirely in the program, while it does not ignore pass. It outcomes in no operation (NOP).
Example
x = 20
y = 30
if x > y:
pass

Output
No output

Here, pass is a keyword in Python. Look at the below flowchart diagram of pass statement.

Explanation In Detail
In Python, we can use the pass statement in function definition def statement, if statement, or for or while loop where they must have a nonempty indented code block.
If the code block is missing, the syntax error will generate. For this reason, Python provides a pass statement, which does nothing, but it is still a valid statement.

There are the following uses of pass statement in Python that are as follows:
1. We can use the pass statement in the program when a statement is syntactically required, but we do not want to use any executable statement at its place.
2. We can use the pass statement to hold the place of code that is not ready or incomplete code yet. We often use in the place of loops or functions.
To use it, we just need to type the word ‘pass’ where we want to insert any other code (like loop or function).
Example

count = 0
while(count <= 5):
pass

As you can see, we have created a while loop that is going to execute some code till the count is less than or equal to 5. Assume this is our code, but we have not complete writing the while loop and want to
move on to something else and come back to it later.
This is the perfect time or place to use the pass statement in Python. Our code will do nothing. When writing the code is finished, we will place it at the place of pass statement.

3. Normally, we use the pass statement within the block of code under the loop statement, typically after a conditional if statement or while statement.
4. We mostly use the pass statement to create empty or null classes or functions.

Example 1:
Let’s write a program to use the pass statement in ‘while loop’.

count = 0
while count <= 5:
count = count + 1
if count == 3:
pass # nothing to be done on this line for output.
print(count, end=' ')

Output
123456

Example 2:
Let’s write a program in Python to use the pass statement in ‘for loop’.

for x in range(2, 6):


if x == 4:
pass
print(x, end=' ')

Output
2345

Example 3:
Let’s write a program to use the pass statement in creating an empty class.

class enpty_class:
pass

Output
blank output
Explanation In Detail
In some programming scenarios, we need to construct empty functions or classes. To construct an empty class, just type pass statement like above.
If we remove it, we will get an error: IndentationError: expected an indented block after class definition on line 1. Therefore, ‘pass’ statement is useful when a statement is syntactically required, but the program
requires no action.

14. Switch Statement


A switch statement is a multiway decision statement that executes a statement by comparing the value of a variable to the values specified in the case statements.
If it matches, a statement or a block of statements associated with that case is executed.
Python programming language provides lots of features that can make switch functionality possible in a cleaner way. They are as:

Using if-elif-else statements


Using Dictionary mapping
Python class
Using Python Functions and Lambdas
Using structural pattern matching

Implementing Switch Statement in Python using if-elif-else


The if-elif-else statement is a way to implement a switch case statement in Python. If the specified condition is true, then a statement or block of statements will execute.
If false, the block of statements will not execute. Else block statement will execute if none of the above conditions meet.

Example

city = 'd' # Initialize the variable.


if city == 'm':
print('Mumbai')
elif city == 'd':
print('Dhanbad')
elif city == 'c':
print('Chennai')
elif city == 'r':
print('Ranchi')
else:
print('No city')

Output
Dhanbad

Implementing Switch Statement in Python using Dictionary


Some Python programmer uses the concept of dictionary mapping instead of using if-elif-else statements.
A dictionary in Python is an unordered collection of data values. It stores the collection of data values as key-value pairs. Keys in the dictionary mapping should be unique because values in the dictionary are
indexed by keys.
We can use the get() method the value for a given key. If the key is not available, then it returns the default value. To implement the switch statement, the key-value pair of dictionary data type works like a ‘case’
in a switch case statement.

Example:
Let’s write the program code in Python to implement the switch case statement using dictionary mapping.

# Implementing switch case statement in Python using Dictionary.


def m():
return "Mumbai"
def d():
return "Dhanbad"
def c():
return "Chennai"
def r():
return "Ranchi"
def default():
return "No city"

# Creating a dictionary and put these in it.


switcher = {
1: m,
2: d,
3: c,
4: r,
}
# Creating a function named switch with a parameter.
def switch(city):
return switcher.get(city, default)()
print(switch(2)) # Calling function.
print(switch(3)) # Calling function.

Output

Dhanbad
Chennai

Explanation In Detail
In this example, we have created different functions which return the name of city. Then, we have created a dictionary in which we have put these in the form of key-value pairs.

After constructing the dictionary, we created a main function named switch with a parameter. This parameter takes a user input in the form of keys to find the name of city.
When we call these values with the help of keys, the specific function gets called, and we get the desired output on the console. At the last, we have called functions by passing two key arguments and printed the
desired output.

Implementing Switch Statement using Python Class


In this method, we are going to use Python class to implement switch case statement.
In Python, a class is an object constructor that contains properties and methods.
getattr(object, name, default)

This function takes three parameters: object, name, and default. Read the explanation of these parameters below.

object: It represents an object name whose attribute is to be returned. It is a mandatory parameter.


name: It is a string that contains the object’s attribute name. It is also a mandatory parameter.
dnefault: It returns the default statement if the attribute is not present in the object.

Example :

# Creating a class.
class PythonSwitch():
def main_function(self, name_of_day):
default = "Incorrect name of day"
method_name = 'day_' + str(name_of_day)
method = getattr(self, method_name, lambda: default())
return method()
def day_1(self):
return "Sunday"
def day_2(self):
return "Monday"
def day_3(self):
return "Tuesday"
def day_4(self):
return "Wednesday"
def day_5(self):
return "Thursday"
def day_6(self):
return "Friday"
def day_7(self):
return "Saturday"

# Creating an object of class.


my_switch = PythonSwitch()
print(my_switch.main_function(1)) # Calling function with passing argument value.
print(my_switch.main_function(3)) # Calling function.

Output

Sunday
Tuesday

Chapter 5 :
Functions in Python

1 Functions in Python Types


2 User Defined Functions in Python
3 Calling a Function in Python
4 Function Arguments in Python Types
5 Pass by Value in Python Pass by Reference
6 Return in Python Return Statement
7 Void Function in Python
8 Scope in Python Variable Scope, Lifetime
9 Global in Python Global Keyword

1 Functions in Python Types


A function in Python is a named block of organized and connected statements that performs a specific task.
In other words, a function is a block of code that performs a specific and well-defined task. It organizes the code into a logical way to perform a certain task.
Every function is called by a certain name and the block of code inside the function gets executed when we call the function.

If you have a block of code that gets invoked more than once, put it into a function. This is because function allows us to use a block of code repeatedly in different sections of a program.
It makes the program more efficient by minimizing the repetition. It makes the code reusable.
Functions help to break down long and complex programs into smaller and manageable segments and enhance program readability and comprehensibility.
Functions are defined outside the class, whereas methods are defined inside the class.

Why do we need to use functions in Python


A function is a piece of code in a program that performs a specific task. Following are some key reasons for using functions in Python. They are:

1. Functions help to reduce the duplicate code. They can make a long program into smaller. We can avoid the repetition of frequently required code using functions.
Later, if we need to make a change in the code, we can easily update it in one place. Hence, debugging of code becomes easy.

2. Breaking up of a long and complex program into functions allows us to debug each segment one at a time and then assemble them into a working whole.

3. We can group together all logically related statements in one entity using functions in Python. Function makes the program easy to read, understand, and debug. It improves the clarity of the code.

4. Once we write the code inside the function and test it, we can reuse this code as per the requirement. Reusability is the significant use of functions in Python.
Syntax to define User defined Function in Python
The user creates or defines user-defined functions. The general syntax to declare a user defined function in Python is as follows:

def function_name(parameters): # Function header.


"""docstring"""
......
body of the function
......
return [expression or values]

Explained in Detail
In the above syntax, the first line of function definition is header, and the rest is the body of function. The function definition begins with def keyword followed by the function name, parentheses (()), and then
colon (:). The parameter list placed within parentheses is optional.
Components of Python Functions
A block of statements that defines a function in Python consists of the following parts:

1. Keyword def:
Function definition starts with the keyword ‘def’ that defines the function. It tells the beginning of the function header.

2. Function name:
The function_name represents the name of a function. Every function must be a unique user-defined name or an identifier and given to it in the function header statement.
It is an excellent practice to name your function according to the work it performs. In the above example, the function name is msg, and add.

3. Parameters:
The formal parameters (arguments) placed inside the parentheses are optional. A parameter is a piece of data or information that we use inside the function to perform a specific task.

4. Colon (:):
A colon indicates the end of function headers.

5. Docstring:
A docstring is a documentation string that is an optional component. We commonly use it to describe what the function does. We write it on the line next to the function header.
A docstring must enclose in triple quotes and can write up to in several lines. We can access it with: function_name.__doc__.

6. Statement(s):
The body of function consists of one or more valid statements. Each statement must be intended with the same indentation to form a block.
In general, 4 spaces of indentation are standard from the header line in Python. When the function gets called, the statements inside the function’s body execute.
Once the function is invoked, the formal parameters inside the parentheses become arguments.

7. Return statement:
A return statement ends the function call and returns a value from a function back to the calling code. It is optional. If we do not define return statement inside the function’s body, the function returns the object
‘None’.
We will learn about the return statement in the further tutorial in more detail.

Rules for defining User defined Function in Python


There are the following important rules for defining the user-defined functions in Python that should you keep in your mind. They are as:
1. Functions must begin either with a letter or an underscore.
2. They should be lowercase.
3. They can comprise numbers but shouldn’t begin with one.
4. Functions can be of any length.
5. The name of function should not be a keyword in Python.
6. We can use an underscore to separate more than one word. For example, function_name(), person_name(), etc. It improves the readability and maintains conventions.
7. There should not be any space between the two words.

Types of Functions in Python


There are two types of functions available in Python programming language. They are:

Built-in functions
User-defined functions

Built-in Functions in Python

Built-in functions in Python are predefined functions by the Python system. They allow us to perform a variety of tasks, such as printing messages, converting one type of data to another, etc.
The predefined functions are always available to use. We do not need to import required module for them. Python comes with a variety of built-in functions.

1. abs(value): This function returns the absolute value of a given numeric value.
Example 1 :

# This statement return the absolute value of a number.


num = abs(-5.45)
print(num)
Output
5.45

2. bin(n): This function returns a binary representation of a integer number.


Example 2 :

# This statement return the binary representation of a number.


num = bin(24)
print(num)

Output
0b11000

3. float(n): It returns a floating-point number of a given number.


Example 3 :

# Converting an integer number 5 into a floating-point number.


num = float(5)
print(num)

Output
5.0

4. int(n): It returns an integer number of a specified number. Example 4 :

# Converting a floating-point number 5.5 into an integer number.


num = int(5.5)
print(num)

Output
5

5. sqrt(x): This function returns the square root of a given number.


Example 5 :

# Finding the square root of a number 36.


import math
sq_num = math.sqrt(36)
print('Square of number 36 = ',sq_num)

Output
Square of number 36 = 6.0

6. pow(x, y): This function returns the value of x raised to the power y.
Example 6 :

# Finding the value of 4 to the power of 2.


import math
pw_num = math.pow(4,2)
print(pw_num)

Output
16.0

7. factorial(x): This function finds the factorial of a specified number.


Example 7 :

# Finding the factorial of number 5.


import math
fact_num = math.factorial(5)
print('Factorial of number 5 = ',fact_num)

Output
Factorial of number 5 = 120

8. len(iterable): This function returns the number of elements or items of the specified iterable object.
Example 8 :

# Returns the number of elements in the list.


city_list = ['Dhanbad', 'New York', 'London', 'Godda', 'Mumbai']
length = len(city_list)
print('Length of list = ',length)

Output
Length of list = 5

9. print(object): This function prints the object to the standard output device.
Example 9 :

# Printing a message onto the screen.


print('This is a message.')

Output
This is a message.
10. input(prompt): This function reads input, converts it to a string, and returns that.
Example 10 :

# Prompt or take the input from the user and store it into a variable str.
str = input('What is your name?')
print(str)

Output
What is your name?

11. max(iterable): This function returns the largest number of two or more numbers.
Example 11 :

# Returns the largest number from the list.


num_list = [20, 40, 10, 60, 50, 30]
largest_num = max(num_list)
print('Largest number from list is ',largest_num)

Output

Largest number from list is 60

12. min(iterable): This function returns the smallest number of two or more numbers.
Example 12 :

# Returns the smallest number.


smallest_num = min(20, 10)
print('Smallest number is ',smallest_num)

Output
Smallest number is 10

13. range(stop) or range(start, stop): This function returns the sequence of numbers, starting from ‘start’ value up to (not including) the ‘stop’ value.
Example 13 :

# Creating a sequence of numbers from 0 to 7, and print each number in the sequence.
num = range(5)
for n in num:
print(n, end=' ')

Output
01234

14. round(f, n): This function rounds a number to a given precision in decimal digits.
Example 14 :

# Round a number to only two decimal points.


num = round(6.759, 2)
print(num)

Output
6.76

15. log10(x): This function returns the logarithm of x at base 10. Example 15 :

# Find the logarithm of a number at base 10.


import math
num = math.log10(2)
print(num)

Output
0.301

2 User Defined Functions in Python


A user defined function in Python is a function that is created by the user to perform a specific task in a program. It gets executed whenever we call the function.

def function_name(parameter_list): # function header


......
body_of_the_function
......
return <value(s)>

Example 1 :

# user defined function definition


def greeting():
print('Hello world!')
print('Welcome to the world of the programming!')
# Function calling.
greeting()

Output

Hello world!
Welcome to the world of the programming!

Example 2 :

# Simple Python function to check even and odd.


def evenOdd(x): # function header. x is a local variable.
if x % 2 == 0:
print('Number',x,'is even')
else:
print('Number',x,'is odd')
# Calling functions by passing two argument values.
evenOdd(20)
evenOdd(25)

Output

Number 20 is even
Number 25 is odd

Example 3 :

# Function definition having two parameters, such as name and age.


def person(name, age): # Here, name and age are local variables.
print(name)
print(age)
person('John', 24)

Output

John
24

Example 4 :

# Function to find the sum of three numbers.


def sum_three_numbers(n1, n2, n3): # Here, n1, n2, n3 are local variables.
sum = n1 + n2 + n3 # Here, sum is a local variable.
return sum
# Calling a function by passing three argument values.
# We will store the returned value into a variable named s.
s = sum_three_numbers(20, 30, 40) # Here, s is a global variable.

# Displaying the value of s in the console.


print('Sum of three numbers = ',s)

Output
Sum of three numbers = 90

Explained in Detail
In this example, we have created a function named sum_three_numbers with three parameters, such as n1, n2, and n3.
This function’s body has two statements: first is a variable sum that adds three numbers and stores it into the variable sum and second is the return statement that returns the value to the calling function.

3 Calling a Function in Python


Basically, a function call is a statement that executes the function object. When we call a user defined function, the program control jumps to the function definition and executes statements
present in the function’s body.
Once all the statements inside the function’s body get executed, the program control goes back to the calling function. This process is called calling a function in Python.
We can call a user defined function in different ways.

Execution Style of Calling a Function in Python


We will try to understand the execution style of calling a function in Python with the help of diagram.
Example 1 :

# Function definition.
def funct_name(): # function header.
print('This function does not contain any parameter.')
# Main program execution started from here.
funct_name() # function calling.

Output
This function does not contain any parameter.
Explained in Detail
In this example, we have created a function named funct_name that does not contain any parameter. When we called it, the program control goes to the function and executes the statement inside it and print the
message.

Example 2 :

# Function definition.
def calcSum(x, y): # Here, x and y are local variables.
z = x + y # Here, z is a local variable.
print("Sum of two numbers = ",z)
# Main program.
# Calling a function by passing two argument values.
calcSum(20, 30)

Output
Sum of two numbers = 50
Explained in Detail
In this example, when the Python interpreter executes calcSum(20, 30), the function calcSum() is called by passing two argument values.

Then, the program control goes to the calcSum() function and statements inside this function execute with using both values. Finally, the function prints the sum of two numbers as a result.
Look at the execution style of function in the below figure to understand more clearly.

Calling a Function from another Function in Python

We can also call a function from another function in Python. Let’s write a program in which we will calculate the sum of two numbers by taking numbers as input from the user.
Example 1 :

# Function1 to take inputs from the user.


def funct_in():
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
calcSum(num1, num2) # Calling function2 from function1.

# Function2 to calculate the sum of two numbers.


def calcSum(num1, num2):
sum = num1 + num2
print("Sum of two numbers = ",sum)

# Main part of the program.


funct_in() # calling function1.

Output
Enter your first number: 10
Enter your second number: 50
Sum of two numbers = 60

Explained in Detail
In this example program, we have created two functions; one is parameterized function calcSum(num1, num2) and another is non-parameterized function funct_in().
After taking the input from the user, we have invoked the function calcSum() from the funct_in() function. In this way, we can easily call one function from another function.

Example 2 :
Let’s write a program in Python to calculate the perimeter and area of the rectangle using functions.

# Function1 to take the input from the user.


def funct_in():
length = int(input('Enter the length of rectangle: '))
breadth = int(input('Enter the breadth of rectangle: '))
calcPer(length, breadth) # Calling function2 from function1.
calcArea(length, breadth) # Calling function3 from the function1.

# Function2 to calculate the perimeter of rectangle.


def calcPer(l, b):
per = 2 * (l + b)
print("Perimeter of the rectangle = ",per)
# Function3 to calculate the area of the rectangle.
def calcArea(l, b):
area = l * b
print('Area of the rectangle =',area)
# Main part of the program.
funct_in() # calling function1.
Output

Enter the length of rectangle: 20


Enter the breadth of rectangle: 30
Perimeter of the rectangle = 100
Area of the rectangle = 600

Explained in Detail
When the Python interpreter executes the funct_in(), then the program control goes to the function funct_in(). Inside the function, Python takes the length of rectangle in string from the user, cast into the integer,
and then store it into a variable length. Similarly, for breadth.

When Python executes calcPer() function with passing arguments, the program control goes to function2 calcPer() and executes all statements by using argument values inside it.

After the complete execution of this function, the control goes back to the executing the function calcArea() inside the funct_in() function.

When the Python executes the function calcArea() with passing arguments, the control goes to the function calcArea() and executes all statements by using arguments inside it.
Example 3 :
Writing a program in Python to calculate the addition, subtraction, multiplication, and division of two numbers taken from the user.

# Function1 to calculate addition of two numbers.


def add(x, y):
z=x+y
print("Addition:",z)
# Function2 to calculate the subtraction.
def sub(p, q):
r=p-q
print("Subtraction:",r)
# Function3 to calculate the multiplication.
def multiply(a, b):
c=a*b
print('Multiplication:',c)

# Function4 to calculate the division.


def div(n, m):
d=n/m
print('Division:',d)
# Function5 to take inputs from the user and calling.
def main_funct():
n1 = int(input('Enter your first number: '))
n2 = int(input('Enter your second number: '))
add(n1, n2)
sub(n1, n2)
multiply(n1, n2)
div(n1, n2)
# Main program.
main_funct() # calling function5.

Output

Enter your first number: 25


Enter your second number: 5
Addition: 30
Subtraction: 20
Multiplication: 125
Division: 5.0

Example 4 :
Writing a Python program to calculate the square of a given number.

def square(num):
result = num * num
print("Square of",num,"=",result)
square(5)

Output
Square of 5 = 25

Example 5 :
Write a program in Python to swap two numbers.

# Python program to swap two numbers.


def swap(x, y):
print('Before swapping: ')
print('x:',x)
print('y:',y)
temp = x
x=y
y = temp
print('After swapping: ')
print('x:',x)
print('y:',y)
# Calling function with passing two arguments.
swap(20, 10)

Output

Before swapping:
x: 20
y: 10
After swapping:
x: 10
y: 20
Example 6 :
Writing a Python program to check the given number is even or odd.

# Python program to check a number is even or odd.


num = int(input('Enter your number to check even or odd: '))
# Create a function.
def evenorodd():
if num % 2 == 0:
print(num,'is an even number.')
else:
print(num,'is an odd number.')
# Calling function.
evenorodd()

Output

Enter your number to check even or odd: 20


20 is an even number.
Enter your number to check even or odd: 9
9 is an odd number.

Example 7 :
Writing a Python program to test whether a year is leap.

# Python program to check a year is leap or not.


year = int(input('Enter a year: '))
def leap():
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year,'is a leap year.')
else:
print(year,'is not a leap year.')
# Calling function.
leap()

Output

Enter a year: 2024


2024 is a leap year.
Enter a year: 2019
2019 is not a leap year.

Example 8 :
Writing a Python program to check a number is prime or not, using function calling.

# Python program to check a number is prime or not.


# Create a function to check conditions for the prime.
def primeChecker(n):
# Using if-else statement for checking the number is greater than 1.
if n > 1:
# Iterating over the number using for loop.
for x in range(2, int(n/2) + 1):
# Check the number is divisible or not.
if (n % x) == 0:
print(n, "is not a prime number.")
break
# Else part if it is a prime number.
else:
print(n, "is a prime number.")
# Else part if the number is not greater than 1.
else:
print(x, "is not a prime number")

# Main part of the program.


# Take a number as input from the user.
n = int(input("Enter a number to check prime or not: "))
# Calling function with passing input number.
primeChecker(n)

Output

Enter a number to check prime or not: 5


5 is a prime number.
Enter a number to check prime or not: 6
6 is not a prime number.

Explained in Detail
In this example, we have used nested if-else statement and for loop to check the conditions for the prime number.
First, we have taken a number as input from the user in the string form. Then, we have converted the entered number into int and stores it into a variable n. We called the function primeChecker() with passing the
variable value.
Inside the function primeChecker(), we have used if-else statement to check the number is greater than 1 or not. If the number is not greater than 1, the else part will execute and print ‘not a prime number.’
Inside the outer if statement, we have used for loop to perform the iteration from 2 to number/2. Inside the for loop, we used the if-else statement. If the number is completely divisible by x with the remainder 0,
then it is not a prime number; otherwise, the number is a prime number.
Example 9 :
Writing a program in which we will create a function and print a list of values containing the square of numbers between 1 to 10 (both included).

def sqList():
# Creating an empty list that will hold values.
l = list()
for x in range(1, 11):
l.append(x ** 2)
print(l)
# Function call.
sqList()

Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Explained in Detail
In this example, we have used the for loop for iteration over generated numbers. The numbers will automatically generated using range() function. We have used the append() function to store the result directly
into the list.

The statement l = list means that we are creating an empty list that will store values generated while the for loop executes.
Example 10 :
Suppose we have a list of five subject marks like [68, 98, 78, 88, 86] and we have to find and print the total marks and percentage of a student.

def totalMarks():
# Marks of five subjects for a student.
marks = [68, 98, 78, 88, 86]
# Transferring individual marks into independent variable.
m1 = marks[0]
m2 = marks[1]
m3 = marks[2]
m4 = marks[3]
m5 = marks[4]
# Total marks.
totMarks = m1 + m2 + m3 + m4 + m5
print('Total marks obtained:',totMarks)
# Percentage.
per = totMarks / 5
print('Percentage:',per)
# Function call.
totalMarks()

Output

Total marks obtained: 418


Percentage: 83.6

4 Function Arguments in Python Types


In Python, we can pass a piece of data into a user-defined function definition based on function arguments and parameters.

Parameters are the local variables mentioned within the parentheses in the function definition. We also call them as formal parameters.

Arguments are specific values (or data) passed into the function’s parameters when it is called. We also call them actual parameters.

In Python, arguments are passed by value (also known as call by value).


Example 1 :
Function arguments and parameters in Python.

# Function definition with two formal parameters x and y. They are local variables.
def multiply(x, y):
print(x * y)
# Main program.
# Function call 1.
multiply(20, 30) # Here, 20 and 30 are argument values.
a = 50
# Function call 2.
multiply(20, a) # Here, value 20 and variable a are arguments or actual parameters.
b = 80
# Function call 3.
multiply(a,b) # Here, variables a and b are argument values/ actual parameters.

Output

600
1000
4000

Explained in Detail
As you can see in the above program, we have defined two parameters x and y in the function definition. Both are local variables. We have passed two argument values to the function’s parameters.
However, we can pass many argument values based on the function’s parameters defined, but they should be separated them by a comma.
Types of Function Arguments in Python
In Python, there are four types of function arguments. We can invoke a function using any of these four types of formal arguments. They are:

Default arguments
Required arguments
Keyword arguments
Variable-length arguments

Default Arguments in Python


Default arguments are the default values in the function header that will be used if we pass no argument values during the function call. We also call the default argument values as implicit values.
Moreover, implicit values should be constant (i.e. immutable) and used if no values passed. We can assign the default value with the help of an assignment operator (=).
Example 1 :

def studentInfo(name, gender = 'Male'):


# This function displays the student's info passed in the function parameters.
print('Name:',name)
print('Gender:',gender)
# Main program.
# Function call 1.
studentInfo('Deepak')
# Function call 2.
studentInfo('Tripti', gender = 'Female')

Output

Name: Deepak
Gender: Male
Name: Tripti
Gender: Female

Explained in Detail
In this example, we have specified the default value for the formal parameter gender as ‘Male’. During the first function call, we simply pass the argument value ‘Deepak’ to the parameter name. We did not pass
argument value to gender. In this case, the default value of gender argument will be used.

During the second function call, we passed all two arguments ‘Tripti’ and ‘Female’ to the both parameters name and gender. Hence, no default argument will use.

Example 2 :

def studentInfo(name, rollNo = 20, branch = 'Electrical'):


print('Name:',name,'Roll no:',rollNo,'Branch:',branch)
# Main program.
# Function call 1.
studentInfo(name = 'John')
# Function call 2.
studentInfo(name = 'Bob', rollNo = 10)
# Function call 3.
studentInfo(name = 'Jenny', rollNo = 5, branch = 'Computer Science')

Output

Name: John Roll no: 20 Branch: Electrical


Name: Bob Roll no: 10 Branch: Electrical
Name: Jenny Roll no: 5 Branch: Computer Science

Explained in Detail
In this example, we have specified default arguments for the parameters rollNo and branch as 20 and ‘Electrical’, respectively. When we do not pass default values to the parameters rollNo and branch, the
default argument values used.

Required Arguments in Python

Required arguments are those arguments that are passed to the function’s parameters in the exact positional order to match the function definition. These arguments are also called positional
arguments in Python.

Positional arguments are mandatory arguments to the function. During the function call, if we do not pass argument values in the correct number and order, or we pass more or less arguments than the number
defined in the function, we will get a syntax error.

Example 1 :

# Program to find the area and perimeter of rectangle using function required arguments.
def rectangle(length, breadth):
areaRec = length * breadth # Area of rectangle.
perRec = 2 * (length + breadth) # Perimeter of rectangle.
print("Area of rectangle = ",areaRec)
print("Perimeter of rectangle = ",perRec)

# Main program.
def main():
ln = int(input("Enter the length of rectangle: "))
br = int(input("Enter the breadth of rectangle: "))
rectangle(ln) # Intentionaly missing one argument value.
main() # function calling.

Output

Enter the length of rectangle: 20


Enter the breadth of rectangle: 10
TypeError: rectangle() missing 1 required positional argument: 'breadth'

Explained in Detail
In this example program, the length and breadth defined in rectangle() function are formal parameters. The ln and br are actual parameters or arguments.
When we execute the above program code, Python assigns the input value to actual parameters, ln and br. We have called rectangle() function from inside the main() function by passing one argument and another
is missing. Therefore, we got syntax error.
Hence, when you call a function that specifies some formal parameters, you must pass the exact required number of arguments to the function.
Keyword Arguments in Python

Keyword arguments are those arguments in which values are associated with parameter names. That’s why these arguments are also called named arguments.

They are especially useful when we call a function with a long parameter list where most of the formal parameters have default values and we only wish to update very few of them.

When we use keyword arguments in the function call statement, the caller identifies arguments by the parameter name. We pass the keyword arguments with assigned values in the function call.

The advantages of using keyword arguments in the function call are as:

Using keyword arguments, function calling becomes easier since we do not need to worry about the order of arguments.
We can pass values to those parameters to which we wish to, provided that other parameters have default argument values.
Example 1 :
Printing the name, age, and gender of two persons using required arguments.

# Displaying persons info.


def display(name, age, gender):
print('Name:',name)
print('Age:',age)
print('Gender:',gender)
def main():
# First function call.
display('John', 20, 'M') # function calling from another function.
# Second function call.
display('Jenny', 18, 'F')
main() # function calling.

Output
Name: John
Age: 20
Gender: M
Name: Jenny
Age: 18
Gender: F

Explained in Detail
In this example program, we have not used keyword arguments. Therefore, the order in which we specify the argument values is important. Otherwise, we will get incorrect outcomes.
Example 2 :
Modifying keywords, name, age, and gender.

# Displaying persons info.


def display(name, age, gender):
print('Name:',name)
print('Age:',age)
print('Gender:',gender)
def main():
# First function call.
display('Herry', age = 20, gender = 'M') # function calling from another function.
# Second function call.
display(age = 18, gender = 'F', name = 'Jimmy')
main() # function calling.

Output

Name: Herry
Age: 20
Gender: M
Name: Jimmy
Age: 18
Gender: F

Explained in Detail
Now observe the function call statement in the above program: the variable name gets the value of ‘Herry’ due to the order or position of the argument. Then, the formal parameters age and gender gets values 20
and ‘M’ respectively due to named or keyword arguments.

Similarly, in the second function call, we have assigned all the formal parameters through keyword arguments. So, the position of all arguments does not matter. However, it is not recommended to change the
order of parameters.

Variable length Arguments

In some case, we may need to call a function with more arguments than we specified when defining the function. These arguments are called variable length arguments in Python.

They are useful when we do not know the exact number of arguments that will be passed to the function. We can pass the multiple non keyword argument values with a single parameter name.

Example 1 :

# Function definition with variable length parameters.


def my_function(*args): # Here, args is name of formal parameter.
print(args)
print('Calling function with two arguments')
my_function(10, 20)
print('Calling function with three arguments')
my_function(10, 20, 30)
print('Calling function with four arguments')
my_function(20, 30, 40, 50)

Output

Calling function with two arguments


(10, 20)
Calling function with three arguments
(10, 20, 30)
Calling function with four arguments
(20, 30, 40, 50)

Explained in Detail
In this example program, you can see that in the first function call, we have passed 2 arguments. In the second function call, we have passed three arguments, whereas we have passed four arguments in the third
function call.

Hence, this is a significant feature by Python that allows us to pass n number of non keyword arguments with a single parameter name.

Example 2 :

# Function definition with one formal parameter and variable length parameters.
def listDay(arg1, *arg2):
print(arg1, arg2, sep="")
def main():
listDay('Name of days are:', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
main() # function calling.

Output
Name of days are:('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')

Explained in Detail
In the above example program, the first argument ‘Name of days are:’ passed to the function and assigned into arg1 formal parameter and passed the rest of the non keyword arguments as a tuple with ‘*arg2’.

5 Pass by Value in Python Pass by Reference

When we define a custom or user defined function in Python we may, optionally we may need to specify parameter names between the function’s parentheses.

If we specify parameters in the function definition, then we need to pass argument values to the function’s parameters while calling it.

The function use that passed values during its execution by referencing it via parameter name.

Basically, there are two ways to pass argument values to the function’s parameters. They are:

Call/Pass by Value
Call/Pass by Reference

Call/Pass by Value in Python


In pass by value (also known as call by value), the argument passed to the function is the copy of of its original object. If we change or update the value of object inside the function, then original
object will not change.
If the argument is variable, the copy of the current value of the variable is passed to the function’s parameter. The value of the variable in the function call is not affected by what happens inside the function.

Call/Pass by Reference
In pass by reference (also known as call by reference), the argument passed to the function’s parameter is the original object. If we change the value of object inside the function, the original object
will also change.

Key Points about Pass by Object Reference

There are the following important points about the pass by object reference you should keep it mind.

In the Python programming language, all argument values are passed to a function by object reference.
If the object is mutable (changeable), the changed value is available outside the function. Mutable objects may be list, set, dictionary, byte array.
If the object is immutable (not changeable), the changed value is not available outside the function. Immutable objects may be numbers (int, float, complex), strings, tuple, frozen set,
bytes.
If we pass immutable objects to the function, the passing works like pass by value or call by value.
If we pass mutable objects to the function, the passing works like pass by reference or call by reference.

Example 1 :
Writing a Python program in which we will pass mutable objects (list) to the function using pass by object reference.
# This program illustrates the concept of call by object reference using mutable objects.
def my_funct(y):
print('Values inside the function before modifying:',y)
y[2] = 4 # modifying value.
print('Values inside the function after modifying:',y)

# Main part of program.


x = [1, 2, 3] # List of values.
print('Values outside the function before modifying:',x)
my_funct(x) # calling function with passing x to function parameter y.
print('Values outside the function after modifying:',x)

Output
Values outside the function before modifying: [1, 2, 3]
Values inside the function before modifying: [1, 2, 3]
Values inside the function after modifying: [1, 2, 4]
Values outside the function after modifying: [1, 2, 4]

Explained in Detail
In this example, ‘x’ is a list of values. Since the list is a mutable object in Python, the passing acts like call by reference. We have passed x as an argument to the function’s parameter y using call by reference.

Here, y is a formal parameter, whereas x is an actual argument. Both x and y belong to the same memory location. If we make any change in y inside the function, then it also affects in x outside the function.

In this scenario, Python makes only one copy of the argument in the memory location for processing. Values are the same in that copy, but parameter names are different, x and y.

Example 2 :
Writing a Python program in which we will pass immutable objects (string) to the function using pass by object reference.
# This program illustrates the concept of call by object reference using immutable objects.
def my_func(name):
print('String inside the function before modifying:',name)
name = 'John' # modifying value.
print('String inside the function after modifying:',name)
# Main part of program.
n = 'Herry'
print('String outside the function before modifying:',n)

my_func(n) # calling function with passing n to function parameter name.


print('String outside the function after modifying:',n)

Output
String outside the function before modifying: Herry
String inside the function before modifying: Herry
String inside the function after modifying: John
String outside the function after modifying: Herry

Explained in Detail
In this example, n is a string. Since string is an immutable object in Python, the passing acts like call by value. We have passed ‘n’ as an argument value to the function’s parameter name.
Here, ‘name’ is a formal parameter, whereas ‘n’ is an actual argument. Initially, both have the same memory location. As we have made an update in the value of name (name = ‘John’), the value of name also has
updated.
In this scenario, the value of ‘n’ remains the same and the memory location of ‘n’ also remains the same. But, the memory location of ‘name’ is changed. Hence, Python makes two copies of arguments in two
memory locations for processing.

Example 3 :
Wtiting a program in which we will pass mutable objects (List) to the function using pass by object reference. In this program, two variables will share the same memory location.

def my_func(y):
print('Id of y before modifying list:',id(y))
print('Values inside the function before modifying:',y)
y[2] = 5
print('Values inside the function after modifying:',y)

# Main program.
x = [1, 2, 3]
print('Values outside the function before modifying:',x)
print('Id of x before modifying list:',id(x))

my_func(x) # function call.


print('Id of x after modifying list:',id(x))
print('Values outside the function after modifying:',x)
Output

Values outside the function before modifying: [1, 2, 3]


Id of x before modifying list: 2959160358016
Id of y before modifying list: 2959160358016
Values inside the function before modifying: [1, 2, 3]
Values inside the function after modifying: [1, 2, 5]
Id of x after modifying list: 2959160358016
Values outside the function after modifying: [1, 2, 5]

Explained in Detail
In this example, ‘x’ is a list. Since the list is a mutable object, the passing will act like call by reference. We pass ‘x’ as an argument to the function my_func(). ‘x’ is an actual argument, whereas ‘y’ is a formal
parameter.

Before updating the list, the memory location of both variable x and y is the same. But, as we made an update in y, also reflected in x. In this case, memory location of both x and y are the same even after making
the changing in y.

In this program, we have used id() function that take an object as a parameter (i.e. id(object)) and return the identity of this particular object. The returned value is an integer, which is unique and permanent for
this object during its lifetime.

Example 4 :
# This program is a demonstration of call by reference overwritten.
def my_func(y):
print('Values inside the function before modifying:',y)
y[1] = 60
print('Values inside the function after modifying:',y)
y = [1, 2, 3, 4, 5] # It would assign a new reference to y.
print('y =',y)
print('x =',x)

# Main program.
x = [10, 20, 30, 40]
print('Values outside the function before modifying:',x)
my_func(x)
print('Values outside the function after modifying:',x)

Output
Values outside the function before modifying: [10, 20, 30, 40]
Values inside the function before modifying: [10, 20, 30, 40]
Values inside the function after modifying: [10, 60, 30, 40]
y = [1, 2, 3, 4, 5]
x = [10, 60, 30, 40]
Values outside the function after modifying: [10, 60, 30, 40]
6 Return in Python Return Statement
A return in Python is a keyword that passes (or returns) a value or data from the function back to the main code.

When we declare a return keyword with a value or expression separating by the comma, then we call it a return statement. It is used to return a value from a function to the caller.

A function that returns some computed result in the terms of a value to the caller is called fruitful function or non-void function in Python.

A function that does not return any computed or final value to the caller is called void function. It may or may not have a return statement.

def function_name(formal_parameters):
.......
function's body
.......
return <values/expression>

Key Points of Python Return Statement

There are a few key points about the return statement that you should keep in mind. They are:
1. Return statement finishes the function call’s execution and returns the result (value or expression).

2. Python function can have one or more return statement but only one statement will execute based on the matching condition.

3. A void function may or may not return a value to the caller. If the function does not contain a return statement, it will send a None value that represents nothingness.

Example 1 :

def greet(name): # Function without return statement.


"""Greets the person
passed as argument"""
print('Hello ' + name + ', Good Morning!')
print(greet('Mark'))

Output

Hello Mark, Good Morning!


None

In this example, the greet() function does not return explicitly a value. It simply prints a message on the console. Since the function does not have a return keyword, it prints None value, which is implicitly sent by
functions without return statement.

4. A function that returns a value, always have a caller which call and receives the final value of a function.

5. Return None is the same as a return statement with no argument value or expression. This means that a void function has a return statement, but it is not returning any value to the caller. It has the following
general syntax.
return

6. A return statement may return more than one value from the function to the caller. It has the following general syntax.
return <value1>, <value2>, <value3>, . . . .
7. The statement following the return statement will not execute.
Example 2 :

def dispMessage(msg): # Void function with return statement.


print(msg)
return # returning not value.
print('Programming')
print(dispMessage('I love Python'))

Output

I love Python
None

8. We cannot use the return statement in the Python function.

Example 3 :
Writing a simple program in Python that will return the sum of two numbers to the caller.

# Function with return statement.


def addition(num1, num2):
total = num1 + num2
return total # returning a single value from a function.
# Main part of program execution starts here.
total = addition(20, 30) # Calling function with passing two values.
print('Sum of two numbers =',total)

Output
Sum of two numbers = 50

Explained in Detail
In this example, we have defined a function named addition that has two parameters num1 and num2. When we have called this function with passing two argument values 20 and 30, it calculates the sum of two
numbers and returned that values to the caller.

Then, we have stored the returned value into a variable named total and printed it on the console. Look the complete execution style of function addition in the below figure.

Example 4 :
Writing a simple program in Python to calculate the cube of a number. We will take a number from the user.

def calCube(x):
return x * x * x # x is the formal parameter.
def main_function():
n = int(input('Enter your number: '))
# Calling function from another function.
result = calCube(n) # n is the actual parameter
print('Cube of a number = ',result)
# Calling main function.
main_function()

Output

Enter your number: 5


Cube of a number = 125

Explained in Detail
Inside the main_function(), we have taken a number from the user using input() function, converted it into int and stored in a variable n.

Then, we have called the calCube() function with passing the value of n to the function’s parameter x. After the calculation of cube, function returned the value to the caller. We have assigned it into a variable
result and then printed the result on the console.
Example 5 :
Writing a program in Python to compute the area and circumference of circle using function and return statement.

PI = 3.14
def areaCircle(r):
area = PI * r * r
return area
def circumCircle(r):
circumference = 2 * PI * r
return circumference
def main_func():
radius = int(input('Enter radius of the circle: '))
area = areaCircle(radius)
circum = circumCircle(radius)
print('Area of circle =',area)
print('Circumference of circle =',circum)
main_func() # calling main function.

Output

Enter radius of the circle: 3


Area of circle = 28.259999999999998
Circumference of circle = 18.84

Example 6 :
Writing a Python program to make a simple calculator using function and return statement.
def add(x, y):
return x + y
def sub(a, b):
return a - b
def mult(p, q):
return p * q
def div(r, s):
return r / s

# Main program execution starts here.


def main_func():
n1 = int(input('Enter your first number: '))
n2 = int(input('Enter your second number: '))
# Calling functions.
print('Addition =',add(n1, n2))
print('Subtraction =',sub(n1, n2))
print('Multiplication =',mult(n1, n2))
print('Division =',div(n1, n2))
main_func() # calling main function.

Output
Enter your first number: 10
Enter your second number: 5
Addition = 15
Subtraction = 5
Multiplication = 50
Division = 2.0
Python Function Return Multiple Values

We can return multiple values from a Python function. We separate the values after the return keyword by comma.
Example 1 :

# Program to return multiple values from a function.


def func():
return 10, 'Hello', 'P', 20 # returning more than one value from a function.
p, q, r, s = func()

print(p)
print(q)
print(r)
print(s)
print(func())

Output

10
Hello
P
20
(10, 'Hello', 'P', 20)

Example 2 :
Writing a program in Python in which we will take marks of five subjects from the student as a user. Then, we will calculate total marks and percentage of a student’s marks using function and return more than
one value from a function.

# Python program to return more than one value from a function.


def marks(m1, m2, m3, m4, m5):
total_marks = m1 + m2 + m3 + m4 + m5
percentage = total_marks / 5
# Returning more than one value from a function
return total_marks, percentage

# Main part of program.


def main_func():
m1 = int(input('Enter your Science marks: '))
m2 = int(input('Enter your Maths marks: '))
m3 = int(input('Enter your English marks: '))
m4 = int(input('Enter your Computer marks: '))
m5 = int(input('Enter your Hindi marks: '))
totalMarks, per = marks(m1, m2, m3, m4, m5)
print('Total marks obtained = ',totalMarks)
print('Percentage =',per)
main_func() # calling main function.

Output

Enter your Science marks: 75


Enter your Maths marks: 85
Enter your English marks: 72
Enter your Computer marks: 65
Enter your Hindi marks: 72
Total marks obtained = 369
Percentage = 73.8

7 Void Function in Python


Void function in Python is a function that performs an action but does not return any computed or final value to the caller.

It can accept any number of parameters and perform operation inside the function. A void function may or may not return a value to the caller.

If we do not declare return statement to return a value, Python will send a value None that represents nothingness.

Example 1 :
Writing a programme , which will calculate the sum of two numbers and prints the result on the console.

# Python program demonstrates void function.


def voidOperation():
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
sum = num1 + num2
print('Sum of %d and %d = %d' %(num1, num2, sum))
def main_fn():
voidOperation() # calling one function from another function.
main_fn() # calling main function.

Output

Enter your first number: 10


Enter your second number: 50
Sum of 10 and 50 = 60

Explained in Detail
In the above program, we have declared a void function named voidOperation(), which does not return any computed value but performs basic operation inside it.

Inside the void function, we have taken two numbers as inputs from the user. Then, we have casted into int and stored them into two variables named num1 and num2, respectively.

When we have called the void function voidOperation() from inside another function main_fn(), the voidOperation() function performs the operation to calculate the sum of two numbers and prints the result on
the console.

Example 2 :
Writing a program in Python in which we will find even and odd numbers till n numbers using continue statement. We will take n numbers as input from the user.

# Python program to find even and odd numbers till n.


def EvenOddFunc(num):
for i in range(1, num + 1):
if i % 2 == 0:
print('Even number: ',i)
continue
print('Odd number:',i)
def main_fun():
number = int(input('Enter your number till you want to find an even or odd number: '))
EvenOddFunc(number) # calling the function from another function with passing input.
main_fun() # calling main function.

Output

Enter your number till you want to find an even or odd number: 5
Odd number: 1
Even number: 2
Odd number: 3
Even number: 4
Odd number: 5

Example 3 :
Writing a program in Python in which we will take a number from the user and check whether it is a palindrome.

A palindrome number is that number that when we read in reverse order is the same as is read in right order. For example, 121, 125521, 610016, etc.

# Python program to check whether a number is palindrome.


def checkPalindrome(n):
String = ""
if n.isdigit():
length_of_string = len(n) # len() function finds the length of a string n.
iNum = int(n) # converting string into integer.
while iNum != 0:
remDigit = iNum % 10
String = String + str(remDigit)
iNum = iNum // 10
if n == String:
print('Number is a palindrome.')
else:
print('Number is not a palindrome.')
def main_fn():
N = input('Enter a number: ')
checkPalindrome(N)
main_fn()

Output

Enter a number: 121


Number is a palindrome.
Enter a number: 123321
Number is a palindrome.

Example 4 :
Writing a program in Python in which we will accept a number from the user and check whether a number is a perfect number.
We will call a number as perfect number if it is equal to the sum of its factor other than the number itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3.

# Python program to check whether a number is a perfect number.


def num_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum = sum + i
if sum == num:
print('Number is a perfect number.')
else:
print('Number is not a perfect number.')
def main_fn():
N = int(input('Enter a number to check a perfect number: '))
num_perfect(N)
main_fn()

Output

Enter a number to check a perfect number: 28


Number is a perfect number.
Enter a number to check a perfect number: 6
Number is a perfect number.

Example 5 :
Writing a Python program in which we will take marks of five subjects from a student as a user and calculate the total marks, percentage, and then display them on the console.

# Python program to calculate total marks and percentage of student's marks.


def marks(m1, m2, m3, m4, m5):
total_marks = m1 + m2 + m3 + m4 + m5
percentage = total_marks / 5
print('Total marks obtained = ', total_marks)
print('Percentage =', percentage)

# Main part of program.


def main_func():
m1 = int(input('Enter your Science marks: '))
m2 = int(input('Enter your Maths marks: '))
m3 = int(input('Enter your English marks: '))
m4 = int(input('Enter your Computer marks: '))
m5 = int(input('Enter your Hindi marks: '))
marks(m1, m2, m3, m4, m5)
main_func() # calling main function.

Output

Enter your Science marks: 89


Enter your Maths marks: 90
Enter your English marks: 96
Enter your Computer marks: 89
Enter your Hindi marks: 78
Total marks obtained = 442
Percentage = 88.4

8 Scope in Python Variable Scope, Lifetime


If we define a variable inside a function or pass a value to a function’s parameter, the value of that variable is only really accessible within that function. This is called scope.

In other words, the scope is the region of a program where we can access a particular identifier or variable. This is called scope of variable or simply variable scope.

Variables declared inside a program may not be accessible at all locations of that program. It depends on the where we have declared a variable in a program.

Most variables that we define in Python are local in scope to their own function or class.
Example 1 :

# Python program demonstrates the variable's local scope.


def localScope():
name = 'John'
print(name) # Accessible.

# Main program.
print(name) # Not accessible because the variable name is undefined here.
localScope() # calling function.

Output

print(name) # Not accessible because the variable name is undefined here.


NameError: name 'name' is not defined

Explained in Detail
In the above example, the variable name defined inside the function will be accessible within that entire function. Therefore, we have easily accessed and printed the value of variable name on the console.
But, when we accessed from the main program that calls the function, then we got NameError. This is because the variable defined within a function has a local scope and is only visible inside the function, not
outside the function.
Variable Scope and Lifetime in Python

Scope : Scope of variable is a region of the program where a variable is visible or accessible.

Lifetime : Lifetime of a variable is the duration for which a variable exists in the memory.

Lifetime of a variable declared inside a function is as long as the function is alive. When the execution of function body is finished, then the variable defined inside a function will destroy.

Types of Scope of Variables in Python


There are two basic types of scope of variables in Python. They are:

Global scope
Local scope

Global Scope in Python

When we define a variable inside the main program but outside the function body, then it has a global scope. The variable declared in the main body of the program or file is a global variable.

In the global scope, the global variable will be visible throughout the program or file, and also inside any file which imports that file. We can easily access a variable defined in global scope from
all kinds of functions and blocks.

Example 1 :
Writing a program in Python in which we will define a global variable and access it from both inside the function and main program body.

# Declaring a global variable in the global scope.


x = 50
# Declare a simple function that prints the value of x.
def showMe():
print('Value of x from local scope = ',x) # calling variable x inside the function.

# Main program.
showMe() # calling function.
print('Value of x from global scope = ',x)

Output

Value of x from local scope = 50


Value of x from global scope = 50

Explained in Detail
In this example, variable x is a global variable. We have accessed it from both inside the function and outside the function because it has a global scope.

Local Scope
A variable defined or created inside a function body or a block has a local scope. We can access it only within the declared function or block and not from outside that function or block.
As the execution of function body or block is finished, Python destroys the local variable from the memory. In other words, local variable exists in the memory as long as the function is executing.

Example 1 :
Writing a program in which we will define a local variable within in a function and we will access it inside a function and from outside the function.

def my_funct():
msg = 'Good morning!' # local variable with local scope.
print(msg) # accessing local variable from inside the function.
my_funct()
print(msg) # accessing local variable from outside the function.

Output

Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined

Explained in Detail
As you can see in the output, as we called local variable from outside the function or main program, we got error because Python destroyed the local variable after the execution of function. That is, the local
variable does not exist outside the function.

When we define a variable inside the function, it is not related to any way to another variable with the same name used outside the function.

Example 2 :
Writing a program, where a variable defined outside a function will be read inside a function only when the function does not change the value.

# Creating a variable city and set to New York.


city = 'New York' # global scope.
def showMe():
city = 'Dhanbad' # local scope within a function.
print('City:',city)
# Function call
showMe()
print('City:',city) # accessing global variable from the global scope.

Output

City: Dhanbad
City: New York

Explained in Detail
In the above program code, first we have assigned a value ‘New York’ to the city, and then printed the value of city on the console after calling the function.

Next, we have created a function named showMe(). Inside the function showMe(), we have defined a variable with the same name as that of global variable but with a change value.

When we accessed this variable, then Python prints the change value on the console, not the value of global variable because it is not related to any way to another variable with the same name used outside the
function.

As the execution of function body is completed, the value of city is destroyed because it is a local variable to that function only.

9 Global in Python Global Keyword


Global in Python is a keyword that we use to make a variable global in the function. A global keyword allows us to modify a variable outside of the current scope.

The scope of local variable is limited to the function or block in which we specify it. Furthermore, when we define a variable within a function or block, that variable is local by default.

We can use it only within that function because it is not accessible outside.

But, we can create a variable global within a function using global keyword. When we define a variable with a keyword global inside a function, we call it as global statement in Python.

Example 1 :
Writing a program by declaring a global statement using the global keyword to better understand the definition.

# Global variable inside a function.


def my_funct(): # function header.
global x; # global statement.
x = 50 # x is not local it is a global because of global keyword.
my_funct() # function calling.
print(x) # prints the value of global variable.

Output
50

Explained in Detail
As you see in the above example program, we can easily access the global variable declared inside a function from outside the function.

Rules used for Global Keyword in Python


The some basic rules for global keyword in Python that you should keep in mind. They are as follows:

We use a global keyword to make a variable global inside the function.


There is no need to use global keyword outside the function because it has no effect.
Variables that are not referenced within a function, they are implicitly global by default.

Example 1 :
Writing a program in which we will access a global variable from the inside of a function.
x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Accessing global variables inside the function.
print(x)
print(y)
my_func()

Output
10
20

Example 2 :
Writing a program in which we will try to modify the global variable from inside a function.

x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Trying to modify the global variable inside the function.
x = x + 30
print(x)
print(y)
my_func() # function call.

Output
UnboundLocalError: local variable 'x' referenced before assignment

Explained in Detail
Here, we have created two global variables, namely x and y. Inside the function my_func(), we are updating the value of x by incrementing by 30. No updating is in the value of b.
Since we are trying to modify the global variable x inside the function without using global statement, therefore, it has displayed error. Because we can only access the global variable but cannot modify it inside the
function.
Example 3 :
Writing a programe, to use the global keyword. Using global statement, we can modify or update the value of global variable x inside the function.

x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Modify the global variable inside the function using global statement.
global x # global statement.
x = x + 30
print(x)
print(y)
my_func()

Output

40
20

Explained in Detail
In the above program code, we have defined x as the global keyword inside the function my_func(). Then, we have incremented the variable x by 30, i.e. x = x + 30.

As we can see in the output while calling my_func(), the value of global variable x is modified from 10 to 40.

Local Variable having the same name as Global Variable


Let’s write a program in which we will define a local variable having the same name as that of global variable in the program. In such a case, Python creates a new local variable of that name, different from the
global variable.

Example 1 :

x = 50
def showMe():
x = 60
print('Inside function, x =',x)
showMe()
print('Outside function, x =',x)

Output

Inside function, x = 60
Outside function, x = 50

Example 2 :

x = 10
def my_func1():
x = 20
print('Inside my_func1, x = %d'%x)
def my_func2():
global x
x = x + 30
print('Inside my_func2, x = %d' %x)

print('x starts at %d' %x)


my_func1()
print('After my_func1, x is now %d' %x)
my_func2()
print('After my_func2, x is now %d' %x)

Output

x starts at 10
Inside my_func1, x = 20
After my_func1, x is now 10
Inside my_func2, x = 40
After my_func2, x is now 40

Explained in Detail
In this example, first we have defined a variable x and assigned a value 10 to it. Then, we have defined two functions my_func1() and my_func2().

In the my_func1() function, we have defined a variable x and assigned the value of 20 to it. This variable x has a local scope, which is strictly only for use within this function.

Inside the my_func2() function, we have defined a variable x with a global keyword. Since we have used global keyword, it refers to the global variable, not local scope.

Now anything happens to the variable x within the routine will change in the value of variable declared in the first line of code.

Now the code continues and will print the statement “x starts at 10”. Then, calls function my_func1(), which creates its own variable x, assigns the value 20 to it and prints the output.

When the program control comes back from that, it prints “After my_func1, x is now 10”. Next, we have called the function my_func2().

Since we have declared that variable x in the function is the global one, it gets changed to 40 and printed. On return from the function, it prints “After my_func2(), x is now 40”.

Example 3 :
Writing a program where global keyword within a nested function.

# Outer function.
def outer_func():
x = 30
# Inner function.
def inner_func():
global x
x = 60

print("Before inner_func() call, x is",x)


inner_func() # Inner function call.
print("After inner_func() call, x is",x)

# Outer function call.


outer_func()
print("Outside both function, x is",x)

Output

Before inner_func() call, x is 30


After inner_func() call, x is 30
Outside both function, x is 60

Explained in Detail
Here, we have declared a global variable inside the nested function inner_func(). Inside outer_func(), x has no effect of the global keyword. Before and after inner_func() function call, x takes the value of the local
variable, i.e. x = 30.

Outside the outer_func() function, x will take the value defined in the inner_func() function, i.e. x = 60. Because we have used the global keyword with x to construct a global variable inside the inner_func()
function (local scope).

Therefore, if we make any changes inside the inner_func() function, the changes will also appear outside the local scope, i.e. outer_func().

Chapter 6 :
Strings in Python

1 Mutable and Immutable in Python


2 Strings in Python Accessing
3 Python String Length len() Function
4 String Concatenation in Python
5 String Comparison in Python
6 String Slicing in Python
7 Iterate over a String in Python
8 String Formatting in Python

1 Mutable and Immutable in Python

Here, we will learn about the meaning of mutable and immutable objects in Python.
We know that everything in Python is an object. For example, objects or relation between objects represent all the data in a Python program.
Every object in Python has three characteristics. They are:

Identity
Data type
Value
An object’s identity never changes once it has created. That is, it is unchangeable. It refers to the address of an object in the computer’s memory.
The is operator compares the identity of two objects and the id() function returns a unique identification value (as an integer) of the object stored in the memory. This unique identification value represents the
identity of an object.
An object’s data type refers to the type of object that is created. Integer, list, string, etc. are examples of an object’s data type. It also defines the types of values that an object can take.
Mutable and Immutable Object’s Value in Python

Object’s id and type cannot be changed once it has been created, only the value of some objects can change. There are two types of an object’s values or data in Python. They are:

Mutable data type


Immutable data type

Mutable Data type in Python

The term mutable means changeable. An object that value or data can change during the execution of a program is called a mutable object or mutable data type. The values of a mutable object can
change after it has created.

In other words, we can change the value of a mutable variable after it has created. The examples of Python’s mutable data types are as:

List
Set
Dictionary
Bytearray
Array

The values of these data types in Python can change after their assignment or creation. When the value of a mutable object is changed, the Python interpreter does not reallocate its memory.

Example 1 :
Writing a program to demonstrate a list of a mutable data type in Python.

# Creating a list of values.


list = ['cat', 'dog', 'goat', 'cow']
print('Original list:',list)
print('Id of original list:',id(list))
# Performing append operation in the current list.
list.append('Buffalo')
# Printing the list after the append operation.
print('List after appending a value: ',list)
print('Id of list after operation:',id(list))
# Removing a value from the list.
list.remove('dog')
# Printing the list after the remove operation.
print('List after removing a value:',list)
print('Id after remove a value:',id(list))

Output
Original list: ['cat', 'dog', 'goat', 'cow']
Id of original list: 1171325498496
List after appending a value: ['cat', 'dog', 'goat', 'cow', 'Buffalo']
Id of list after operation: 1171325498496
List after removing a value: ['cat', 'goat', 'cow', 'Buffalo']
Id after remove a value: 1171325498496

Explained in Detail
In the above program, we have created a list of values and performed multiple operations to demonstrate that a list is a mutable object whose values we can change.

Initially, we created a dummy list and printed the values of list and its id using id() function. Then, we appended a value to the current list, and printed the updated list and its id.

As you will notice, that list’s value has changed, but its identity remains the same (1171325498496). This shows that a list in Python is a mutable object whose values can be changed after creation.

Example 2 :
Writing a program in which we will change the value of a list by using assignment operator in Python.
# Creating a list of values.
list = [20, 40, 60, 80, 100]
print('Original list:',list)
print('Id of original list:',id(list))

# Changing the value of list.


list[2] = 50
print('Updated list:',list)
print('Id of updated list:',id(list))

Output

Original list: [20, 40, 60, 80, 100]


Id of original list: 2625015100544
Updated list: [20, 40, 50, 80, 100]
Id of updated list: 2625015100544

Example 3 :
Writing a program in which we will concatenate a new list into the old list using + operator.

# Creating a list of values.


list = [20, 40]
print('Original list:',list)
print("Original list's id:",id(list))
# Adding a list of values into old list.
list = [20, 40] + [60, 80]
print('New list:',list)
print("New list's id:",id(list))

Output

Original list: [20, 40]


Original list's id: 1882487698560
New list: [20, 40, 60, 80]
New list's id: 1882487986304

Explained in Detail
As you can observe in the above program code, list concatenation creates a new list with a new identity (i.e. new memory address). When it happens, the garbage collector removes the old list from the memory
because it is garbage.

Example 4 :
Writing a program to demonstrate a set of a mutable data type in Python.

# Creating a set of values.


my_set = {10, 20, 30}
# Printing set and its id.
print('Original set:',my_set)
print("Original set's id:",id(my_set))
# Adding a new value in the set.
my_set.add(15)
# Printing the set after the add operation.
print("Set after adding a value:",my_set)
print("Set's is after adding value:",id(my_set))

Output

Original set: {10, 20, 30}


Original set's id: 1999656034912
Set after adding a value: {10, 20, 30, 15}
Set's is after adding value: 1999656034912

Immutable Data types in Python

The term immutable means unchangeable. An object that value or data cannot change in its place after initialization or assignment during the execution of a program is called an immutable object or
immutable data type.

The values of an immutable object cannot change after it has created. In other words, we cannot change the value of an immutable variable after it has created.

Examples of Python’s immutable data types or objects or variables are as follows:

Integers
Floating-point numbers
Boolean
Strings
Tuples
Frozen set
Bytes

The values of these data types in Python cannot modify after their assignment or initialization. When the value of an immutable object modify, the Python interpreter always allocates a new memory location.

Example 1 :

# Creating a string.
str = 'Hello'
print('Original string:',str)
print("Id:",id(str))
# Modifying the value in existing string, but Python will create new string object.
str = 'Good bye'
print('New string:',str)
print("Id:",id(str))

Output

Original string: Hello


Id: 2171413179952
New string: Good bye
Id: 2171413182960

Explained in Detail
From the above code, it seems that whenever we override the value of variable, it might look like we are changing the object’s value. Actually, it is not happening.

Here, we are not changing the object’s value from “Hello” to “Good bye”. Actually, the reference variable str has only switched to refer from the “Hello” object to “Good bye” object.

Both are two different string objects having two different identities. Both string objects have different memory locations or ids.

This shows that string is an immutable object, meaning that whenever we try to modify a string object’s value, Python interpreter always allocates a new memory location with a new address. It never changes the
string object’s value in the existing place. Attempting to modify the value of string is not allowed in Python.

2 Strings in Python Accessing

Strings in Python are a sequence of characters, which consist of one or more letters, numbers, punctuation marks, and spaces.

For example, “Python” is a string which contains a sequence of six characters ‘P’, ‘y’, ‘t’, ‘h’, ‘o’ and ‘n’.

String is one of the most popular and useful data types in Python. Therefore, Python provides lots of features and functions for it.

In Python, strings are immutable objects of the built-in str class, which store the sequence of characters, called string.

To create strings or a string literal in Python, we must enclose it in either single (‘), double (“) or triple (”’ or “””) quotes and assign it to a variable. The general syntax to create or initialize a string is as:
<name of string> = "<value of string>"

# Create a string using double quotes.


language = "Python" # Here, language is the name of variable of string type.

Here, we have created a string variable named language and assigned it with a value “Python” in double quotes. Since a string is an array of characters, whenever we store a string into a variable, the first
characters always get placed at index number 0.

Look at the below figure to understand better where the first letter of ‘Python’ string has placed at index number 0, second at index number 1, and so on.

Accessing String Characters in Python

In Python, we can access individual characters of a string through index and a range of characters by slicing. An index is a number which denotes the position of elements.

From left to right, the indices start at 0, not 1. So, the first character of a string takes zero as its index number and succeeding characters take 1, 2, 3… and so on as index numbers. Index of the last character is
always (length of string – 1).

To access the characters of a string, just write the variable name and enclose the integer number inside the index operator or square brackets [ ].

Example 1 :
Writing a program in which we will access the characters of a string.

# Python program to access the characters of a string literal.


msg = 'Goodbye'
print('String:', msg)
# Access the first character from left of the string.
print('First character of sting:',msg[0])
# Access the second character from left of string.
print('Second character of sting:',msg[1])
# Access the third character of string.
print('Third character of sting:',msg[2])

# Access the last character of string.


print('Last character of sting:',msg[len(msg) - 1])

Output
String: Goodbye
First character of sting: G
Second character of sting: o
Third character of sting: o
Last character of sting: e

Explained in Detail
Indexing also allows negative address references to access the characters of a string from backwards (i.e. from right to left). For example, the last character takes -1 as its index, the second last character takes
-2 as its index, and so on.

Example 2 :
Writing a program on the taking negative index number for accessing characters of a string.

# Program to access the characters of a string from backwards.


language = 'Python'
print('String:',language)
# Access the first character of string from back.
print('First character of sting:',language[-1])

# Access the second character of string from back.


print('Second character of sting:',language[-2])
# Access the last character of string from backwards.
print('Last character of sting:',language[-6])

Output

String: Python
First character of sting: n
Second character of sting: o
Last character of sting: P

Strings are immutable objects in Python

In Python, strings are immutable objects, meaning once we create it, we can no longer change it. That is, their values cannot be change or modified.

If we try to modify it either by taking a new value, or concatenating another string on the end, etc., Python interpreter will automatically allocate a new space in the memory for a new string object.

So, we cannot perform any changes with the existing string object in Python. This non-changeable behavior is nothing but a string immutability in Python.

Example 1 :

# Program to demonstrate that string is an immutable object or data type.


str = 'Python'
print('Original string:',str)
print('Id of original string:',id(str))
str = str + ' Programming'
print('Modified string:',str)
print('Id of modified string:',id(str))

Output

Original string: Python


Id of original string: 2466945975984
Modified string: Python Programming
Id of modified string: 2466950814480

Explained in Detail
In the above example program, it looks like we have assigned a string “Python” to a variable str of string type and then appended a string “Programming” to string str.

Thus, the string looks mutable in nature. In fact, it is not happening. When the operation str + “Programming” will be performed, a new string object will create and assign back to str, and deallocate the old string.
In other words, when Python will execute the statement str = str + ” Programming”, it will create a new string object in the memory for storing a new value.

To understand more it clearly, we have used a built-in id() function that returns the identity of an object. Look at the output that the memory address of string object before and after update is different. This shows
that we cannot modify or update the value in the existing string object.
3 Python String Length len() Function
In Python or other programming language, the length of a string is the total number of characters present in a string.

To find the length of a string, Python provides a built-in function named len().

This len() function returns the length of a string object or the total numbers of characters present in the string object. It counts all characters, numbers, and symbols enclosed in ” “.

Example 1 :
Writing a program in Python to find the length of a string using len() function.

# Python program to find the length of the string.


str = "Python"
# Call len() function to find string length.
length_of_string = len(str)
print('Length of string is',length_of_string)

Output
Length of string str is 6

Example 2 :
Writing a program to find the number of characters present in the string using len() function.

language = "Python Programming"


# Call len() function to find string length.
length_of_string = len(language)
print(f'Number of characters in the string "{language}" is',length_of_string)

Output
Number of characters in the string "Python Programming" is 18

Example 3 :
Writing a program in Python to calculate the length of list, tuple, set, and dictionary using len() function.

num_list = [10, 20, 30, 40, 50, 60]


length_list = len(num_list)
print('Total number of elements in list is',length_list)

name_tuple = ('john', 'harry', 'bob', 'mark')


length_tuple = len(name_tuple)
print('Total number of elements in tuple is',length_tuple)

city_set = {'Dhanbad', 'Godda', 'Sydney', 'New York'}


length_set = len(city_set)
print('Total number of elements in set is',length_set)

dic = {1: 'one', 2: 'two', 3: 'three'}


length_dic = len(dic)
print('Number of elements in dic is',length_dic)

Output

Total number of elements in list is 6


Total number of elements in tuple is 4
Total number of elements in set is 4
Number of elements in dic is 3

4 String Concatenation in Python

String concatenation means joining or combining two or more strings. Joining of two or more strings to make them one is called string concatenation in Python.

In general, Python provides (+) operator to concatenate multiple strings. We can concatenate two or more strings, or a string with a number or symbol to display information as per requirements.

For example, when you fill an online registration form, you fill your first name, middle name, and last name in three separate columns.

But when you finish the form, then you see your complete name as a single string. This is a realtime use of string concatenation in Python.

Example 1 :

# Python program to demonstrate the string concatenation.


# Take first name as input from the user.
first_name = input('Enter your first name: ')

# Take middle name as input from the user.


middle_name = input('Enter your middle name: ')
# Take last name as input from the user.
last_name = input('Enter your last name: ')

# Concatenate strings using + operator.


string_concatenation = first_name + " " + middle_name + " " +last_name
print("Full name:",string_concatenation)

Output

Enter your first name: Tripti


Enter your middle name: Deepak
Enter your last name: Priya
Full name: Tripti Deepak Priya

Explained in Detail
In the above example code, we have taken first name, middle name, and last name as inputs from the user using input() function and stored into variables named first_name, middle_name, and last_name,
respectively.

Then, we have concatenated all strings using (+) operator, stored in a variable named string_concatenation, and printed it on the console. Thus, we can combine several strings into one large string using the +
operator.

Ways to Concatenate Strings in Python


String concatenation is heavily used in Python programming. There are five convenient and best ways to concatenate strings. They are as:

Using + operator
Using join() method
By using % operator
By using format() function
Using f-string (Literal String Interpolation)
Example 1 :
Writing a program to add multiple strings together to make them one.
# Python program to join three strings.
str1 = 'Python'
str2 = ' Programming' # string with a space.
str3 = ' Language' # string with a space.

concatenated_string = str1 + str2 + str3


print('Joined string:',concatenated_string)
Output
Joined string: Python Programming Language

Example 2 :

# Python program to join a number with a string.


num = 25
str = 'twenty-five'
# Joining a number with string.
concatenated_string = num + str
print('Joined string:',concatenated_string)

Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explained in Detail
In the above example, we have used the (+) operator to concatenate two values of different data types. We are trying to join string data type with integer data type. Therefore, Python generates TypeError error.

Example 3 :
Writing a program to concatenate integer number with a string.
You first need to convert integer data type into string data type using str() function and then concatenate both string values.

# Python program to join two strings.


num = 20
# This statement converts integer type into string type.
str1 = str(num) # returns a string version of the object.
str2 = 'twenty'

# Joining two strings.


concatenated_string = str1 + str2
print('Joined string:',concatenated_string)

Output
Joined string: 20twenty

Explained in Detail
In the above code, we have used str() function to convert an integer data type into string data type. This function returns a string version of object. If we do not provide any object, it returns an empty string.

Example 4 :
Writing a program to concatenate an integer type with string type without using str() function if you write integer type into string type.

# Python program to join two strings.


str1 = '25' # number in string type.
str2 = 'twenty-five'
# Joining strings.
concatenated_string = str1 + str2
print('Joined string:',concatenated_string)

Output
Joined string: 25twenty-five
Example 5 :
Writing a program by using multiplication operator (*) to repeat a string number of times
# Python program to repeat a string number of times.
str = 'Love' * 4 # Multiplying strings.
print('Repeated string:',str)

Output
Repeated string: LoveLoveLoveLove

Example 6 :

str1 = 'Python'
str2 = str1 * 2
print(str2)

str3 = (str2) * 2
print(str3)

str4 = 2 * ('Love', 'Python')


print(str4)

Output

PythonPython
PythonPythonPythonPython
('Love', 'Python', 'Love', 'Python')

String Concatenation using join() Method

We can join strings by using join() method. This function provides a flexible way to concatenate strings. The general syntax for join() method is as:
string_name.join(sequence)

Example 1 :

# Python program to concatenate strings using join() method.


first_name = 'Ivaan'
middle_name = 'Vidya'
last_name = 'Sagar'

# This statement inserts blank space between each sequence of strings.


full_name = ' '.join((first_name, middle_name, last_name))
print("Full name:",full_name)

dob = ["23","12","2016"]
my_dob = '/'.join(dob)
print('Date of birth:',my_dob)

Output

Full name: Ivaan Vidya Sagar


Date of birth: 23/12/2016

Explained in Detail
In this example, we have inserted a blank space between each sequence of string using join() function and stored returned concatenated string in the variable full_name.

In dob list variable, all the elements in the list are of string type. We have inserted ‘/’ between each of the list elements and stored the returned joined string into a variable my_dob and then displayed it on the
console.

Example 2 :

# Python program to concatenate strings using join() method.


str = 'Python'
str2 = 'Programming'
institute_name = " ".join((str, str2))
print('Institute name:',institute_name)
address = ['Dhanbad','Jharkhand']
print('Address:',", ".join(address))

Output

Institute name: Python Programming


Address: Dhanbad, Jharkhand

Joining Strings using Formatting Operator (%)


We can also use a string formatting operator (%) for joining two or more strings or string and number.
Example 1 :
# Python program to concatenate strings using formatting operator %.
first_name = 'John'
last_name = 'Smith'
full_name = "% s % s" % (first_name, last_name)
print('Full name:',full_name)

day = 20
month = 'Oct'
year = 2002
dob = "% s % s % s" % (day, month, year)
print("Date of birth:",dob)

Output
Full name: John Smith
Date of birth: 20 Oct 2002

Concatenating String using format() function


We can also use format() function to concatenate strings. This function uses positional formatting to concatenate string in the sequence. We use curly braces ({ }) to position a sequence of strings in a specific
order.
Example 1 :

# Python program to concatenate strings using format() function.


first_name = 'John'
last_name = 'Smith'
full_name = "{} {}".format(first_name, last_name)
print('Full name:',full_name)

day = 12
month = 'Nov'
year = 2010
dob = "{} {} {}".format(day, month, year)
print("Date of birth:",dob)

Output

Full name: John Smith


Date of birth: 12 Nov 2010

String Concatenation using f-string


If you are using Python 3.6+, you can also use f-string for concatenating strings. PEP 498 introduced a new way to format strings known as Literal String Interpolation or f-string. To create an f-string, prefix the
string with the letter “ f ”.
Example 1 :

# Python program to concatenate strings using f-strings.


fName = 'John'
sName = 'Smith'
fName = f'{fName} {sName}'
print('Full name:', fName)

age = 34
print('Age:',f'{age}')

Output

Full name: John Smith


Age: 34

5 String Comparison in Python

In Python or any other programming language, string comparison means identifying whether or not two strings are equivalent to each other.
Basically, Python provides us three general ways by which we can compare between two strings. They are as:

Using relational operators


Using is and is not
User-defined function

Python String Comparison using Relational Operators


Relational operators return a boolean value, True or False, according to the operator used. Following are the relational operators available in Python programming language.

Operator (==): This “equal to” operator checks whether or not two strings are equal.
Operator (!=): This “not equal” operator checks if two strings are not equal.
Operator (>): This “greater than” operator checks if the string on its left side is greater than that on its right side.
Operator (<): This “less than” operator checks if the string on its left side is smaller than that on its right side.
Operator (>=): This “greater than or equal to” operator checks if the string on its left side is greater than or equal to that on its right side.
Operator (<=): This “less than or equal to” operator checks if the string on its left side is smaller than or equal to that on its right side.

Example 1 :

# Python program to compare two strings using comparison operators.


str1 = 'january'
str2 = 'jane'
print(str1 == str2)
print(str1 != str2)
print(str1 > str2)
print(str1 >= str2)
print(str1 < str2)
print(str1 <= str2)

Output

False
True
True
True
False
False

Example 2 :
# Python program to compare two strings using comparison operators.
print('abc' == 'abc')
print('abc' != 'abc')
print('a' == 'A')

print('a' != 'A')
print('abc' > 'ABC')
print('1234' > '4567')

Output

True
False
False
True
True
False

Example 3 :

# Python program to compare a string with an empty string.


str1 = 'Python'
str2 ='' # an empty string.
print(str1 == str2)
print(str1 > str2)
print(str1 < str2)
print(str1 != str2)

Output

False
True
False
True

Example 4 :

str1 = 'abc'
str2 =' abc' # space before letters in the string.
print(str1 == str2)
print(str1 > str2)
print(str1 < str2)
print(str1 != str2)

Output

False
True
False
True

Comparing String using Identity Operators


In Python, we can also compare two strings with the help of identity operators. Python supports two types of identity operators. They are:
is and is not.
Example 1 :

# Python program to compare two strings using identity operators.


str1 = 'Python'
str2 ='Python'
str3 = str1

# Comparing two strings using is and is not operators.


print(str1 is str1)
print(str1 is str2)
print(str1 is str3)

print(str1 is not str2)


print(str1 is not str2)
print(str1 is not str3)

Output
True
True
True
False
False
False
Explained in Detail
In this example, str1, str2, and str3 are string objects with the same values. Therefore, they are equal, identical, and stored in the same memory location. Hence, ‘is’ identity operator returned true value and ‘is
not’ operator returned false value.

Example 2 :

str1 = '1234'
str2 = '1234'
if str1 is str2:
print('Both strings are identical.')
else:
print('Both strings are not identical.')

Output
Both strings are identical.
Example 3 :

str1 = 'abcd'
str2 = input('Enter a string "abcd": ')
print(str1 is str2)

str3 = 'pqrs'
str4 = input('Enter a string "pqrs": ')
print(str3 is not str4)

Output

Enter a string "abcd": abcd


False
Enter a string "pqrs": pqrs
True

Explained in Detail
In this example, the statement print(str1 is str2) returns false value because both are referring to the different string objects in different memory locations instead of having the same value.

Similarly, the statement print(str3 is not str4) returns true value because both are referring to the different string objects in different memory locations instead of having the same value.

Comparing String using User-defined Function


In Python, we can also create a user-defined function to compare strings. A user-defined function compares two strings based upon the number of digits.
Example 1 :

# Python program to compare two strings based on the number of digits.


def string_comp(str1, str2):
count1 = 0
count2 = 0
# Find the length of strings using len() function.
len_str1 = len(str1)
len_str2 = len(str2)

for i in range(len_str1):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1 # increment by 1.

for i in range(len_str2):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1 # increment by 1.
return count1 == count2 # comparing.
# Mian program.
# Calling function by passing argument values.
print(string_comp("1234", "1234"))
print(string_comp('345', '1234'))
print(string_comp('Programming', 'Programming'))

Output

True
False
True

6 String Slicing in Python


String slicing in Python is a technique in which we can obtain a sub-part of the original string by specifying a range of index numbers separated by a colon.

A sub-part of the original string is called substring. It is any sequence of characters which already exists in the original string.

With string slicing, we can access a range of characters in a string or create substring.

Example 1 :

# Program to demonstrate the string slicing in Python.


# Original string.
string = 'Language'
my_sub = string[0:4] # string slicing.
print("Substring:",my_sub)

Output
Substring: Lang

Explained in Detail
In the above code, we have obtained a substring of four characters starting from 0 to 4. The square brackets ([ ]) is an array operator. The first index is inclusive and the last index is exclusive. So, 0:4 means 0 to
3 sequence of characters, not 4th character. Look at the below figure to understand string slicing better.
Ways to Perform String Slicing in Python
There are basically two ways to perform string slicing in Python. They are as:

Using slice() method (Built-in method)


Using array slice operator

String Slicing by slice() Function

Python provides a built-in function named slice() that we can use to obtain a slice (i.e. subpart) of elements from the collection of elements.

This function returns a slice object we can use to slice strings, lists, tuples, sets, bytes, or range objects. Python language provides two overloaded slice() functions.

The first function takes a single formal parameter ‘stop’ index, while the second function takes three formal parameters ‘start’ index, ‘stop’ index, and ‘step’ value as well.

The general syntax for slice() function with parameters is as:

slice(stop)
slice(start, stop, step)

Parameters:
(a) A start parameter specifies the starting index at which the slicing of string object begins.

(b) A stop parameter specifies the ending index where a string object’s slicing comes to a halt. The slice() function excludes the stop index while generating the substring. That is, the slice() doesn’t stop ‘at’ or
‘after’ the stop index. It stops just before this index when performing slicing.

(c) A step parameter is an optional parameter that specifies the increment between each index for slicing. It basically refers to the number of characters that we can skip after start indexing character in the string.

If you pass only one parameter, start and stop parameters are considered to be None.

Example 1 :

# Program to demonstrate the string slicing.


# Original string.
string = 'Welcome to Programme Java'
# This statement starts the slice object at position 0 and slice up to position 7 and returns the result.
my_sub1 = slice(7) # returns slice object.
print('my_sub1 object',my_sub1)
print('Substring from 0 to 7:',string[my_sub1])

# This statement starts the slice object at position 11 and slice up to position 21 and returns the result.
my_sub2 = slice(11, 21) # returns slice object.
print('my_sub2 object:',my_sub2)
print('Substring from 11 to 21 :',string[my_sub2])

# This statement uses the step parameter to return every second element.
my_sub3 = slice(0, 20, 2)
print('Substring containing every second elements:',string[my_sub3])

Output
my_sub1 object slice(None, 7, None)
Substring from 0 to 7: Welcome
my_sub2 object: slice(11, 21, None)
Substring from 11 to 21 : Programme
Substring: Wloet cetc

String Slicing using slice operator

We can obtain a substring of an original string using slice operator. It is an easy and convenient way to slice a string. To slice or access a range of characters in a string or create a substring, use the slice operator
[:].
The general syntax for slicing string is as:
string_name[start:end[:step]]

In the above syntax, a colon specifies the range of value. It also separates the two indices. We can access the substring within an original string by specifying a range of index number by colon.

This slice syntax returns the sequence of characters beginning at the start index and extending up to but not including the end index. The start and end values should be an integer. We can perform string slicing
operation using either positive or negative indexing.

Example 1 :
Writing a program in which we will perform string slicing operation using range slice operator.

Here, we will create a variable named healthy_juice and assign it with a string value “Tomato juice”. The sequence of characters of this string will be index, starting from 0, and so on, as shown in the below figure.
# Python program to demonstrate the string slicing using range slice operator.
# Original string.
healthy_juice = 'Tomato juice'
print('Original string:',healthy_juice)
# This statement starts to slice string at position 0 and slices up to position 4 and returns the result.
my_sub1 = healthy_juice[0:4]
print('Substring from 0 to 4:',my_sub1)

# This statement starts to slice string at position 0 and slices up to position 6 and returns the result.
my_sub2 = healthy_juice[:6]
print('Substring up to 6:',my_sub2)

# This statement starts string slicing at position 6 and slices up to end.


my_sub3 = healthy_juice[6:]
print('Substring up to end:',my_sub3)

# This statement does not slice the string and displays the entire string.
my_sub4 = healthy_juice[:]
print('Entire substring:',my_sub4)

# This statement produces an empty string.


my_sub5 = healthy_juice[4:4]
print('Empty string:',my_sub5)
# This statement starts to slice the string at position 6 and slices up to end position (including).
my_sub6 = healthy_juice[6:12]
print('Substring up to end:',my_sub6)

Output

Original string: Tomato juice


Substring from 0 to 4: Toma
Substring up to 6: Tomato
Substring up to end: juice
Entire substring: Tomato juice
Empty string:
Substring up to end: juice

Explained in Detail
In the above example program, we have created a variable named healthy_juice and assigned a string “Tomato juice”.

(a) In my_sub1, we have sliced the original string from the position 0 up to position 4 and stored the returned result in a variable my_sub1.

(b) In my_sub2, we have not included the start index number. Therefore, slicing starts from position 0 and goes up to index number 6. We have stored the returned result in a variable my_sub2.

(c) In my_sub3, we have not included the stop index value. Therefore, slicing starts at position 6 and slices the original string up to the end of string index.

(d) In my_sub4, we have not omitted the start and stop index value. So, the entire string will display.

(e) If the start index number is equal to or higher than end index number. In my_sub5, the start index number is equal to end index number. Therefore, it displays an empty string.

(f) In my_sub6, the end index number is beyond the end of string. Therefore, it stops at the end of string.

7 Iterate over a String in Python


In Python or other programming language, iterate over a string means accessing each of its characters of a string one by one.

Since a string is a sequence of characters, we can iterate or traverse each character of the string. This process is called traversing or iteration.

There are basically three ways to iterate over characters of a string in Python. They are:

Using for loop


Using while loop
Using enumerate() function

Example 1 :
Writing a Python program in which we will iterate or traverse over each character of a string using for loop.

# Python program to iterate over characters of a string using for loop.


# Create a string.
str = 'Google'

# Iterating over characters of a string.


for i in str:
print(i, end=' ')
print('\n')
str2 = 'Yahoo'
for i in str2:
print(i)

Output

Google
Y
a
h
o
o

Explained in Detail
In this example program, we have used end= ‘ ‘ in the print() function. By default, the print() statement ends with a newline character (\n). The function of end parameter is to change default behavior of print()
statement in Python.

The parameter end = ” ” in the print() function is to place a white space after each character of a string while iterating. Thus, the the print() function ends with white space, not a newline.

The for loop iterates over each character of a string and prints each letter on a separate line.

Example 2 :
Writing a Python program in which we will iterate over the index of characters of a string using for loop.

# Python program to iterate over index of a string using for loop.


# Create a string.
str = 'Google'
len_str = len(str) # finding the length of string.
# Iterating over the index of a string.
for i in range(0, len_str):
print(str[i], end=' ')

Output
Google

Example 3 :
Writing a program in Python to iterate through each character of a string using while loop.

# Python program to iterate over index of a string using while loop.


# Create a string.
institute = 'Python Programming'
len_str = len(institute) # finding the length of string.

# Iterating over index of a string.


index = 0
while index < len_str:
letter = institute[index]
print(letter, end=" ")
index = index + 1

Output
Python Programming

Example 4 :
Writing a program in Python to traverse over a string using enumerate() function.

# Python program to iterate over a string using enumerate() function.


# Create a string.
str = 'Instagram'
# Iterating over a string.
for i, v in enumerate(str):
print(v, end=" ")

Output
Instagram

Example 5 :

# Python program to traverse over a string using for loop.


# Create a string.
def main():
language = "Python"
index = 0
print(f"In the string '{language}'")
for each_ch in language:
print(f"Character '{each_ch}' has an index value of '{index}'")
index += 1
if __name__ == '__main__':
main()

Output
In the string 'Python'
Character 'P' has an index value of '0'
Character 'y' has an index value of '1'
Character 't' has an index value of '2'
Character 'h' has an index value of '3'
Character 'o' has an index value of '4'
Character 'n' has an index value of '5'

Explained in Detail
In this example, we have created a string “Python” and assigned it in a variable named language. We have initialized the index variable with a value zero. We have used a for loop that make it easy to loop or
iterate over each character of a string.

The index value is incremented by a value of one when each character traversed in the string. We have displayed each character of the string and its corresponding index value.

Iterating over Words in a String in Python

In Python, we can also traverse or iterate over each word of a string. A string can consists of several words separated by a white space. There are two methods to iterate over words of a string in Python.
They are:

Using split() function


Using re.findall() function

Example 1 :
Writing a program in Python to iterate over each word of a string using split() function.

# Python program to traverse over words of a string using split() function.


# Create a string.
def main():
str = "Python is an easy to use programming language."
index = 0
print(f"In the string '{str}'")
# Call split() function to extract words from string.
result = str.split()
print('\nWords of string are as:')
for each_word in result:
print(each_word)
index += 1
if __name__ == '__main__':
main()

Output

In the string 'Python is an easy to use programming language.'

Words of string are as:


Python
is
an
easy
to
use
programming
language.

Explained in Detail
In this example, we have used split() function to traverse over each word a string. This function splits the string into a list of words, but it fails if a string contains punctuation marks, such as question mark,
exclamation point, comma, colon, semicolon, etc. To overcome this issue, use re.findall() function.

Example 2 :
Writing a program to iterate over each word of a string using re.findall() function.

# Python program to traverse over words of a string using findall() function.


import re
def main():
str = "I love Python programming."
index = 0
print(f"In the string '{str}'")

# Call split() function to extract words from string.


result = re.findall(r'\w+',str)
print('\nWords of string are as:')
for each_word in result:
print(each_word)
index += 1
if __name__ == '__main__':
main()

Output
In the string 'I love Python programming.'
Words of string are as:
I
love
Python
programming

8 String Formatting in Python


String formatting is a way to present a string value to provide a better view on the console. It produces a more readable and interesting output on the console.
Sometimes, it is also called string interpolation because it interpolates string literal and converts values. There are several different ways to perform string formatting in Python. They are as:

Formatting with % Operator.


Formatting with format() string method.
Formatting with string literals, called f-strings

String Formatting with % Operator in Python


This is the oldest and easiest method of string formatting in Python. We can use a format operator (%) to perform string formatting operations. When we use the % sign with numbers in the print
statement, it works as a remainder operation.
With strings, it works as a string formatting operator. The general syntax to use string formatting operator is as:
<string> % <values>

Here is a table of all the symbols that we can use alongside % to format string.

Example 1 :
Use of %s operator

age = 22
print('My age is %s'%age)

Output
My age is 22

Explained in Detail
%s is used to convert any type of value into string format. Here, we have used %s to insert or put the value of variable age into a string. The %s is replaced by the argument value and print it.

Example 2 :

first_name = 'John'
last_name = 'Harry'
print('My name is %s %s'%(first_name, last_name))

Output
My name is John Harry

Explained in Detail
In this example, the (first_name, last_name) is a tuple and the complete expression is transformed into a string with the help of %s. The first %s is replaced by the value of “first_name” and the second %s is
replaced by the value of “last_name”. All the other characters in the string stay as they are.

Example 3 :
Usage of %i and %d

num1 = 20.456
num2 = 30.5768
print('First number is %i'%num1)
print('Second number is %d'%num2)

Output

First number is 20
Second number is 30

Explained in Detail
We can also perform string formatting with integer by using %i or %d instead of %s. In the above example, we have assigned the values of num1 and num2 in the form of decimal, but formatting string %i and %d
print only the integer part of the variable’s value.
Example 4 :
Usage of %f or %F

per1 = 80.4567
print('My first term percentage is %f' %per1)
per2 = 80.4546
print('My second term percentage is %.2F' %per2)

Output

My first term percentage is 80.456700


My second term percentage is 80.45

Example 5 :
Usage of %x and %o

num = 27
print(f"Hexadecimal representation of {num}: %x" %num)
print(f"Octal representation of {num}: %o" %num)

Output
Hexadecimal representation of 27: 1b
Octal representation of 27: 33

String Formatting using format() Method


String class also provides a method named format() to format string in Python. It is a newer and most popular method of formatting strings to produce more readable output on the console.
In this method, we use curly braces ({ }) as placeholders to enclose strings format objects. The general syntax to use format() function of string class is as:
In the above syntax, String is an object that has to be formatted. Parameters are values or objects to be formatted and starting from default position {0}.
String.format(parameters)

Example 1 :

my_name = input("Enter your name: ")


print("My name is {}".format(my_name))

Output

Enter your name: John


My name is John

Explained in Detail
In this example, we have taken the name of user as input by using input() function and stored in the variable my_name. Then, we have called the format() method on the string literal with passing the value of
my_name which are interpolated, in order, into the locations of replacement fields, indicated by empty curly braces, ({ }).

Example 2 :

name = "John"
age = 22
id = 23424
print("Name: {}, Age: {}, Id: {}".format(name, age, id))

Output
Name: John, Age: 22, Id: 23424

Example 3 :

name = "Bob"
age = 22
id = 35465
print("{} {} {}".format(name, age, id))

Output
Bob 22 35465

Example 4 :

n1 = "Mark"
n2 = "John"
n3 = "Harry"
# Default order.
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))

print("Students by positional order: ")


# Setting the order of positions. 0, 1, 2 are order parameters.
print("{1}, {0}, {2}".format(n1, n2, n3))

Output

Students by default order:


Mark, John, Harry
Students by positional order:
John, Mark, Harry

Example 5 :
n1 = "Mark"
n2 = "John"
n3 = "Harry"
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))

print("Students by keyword order: ")


print("{h}, {j}, {m}".format(h = n3, j = n2, m = n1))

Output

Students by default order:


Mark, John, Harry
Students by keyword order:
Harry, John, Mark

Formatting String Literals using f-strings

Python 3.6 has introduced a new string formatting mechanism called f-strings (short for formatted string literals). This mechanism is quite cool and is faster than using format() method and % formatting. It provides
a more convenient way to create formatted strings.

An f-string is a string literal, prefixed with ‘f’, which contains expressions inside the pair of curly braces ({ }). To create an f-string, first write the character f immediately preceding a string literal.

Within string literal, enclose expressions in the pair of curly braces to put the value of expressions into the formatted string. The general syntax to create formatted string literals in Python is as:
f"string_statements {variable_name [:{width}.{precision}]}"

Example 1 :

name = "Harry"
age = 22
sName = "RSVM"
print(f"{name}, {age}, {sName}")

Output
Harry, 22, RSVM

Example 2 :

name = "Harry"
age = 22
print(f"Hello! My name is {name} and I'm {age} years young.")

Output
Hello! My name is Harry and I'm 22 years young.

Example 3 :
Arithmetic operations using f-strings

n1 = 23
n2 = 45
n3 = 55
print(f"Sum of three numbers = {n1 + n2 + n3}")

Output
Sum of three numbers = 123

You might also like