0% found this document useful (0 votes)
17 views81 pages

Phyton 3 (1)

This document is a comprehensive tutorial on Python 3, covering its features, syntax, and various programming concepts. It is designed for software programmers looking to upgrade their skills or learn Python from scratch, with prerequisites including basic programming knowledge. The tutorial includes practical examples, execution options, and a detailed table of contents for easy navigation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views81 pages

Phyton 3 (1)

This document is a comprehensive tutorial on Python 3, covering its features, syntax, and various programming concepts. It is designed for software programmers looking to upgrade their skills or learn Python from scratch, with prerequisites including basic programming knowledge. The tutorial includes practical examples, execution options, and a detailed table of contents for easy navigation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Python 3

About the Tutorial


Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985 – 1990. Like
Perl, Python source code is also available under the GNU General Public License (GPL).
Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after
Python-the snake.

Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been backported to be
compatible with the version 2.7. This tutorial gives enough understanding on Python 3
version programming language. Please refer to this link for our Python 2 tutorial.

Audience
This tutorial is designed for software programmers who want to upgrade their Python skills
to Python 3. This tutorial can also be used to learn Python programming language from
scratch.

Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.

Execute Python Programs


For most of the examples given in this tutorial you will find Try it option, so just make use
of it and enjoy your learning.

Try the following example using Try it option available at the top right corner of the below
sample code box −

#!/usr/bin/python3

print ("Hello, Python!")

Copyright & Disclaimer


 Copyright 2016 by Tutorials Point (I) Pvt. Ltd.

All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.

We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com

i
Python 3

Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Execute Python Programs ................................................................................................................................ i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii

PYTHON 3 – BASIC TUTORIAL ...................................................................................................... 1

1. Python 3 – What is New? .......................................................................................................................... 2


The __future__ module ................................................................................................................................... 2
The print Function ........................................................................................................................................... 2
Reading Input from Keyboard ......................................................................................................................... 2
Integer Division ................................................................................................................................................ 3
Unicode Representation .................................................................................................................................. 3
xrange() Function Removed ............................................................................................................................ 4
raise exceprion ................................................................................................................................................ 4
Arguments in Exceptions ................................................................................................................................. 4
next() Function and .next() Method ................................................................................................................ 4
2to3 Utility ....................................................................................................................................................... 4

2. Python 3 – Overview ................................................................................................................................. 6


History of Python ............................................................................................................................................. 6
Python Features .............................................................................................................................................. 7

3. Python 3 – Environment Setup.................................................................................................................. 8


Local Environment Setup ................................................................................................................................. 8
Getting Python ................................................................................................................................................ 8
Setting up PATH ............................................................................................................................................... 9
Setting Path at Unix/Linux ............................................................................................................................. 10
Setting Path at Windows ............................................................................................................................... 10
Python Environment Variables ...................................................................................................................... 10
Running Python ............................................................................................................................................. 11

4. Python 3 – Basic Syntax .......................................................................................................................... 13


First Python Program ..................................................................................................................................... 13
Python Identifiers .......................................................................................................................................... 14
Reserved Words ............................................................................................................................................ 15
Lines and Indentation .................................................................................................................................... 15
Multi-Line Statements ................................................................................................................................... 17
Quotation in Python ...................................................................................................................................... 17
Comments in Python ..................................................................................................................................... 17
Using Blank Lines ........................................................................................................................................... 18
Waiting for the User ...................................................................................................................................... 18
Multiple Statements on a Single Line ............................................................................................................ 18
Multiple Statement Groups as Suites ............................................................................................................ 19
Command Line Arguments ............................................................................................................................ 19

ii
Python 3

Parsing Command-Line Arguments ............................................................................................................... 20

5. Python 3 – Variable Types ....................................................................................................................... 23


Assigning Values to Variables ........................................................................................................................ 23
Multiple Assignment ..................................................................................................................................... 23
Standard Data Types...................................................................................................................................... 24
Python Numbers ............................................................................................................................................ 24
Python Strings................................................................................................................................................ 25
Python Lists ................................................................................................................................................... 26
Python Tuples ................................................................................................................................................ 27
Python Dictionary .......................................................................................................................................... 27
Data Type Conversion .................................................................................................................................... 28

6. Python 3 – Basic Operators ..................................................................................................................... 30


Types of Operator .......................................................................................................................................... 30
Python Arithmetic Operators ........................................................................................................................ 30
Python Comparison Operators ...................................................................................................................... 32
Python Assignment Operators ...................................................................................................................... 33
Python Bitwise Operators.............................................................................................................................. 35
Python Logical Operators .............................................................................................................................. 37
Python Membership Operators ..................................................................................................................... 38
Python Identity Operators ............................................................................................................................. 39
Python Operators Precedence ...................................................................................................................... 40

7. Python 3 – Decision Making .................................................................................................................... 43


IF Statement .................................................................................................................................................. 44
IF...ELIF...ELSE Statements ............................................................................................................................. 45
Nested IF Statements .................................................................................................................................... 48
Single Statement Suites ................................................................................................................................. 49

8. Python 3 – Loops..................................................................................................................................... 51
while Loop Statements .................................................................................................................................. 52
for Loop Statements ...................................................................................................................................... 56
Nested loops .................................................................................................................................................. 59
Loop Control Statements ............................................................................................................................... 60
break statement ............................................................................................................................................ 61
continue Statement ....................................................................................................................................... 63
pass Statement .............................................................................................................................................. 65
Iterator and Generator .................................................................................................................................. 66

9. Python 3 – Numbers ............................................................................................................................... 68


Mathematical Functions ................................................................................................................................ 70
Number abs() Method ................................................................................................................................... 71
Number ceil() Method ................................................................................................................................... 71
Number exp() Method ................................................................................................................................... 72
Number fabs() Method .................................................................................................................................. 73
Number floor() Method ................................................................................................................................. 74
Number log() Method.................................................................................................................................... 75
Number log10() Method ............................................................................................................................... 76
Number max() Method .................................................................................................................................. 77
Number min() Method .................................................................................................................................. 78
Number modf() Method ................................................................................................................................ 79

iii
Python 3

Number pow() Method ................................................................................................................................. 80


Number round() Method ............................................................................................................................... 80
Number sqrt() Method .................................................................................................................................. 81
Random Number Functions ........................................................................................................................... 82
Number choice() Method .............................................................................................................................. 82
Number randrange() Method ........................................................................................................................ 83
Number random() Method ............................................................................................................................ 84
Number seed() Method ................................................................................................................................. 85
Number shuffle() Method ............................................................................................................................. 86
Number uniform() Method ........................................................................................................................... 87
Trigonometric Functions ............................................................................................................................... 88
Number acos() Method ................................................................................................................................. 88
Number asin() Method .................................................................................................................................. 89
Number atan() Method ................................................................................................................................. 90
Number atan2() Method ............................................................................................................................... 91
Number cos() Method ................................................................................................................................... 92
Number hypot() Method ............................................................................................................................... 93
Number sin() Method .................................................................................................................................... 94
Number tan() Method ................................................................................................................................... 95
Number degrees() Method ............................................................................................................................ 96
Number radians() Method ............................................................................................................................. 97
Mathematical Constants ............................................................................................................................... 98

10. Python 3 – Strings ................................................................................................................................... 99


Accessing Values in Strings ............................................................................................................................ 99
Updating Strings ............................................................................................................................................ 99
Escape Characters ....................................................................................................................................... 100
String Special Operators .............................................................................................................................. 101
String Formatting Operator ......................................................................................................................... 102
Triple Quotes ............................................................................................................................................... 104
Unicode String ............................................................................................................................................. 105
String capitalize() Method ........................................................................................................................... 109
String center() Method ................................................................................................................................ 110
String count() Method ................................................................................................................................. 111
String decode() Method .............................................................................................................................. 112
String encode() Method .............................................................................................................................. 112
String endswith() Method ........................................................................................................................... 113
String expandtabs() Method........................................................................................................................ 114
String find() Method .................................................................................................................................... 115
String index() Method ................................................................................................................................. 116
String isalnum() Method .............................................................................................................................. 117
String isalpha() Method ............................................................................................................................... 118
String isdigit() Method ................................................................................................................................. 118
String islower() Method ............................................................................................................................... 119
String isnumeric() Method .......................................................................................................................... 120
String isspace() Method ............................................................................................................................... 121
String istitle() Method ................................................................................................................................. 122
String isupper() Method .............................................................................................................................. 122
String join() Method .................................................................................................................................... 123
String len() Method ..................................................................................................................................... 124
String ljust() Method ................................................................................................................................... 125
String lower() Method ................................................................................................................................. 125

iv
Python 3

String lstrip() Method .................................................................................................................................. 126


String maketrans() Method ......................................................................................................................... 127
String max() Method ................................................................................................................................... 128
String min() Method .................................................................................................................................... 129
String replace() Method .............................................................................................................................. 129
String rfind() Method................................................................................................................................... 130
String rindex() Method ................................................................................................................................ 131
String rjust() Method ................................................................................................................................... 132
String rstrip() Method .................................................................................................................................. 133
String split() Method ................................................................................................................................... 134
String splitlines() Method ............................................................................................................................ 135
String startswith() Method .......................................................................................................................... 135
String strip() Method ................................................................................................................................... 136
String swapcase() Method ........................................................................................................................... 137
String title() Method .................................................................................................................................... 138
String translate() Method ............................................................................................................................ 138
String upper() Method ................................................................................................................................. 140
String zfill() Method ..................................................................................................................................... 140
String isdecimal() Method ........................................................................................................................... 141

11. Python 3 – Lists ..................................................................................................................................... 143


Python Lists ................................................................................................................................................. 143
Accessing Values in Lists .............................................................................................................................. 143
Updating Lists .............................................................................................................................................. 144
Delete List Elements .................................................................................................................................... 144
Basic List Operations ................................................................................................................................... 144
Indexing, Slicing and Matrixes ..................................................................................................................... 145
Built-in List Functions & Methods ............................................................................................................... 145
List len() Method ......................................................................................................................................... 146
List max() Method ....................................................................................................................................... 147
List min() Method ........................................................................................................................................ 147
List list() Method ......................................................................................................................................... 148
List append() Method .................................................................................................................................. 150
List count() Method ..................................................................................................................................... 151
List extend() Method ................................................................................................................................... 151
List index() Method ..................................................................................................................................... 152
List insert() Method ..................................................................................................................................... 153
List pop() Method ........................................................................................................................................ 154
List remove() Method .................................................................................................................................. 154
List reverse() Method .................................................................................................................................. 155
List sort() Method ........................................................................................................................................ 156

12. Python 3 – Tuples.................................................................................................................................. 157


Accessing Values in Tuples .......................................................................................................................... 157
Updating Tuples........................................................................................................................................... 158
Delete Tuple Elements ................................................................................................................................ 158
Basic Tuples Operations .............................................................................................................................. 159
Indexing, Slicing, and Matrixes .................................................................................................................... 159
No Enclosing Delimiters ............................................................................................................................... 160
Built-in Tuple Functions ............................................................................................................................... 160
Tuple len() Method ...................................................................................................................................... 160
Tuple max() Method .................................................................................................................................... 161

v
Python 3

Tuple min() Method .................................................................................................................................... 162


Tuple tuple() Method .................................................................................................................................. 162

13. Python 3 – Dictionary ............................................................................................................................ 164


Accessing Values in Dictionary .................................................................................................................... 164
Updating Dictionary..................................................................................................................................... 165
Delete Dictionary Elements ......................................................................................................................... 165
Properties of Dictionary Keys ...................................................................................................................... 166
Built-in Dictionary Functions & Methods .................................................................................................... 167
Dictionary len() Method .............................................................................................................................. 167
Dictionary str() Method ............................................................................................................................... 168
Dictionary type() Method ............................................................................................................................ 168
Dictionary clear() Method ........................................................................................................................... 170
Dictionary copy() Method ........................................................................................................................... 171
Dictionary fromkeys() Method .................................................................................................................... 172
Dictionary get() Method .............................................................................................................................. 172
Dictionary items() Method .......................................................................................................................... 173
Dictionary keys() Method ............................................................................................................................ 174
Dictionary setdefault() Method ................................................................................................................... 174
Dictionary update() Method ........................................................................................................................ 175
Dictionary values() Method ......................................................................................................................... 176

14. Python 3 – Date & Time ........................................................................................................................ 178


What is Tick?................................................................................................................................................ 178
What is TimeTuple? ..................................................................................................................................... 178
Getting current time .................................................................................................................................... 180
Getting formatted time ............................................................................................................................... 180
Getting calendar for a month ...................................................................................................................... 180
The time Module ......................................................................................................................................... 181
Time altzone() Method ................................................................................................................................ 182
Time asctime() Method ............................................................................................................................... 183
Time clock() Method ................................................................................................................................... 184
Time ctime() Method ................................................................................................................................... 185
Time gmtime() Method ............................................................................................................................... 186
Time localtime() Method ............................................................................................................................. 187
Time mktime() Method ............................................................................................................................... 187
Time sleep() Method ................................................................................................................................... 188
Time strftime() Method ............................................................................................................................... 189
Time strptime() Method .............................................................................................................................. 191
Time time() Method .................................................................................................................................... 193
Time tzset() Method .................................................................................................................................... 194
The calendar Module .................................................................................................................................. 196
Other Modules & Functions ........................................................................................................................ 198

15. Python 3 – Functions............................................................................................................................. 199


Defining a Function...................................................................................................................................... 199
Calling a Function ........................................................................................................................................ 200
Pass by Reference vs Value ......................................................................................................................... 200
Function Arguments .................................................................................................................................... 202
Required Arguments.................................................................................................................................... 202
Keyword Arguments .................................................................................................................................... 202
Default Arguments ...................................................................................................................................... 203

vi
Python 3

Variable-length Arguments ......................................................................................................................... 204


The Anonymous Functions .......................................................................................................................... 205
The return Statement .................................................................................................................................. 206
Global vs. Local variables ............................................................................................................................. 206

16. Python 3 – Modules .............................................................................................................................. 208


The import Statement ................................................................................................................................. 208
The from...import Statement ...................................................................................................................... 209
The from...import * Statement: .................................................................................................................. 209
Executing Modules as Scripts ...................................................................................................................... 209
Locating Modules ........................................................................................................................................ 210
The PYTHONPATH Variable ......................................................................................................................... 210
Namespaces and Scoping ............................................................................................................................ 211
The dir( ) Function ....................................................................................................................................... 212
The globals() and locals() Functions............................................................................................................ 212
The reload() Function .................................................................................................................................. 212
Packages in Python ...................................................................................................................................... 213

17. Python 3 – Files I/O ............................................................................................................................... 215


Printing to the Screen .................................................................................................................................. 215
Reading Keyboard Input .............................................................................................................................. 215
The input Function ...................................................................................................................................... 215
Opening and Closing Files ............................................................................................................................ 216
The open Function ...................................................................................................................................... 216
The file Object Attributes ............................................................................................................................ 217
The close() Method ..................................................................................................................................... 218
Reading and Writing Files ............................................................................................................................ 219
The write() Method ..................................................................................................................................... 219
The read() Method ...................................................................................................................................... 220
File Positions ................................................................................................................................................ 220
Renaming and Deleting Files ....................................................................................................................... 221
The rename() Method ................................................................................................................................. 221
The remove() Method ................................................................................................................................. 222
Directories in Python ................................................................................................................................... 222
The mkdir() Method .................................................................................................................................... 222
The chdir() Method ..................................................................................................................................... 223
The getcwd() Method ................................................................................................................................. 223
The rmdir() Method .................................................................................................................................... 224
File & Directory Related Methods ............................................................................................................... 224
File Methods ................................................................................................................................................ 224
File close() Method ...................................................................................................................................... 226
File flush() Method ...................................................................................................................................... 227
File fileno() Method ..................................................................................................................................... 228
File isatty() Method ..................................................................................................................................... 228
File next() Method ....................................................................................................................................... 229
File read() Method ....................................................................................................................................... 231
File readline() Method ................................................................................................................................. 232
File readlines() Method ............................................................................................................................... 233
File seek() Method ....................................................................................................................................... 234
File tell() Method ......................................................................................................................................... 236
File truncate() Method ................................................................................................................................ 237

vii
Python 3

File write() Method ...................................................................................................................................... 238


File writelines() Method .............................................................................................................................. 240
OS File/Directory Methods .......................................................................................................................... 241
os.access() Method...................................................................................................................................... 248
os.chdir() Method ........................................................................................................................................ 250
os.chflags() Method ..................................................................................................................................... 251
os.chmod() Method ..................................................................................................................................... 252
os.chown() Method ..................................................................................................................................... 254
os.chroot() Method ..................................................................................................................................... 255
Python os.close() Method ........................................................................................................................... 255
os.closerange() Method .............................................................................................................................. 256
os.dup() Method .......................................................................................................................................... 258
os.dup2() Method ........................................................................................................................................ 259
os.fchdir() Method....................................................................................................................................... 260
os.fchmod() Method .................................................................................................................................... 261
os.fchown() Method .................................................................................................................................... 263
os.fdatasync() Method ................................................................................................................................ 264
os.fdopen() Method .................................................................................................................................... 266
os.fpathconf() Method ................................................................................................................................ 267
os.fstat() Method ......................................................................................................................................... 269
os.fstatvfs() Method .................................................................................................................................... 270
os.fsync() Method ........................................................................................................................................ 272
os.ftruncate() Method ................................................................................................................................. 273
os.getcwd() Method .................................................................................................................................... 274
os.getcwdu() Method .................................................................................................................................. 275
os.isatty() Method ....................................................................................................................................... 276
os.lchflags() Method .................................................................................................................................... 278
os.lchown() Method .................................................................................................................................... 279
os.link() Method .......................................................................................................................................... 280
os.listdir() Method ....................................................................................................................................... 281
os.lseek() Method ........................................................................................................................................ 282
os.lstat() Method ......................................................................................................................................... 284
os.major() Method ...................................................................................................................................... 286
os.makedev() Method ................................................................................................................................. 286
os.makedirs() Method ................................................................................................................................. 288
os.minor() Method ...................................................................................................................................... 288
os.mkdir() Method....................................................................................................................................... 289
os.mkfifo() Method ..................................................................................................................................... 290
os.mknod() Method ..................................................................................................................................... 291
os.open() Method ........................................................................................................................................ 292
os.openpty() Method .................................................................................................................................. 293
os.pathconf() Method ................................................................................................................................. 294
os.pipe() Method ......................................................................................................................................... 296
os.popen() Method ...................................................................................................................................... 297
os.read() Method......................................................................................................................................... 298
os.readlink() Method ................................................................................................................................... 299
os.remove() Method.................................................................................................................................... 300
os.removedirs() Method .............................................................................................................................. 301
os.rename() Method ................................................................................................................................... 302
os.renames() Method .................................................................................................................................. 303
os.renames() Method .................................................................................................................................. 304
os.rmdir() Method ....................................................................................................................................... 305

viii
Python 3

os.stat() Method .......................................................................................................................................... 307


os.stat_float_times() Method ..................................................................................................................... 308
os.statvfs() Method ..................................................................................................................................... 309
os.symlink() Method .................................................................................................................................... 310
os.tcgetpgrp() Method ................................................................................................................................ 311
os.tcsetpgrp() Method ................................................................................................................................. 312
os.tempnam() Method ................................................................................................................................ 313
os.tmpfile() Method .................................................................................................................................... 314
os.tmpnam() Method .................................................................................................................................. 315
os.ttyname() Method .................................................................................................................................. 315
os.unlink() Method ...................................................................................................................................... 317
os.utime() Method ...................................................................................................................................... 318
os.walk() Method ........................................................................................................................................ 319
os.write() Method ....................................................................................................................................... 321

18. Python 3 – Exceptions Handling ........................................................................................................... 323


Standard Exceptions .................................................................................................................................... 323
Assertions in Python .................................................................................................................................... 325
What is Exception? ...................................................................................................................................... 326
Handling an Exception ................................................................................................................................. 326
The except Clause with No Exceptions ....................................................................................................... 328
The except Clause with Multiple Exceptions .............................................................................................. 328
The try-finally Clause ................................................................................................................................... 329
Argument of an Exception ........................................................................................................................... 330
Raising an Exception .................................................................................................................................... 331
User-Defined Exceptions ............................................................................................................................. 332

PYTHON 3 – ADVANCED TUTORIAL ......................................................................................... 333

19. Python 3 – Object Oriented................................................................................................................... 334


Overview of OOP Terminology .................................................................................................................... 334
Creating Classes ........................................................................................................................................... 335
Creating Instance Objects ............................................................................................................................ 336
Accessing Attributes .................................................................................................................................... 336
Built-In Class Attributes ............................................................................................................................... 337
Destroying Objects (Garbage Collection) .................................................................................................... 339
Class Inheritance ......................................................................................................................................... 340
Overriding Methods .................................................................................................................................... 342
Base Overloading Methods ......................................................................................................................... 342
Overloading Operators ................................................................................................................................ 343
Data Hiding .................................................................................................................................................. 344

20. Python 3 – Regular Expressions............................................................................................................. 346


The match Function .................................................................................................................................... 347
The search Function ................................................................................................................................... 348
Matching Versus Searching ......................................................................................................................... 349
Search and Replace ..................................................................................................................................... 350
Regular Expression Modifiers: Option Flags ................................................................................................ 350
Regular Expression Patterns ........................................................................................................................ 351
Regular Expression Examples ...................................................................................................................... 353
Character classes ......................................................................................................................................... 354

ix
Python 3

Special Character Classes ............................................................................................................................ 354


Repetition Cases .......................................................................................................................................... 355
Nongreedy Repetition ................................................................................................................................. 355
Grouping with Parentheses ......................................................................................................................... 355
Backreferences ............................................................................................................................................ 356
Alternatives ................................................................................................................................................. 356
Anchors ........................................................................................................................................................ 356
Special Syntax with Parentheses ................................................................................................................. 357

21. Python 3 – CGI Programming ................................................................................................................ 358


What is CGI? ................................................................................................................................................ 358
Web Browsing ............................................................................................................................................. 358
CGI Architecture Diagram ............................................................................................................................ 359
Web Server Support and Configuration ...................................................................................................... 359
First CGI Program......................................................................................................................................... 360
HTTP Header ................................................................................................................................................ 361
CGI Environment Variables .......................................................................................................................... 361
GET and POST Methods ............................................................................................................................... 363
Passing Information using GET method ...................................................................................................... 363
Simple URL Example – Get Method ............................................................................................................. 363
Simple FORM Example – GET Method ........................................................................................................ 364
Passing Radio Button Data to CGI Program ................................................................................................. 367
Passing Text Area Data to CGI Program....................................................................................................... 368
Passing Drop Down Box Data to CGI Program ............................................................................................. 369
Using Cookies in CGI .................................................................................................................................... 370
How It Works? ............................................................................................................................................. 370
Setting up Cookies ....................................................................................................................................... 371
Retrieving Cookies ....................................................................................................................................... 371
File Upload Example .................................................................................................................................... 372
How To Raise a "File Download" Dialog Box ? ............................................................................................. 374

22. Python 3 – MySQL Database Access ...................................................................................................... 375


What is PyMySQL ? ...................................................................................................................................... 375
How do I Install PyMySQL? .......................................................................................................................... 376
Database Connection .................................................................................................................................. 376
Creating Database Table.............................................................................................................................. 377
INSERT Operation ........................................................................................................................................ 378
READ Operation ........................................................................................................................................... 380
Update Operation ........................................................................................................................................ 382
DELETE Operation ........................................................................................................................................ 383
Performing Transactions ............................................................................................................................. 383
COMMIT Operation ..................................................................................................................................... 384
ROLLBACK Operation ................................................................................................................................... 384
Disconnecting Database .............................................................................................................................. 384
Handling Errors ............................................................................................................................................ 385

23. Python 3 – Network Programming ....................................................................................................... 387


What is Sockets? .......................................................................................................................................... 387
The socket Module ...................................................................................................................................... 388
Server Socket Methods ............................................................................................................................... 388
Client Socket Methods ................................................................................................................................ 388
General Socket Methods ............................................................................................................................. 389

x
Python 3

A Simple Server............................................................................................................................................ 389


A Simple Client............................................................................................................................................. 390
Python Internet Modules ............................................................................................................................ 391
Further Readings ......................................................................................................................................... 392

24. Python 3 – Sending Email using SMTP .................................................................................................. 393


Sending an HTML e-mail using Python ........................................................................................................ 394
Sending Attachments as an E-mail .............................................................................................................. 395

25. Python 3 – Multithreaded Programming .............................................................................................. 398


Starting a New Thread ................................................................................................................................. 398
The Threading Module ................................................................................................................................ 400
Creating Thread Using Threading Module .................................................................................................. 400
Synchronizing Threads ................................................................................................................................. 402
Multithreaded Priority Queue ..................................................................................................................... 404

26. Python 3 – XML Processing ................................................................................................................... 407


What is XML? ............................................................................................................................................... 407
XML Parser Architectures and APIs ............................................................................................................. 407
Parsing XML with SAX APIs .......................................................................................................................... 408
The make_parser Method............................................................................................................................ 409
The parse Method ........................................................................................................................................ 409
The parseString Method .............................................................................................................................. 409
Parsing XML with DOM APIs ........................................................................................................................ 412

27. Python 3 – GUI Programming (Tkinter) ................................................................................................. 415


Tkinter Programming ................................................................................................................................... 415
Tkinter Widgets ........................................................................................................................................... 416
Tkinter Button ............................................................................................................................................. 418
Tkinter Canvas ............................................................................................................................................. 420
Tkinter Checkbutton .................................................................................................................................... 423
Tkinter Entry ................................................................................................................................................ 427
Tkinter Frame .............................................................................................................................................. 431
Tkinter Label ................................................................................................................................................ 433
Tkinter Listbox ............................................................................................................................................. 435
Tkinter Menubutton .................................................................................................................................... 439
Tkinter Menu ............................................................................................................................................... 442
Tkinter Message .......................................................................................................................................... 446
Tkinter Radiobutton .................................................................................................................................... 449
Tkinter Scale ................................................................................................................................................ 453
Tkinter Scrollbar .......................................................................................................................................... 457
Tkinter Text.................................................................................................................................................. 460
Tkinter Toplevel ........................................................................................................................................... 464
Tkinter Spinbox ............................................................................................................................................ 467
Tkinter PanedWindow ................................................................................................................................. 471
Tkinter LabelFrame ...................................................................................................................................... 473
Tkinter tkMessageBox ................................................................................................................................. 475
Standard Attributes ..................................................................................................................................... 477
Tkinter Dimensions ...................................................................................................................................... 477
Tkinter Colors .............................................................................................................................................. 478
Tkinter Fonts ................................................................................................................................................ 479
Tkinter Anchors ........................................................................................................................................... 480

xi
Python 3

Tkinter Relief styles ..................................................................................................................................... 481


Tkinter Bitmaps ........................................................................................................................................... 482
Tkinter Cursors ............................................................................................................................................ 484
Geometry Management .............................................................................................................................. 485
Tkinter pack() Method ................................................................................................................................. 486
Tkinter grid() Method .................................................................................................................................. 487
Tkinter place() Method ................................................................................................................................ 488

28. Python 3 – Extension Programming with C ........................................................................................... 490


Pre-Requisites for Writing Extensions ......................................................................................................... 490
First look at a Python Extension .................................................................................................................. 490
The Header File Python.h ............................................................................................................................ 490
The C Functions ........................................................................................................................................... 491
The Method Mapping Table ........................................................................................................................ 491
The Initialization Function ........................................................................................................................... 492
Building and Installing Extensions ............................................................................................................... 494
Importing Extensions ................................................................................................................................... 494
Passing Function Parameters ...................................................................................................................... 495
The PyArg_ParseTuple Function .................................................................................................................. 496
Returning Values ......................................................................................................................................... 497
The Py_BuildValue Function ........................................................................................................................ 498

xii
Python 3

Python 3 – Basic Tutorial

1
1. Python 3 – What is New? Python 3

The __future__ module


Python 3.x introduced some Python 2-incompatible keywords and features that can be
imported via the in-built __future__ module in Python 2. It is recommended to use
__future__ imports, if you are planning Python 3.x support for your code.

For example, if we want Python 3.x's integer division behavior in Python 2, add the
following import statement.

from __future__ import division

The print Function


Most notable and most widely known change in Python 3 is how the print function is used.
Use of parenthesis () with print function is now mandatory. It was optional in Python 2.

print "Hello World" #is acceptable in Python 2


print ("Hello World") # in Python 3, print must be followed by ()

The print() function inserts a new line at the end, by default. In Python 2, it can be
suppressed by putting ',' at the end. In Python 3, "end=' '" appends space instead of
newline.

print x, # Trailing comma suppresses newline in Python 2


print(x, end=" ") # Appends a space instead of a newline in Python 3

Reading Input from Keyboard


Python 2 has two versions of input functions, input() and raw_input(). The input()
function treats the received data as string if it is included in quotes '' or "", otherwise the
data is treated as number.

In Python 3, raw_input() function is deprecated. Further, the received data is always


treated as string.

In Python 2
>>> x=input('something:')
something:10 #entered data is treated as number
>>> x
10

>>> x=input('something:')
something:'10' #eentered data is treated as string
2
Python 3

>>> x
'10'
>>> x=raw_input("something:")
something:10 #entered data is treated as string even without ''
>>> x
'10'
>>> x=raw_input("something:")
something:'10' #entered data treated as string including ''
>>> x
"'10'"
In Python 3
>>> x=input("something:")
something:10
>>> x
'10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
>>> x=raw_input("something:") # will result NameError
Traceback (most recent call last):
File "", line 1, in

x=raw_input("something:")
NameError: name 'raw_input' is not defined

Integer Division
In Python 2, the result of division of two integers is rounded to the nearest integer. As a
result, 3/2 will show 1. In order to obtain a floating-point division, numerator or
denominator must be explicitly used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will
result in 1.5

Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.

Unicode Representation
Python 2 requires you to mark a string with a u if you want to store it as Unicode.

Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2
byte classes: byte and byte arrays.

3
Python 3

xrange() Function Removed


In Python 2 range() returns a list, and xrange() returns an object that will only generate
the items in the range when needed, saving memory.

In Python 3, the range() function is removed, and xrange() has been renamed as range().
In addition, the range() object supports slicing in Python 3.2 and later .

raise exceprion
Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a
SyntaxError if we do not enclose the exception argument in parenthesis.

raise IOError, "file error" #This is accepted in Python 2


raise IOError("file error") #This is also accepted in Python 2
raise IOError, "file error" #syntax error is raised in Python 3
raise IOError("file error") #this is the recommended syntax in Python 3

Arguments in Exceptions
In Python 3, arguments to exception should be declared with 'as' keyword.

except Myerror, err: # In Python2


except Myerror as err: #In Python 3

next() Function and .next() Method


In Python 2, next() as a method of generator object, is allowed. In Python 2, the next()
function, to iterate over generator object, is also accepted. In Python 3, however, next(0
as a generator method is discontinued and raises AttributeError.

gen = (letter for letter in 'Hello World') # creates generator object


next(my_generator) #allowed in Python 2 and Python 3
my_generator.next() #allowed in Python 2. raises AttributeError in Python 3

2to3 Utility
Along with Python 3 interpreter, 2to3.py script is usually installed in tools/scripts folder.
It reads Python 2.x source code and applies a series of fixers to transform it into a valid
Python 3.x code.

Here is a sample Python 2 code (area.py):


def area(x,y=3.14):
a=y*x*x
print a
return a
4
Python 3

a=area(10)
print "area",a
To convert into Python 3 version:
$2to3 -w area.py
Converted code :
def area(x,y=3.14): # formal parameters
a=y*x*x
print (a)
return a
a=area(10)
print("area",a)

5
2. Python 3 – Overview Python 3

Python is a high-level, interpreted, interactive and object-oriented scripting language.


Python is designed to be highly readable. It uses English keywords frequently whereas the
other languages use punctuations. It has fewer syntactical constructions than other
languages.

 Python is Interpreted: Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL and
PHP.

 Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.

 Python is Object-Oriented: Python supports Object-Oriented style or technique


of programming that encapsulates code within objects.

 Python is a Beginner's Language: Python is a great language for the beginner-


level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.

 Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.

 Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).

 Python is now maintained by a core development team at the institute, although


Guido van Rossum still holds a vital role in directing its progress.

 Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.

 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.

6
Python 3

Python Features
Python's features include-

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a student to pick up the language quickly.

 Easy-to-read: Python code is more clearly defined and visible to the eyes.

 Easy-to-maintain: Python's source code is fairly easy-to-maintain.

 A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.

 Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.

 Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

 Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

 Databases: Python provides interfaces to all major commercial databases.

 GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.

 Scalable: Python provides a better structure and support for large programs than
shell scripting.

Apart from the above-mentioned features, Python has a big list of good features. A few
are listed below-

 It supports functional and structured programming methods as well as OOP.

 It can be used as a scripting language or can be compiled to byte-code for building


large applications.

 It provides very high-level dynamic data types and supports dynamic type
checking.

 It supports automatic garbage collection.

 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

7
3. Python 3 – Environment Setup Python 3

Try it Option Online


We have set up the Python Programming environment online, so that you can compile and
execute all the available examples online. It will give you the confidence in what you are
reading and will enable you to verify the programs with different options. Feel free to
modify any example and execute it online.

Try the following example using our online compiler available at CodingGround

#!/usr/bin/python3
print ("Hello, Python!")

For most of the examples given in this tutorial, you will find a Try it option on our website
code sections, at the top right corner that will take you to the online compiler. Just use it
and enjoy your learning.

Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating
system. Even though Python 2 is available for many other OSs, Python 3 support either
has not been made available for them or has been dropped.

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed and which
version is installed.

Getting Python

Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page

The following different installation options are available.

 Windows x86-64 embeddable zip file


 Windows x86-64 executable installer
 Windows x86-64 web-based installer
 Windows x86 embeddable zip file
 Windows x86 executable installer
 Windows x86 web-based installer

Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1.
For versions 3.0 to 3.4.x, Windows XP is acceptable.

8
Python 3

Linux platform
Different flavors of Linux use different package managers for installation of new packages.

On Ubuntu Linux, Python 3 is installed using the following command from the terminal.

$sudo apt-get install python3-minimal

Installation from source

Download Gzipped source tarball from Python's download URL:


https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Extract the tarball
tar xvfz Python-3.5.1.tgz
Configure and Install:
cd Python-3.5.1
./configure --prefix=/opt/python3.5.1
make
sudo make install

Mac OS
Download Mac OS installers from this URL:https://www.python.org/downloads/mac-osx/

 Mac OS X 64-bit/32-bit installer : python-3.5.1-macosx10.6.pkg

 Mac OS X 32-bit i386/PPC installer : python-3.5.1-macosx10.5.pkg

Double click this package file and follow the wizard instructions to install.

The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python:

Python Official Website : http://www.python.org/

You can download Python documentation from the following site. The documentation is
available in HTML, PDF and PostScript formats.

Python Documentation Website : www.python.org/doc/

Setting up PATH
Programs and other executable files can be in many directories. Hence, the operating
systems provide a search path that lists the directories that it searches for executables.

The important features are-

 The path is stored in an environment variable, which is a named string maintained


by the operating system. This variable contains information available to the
command shell and other programs.

9
Python 3

 The path variable is named as PATH in Unix or Path in Windows (Unix is case-
sensitive; Windows is not).

 In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.

Setting Path at Unix/Linux


To add the Python directory to the path for a particular session in Unix-

 In the csh shell: type setenv PATH "$PATH:/usr/local/bin/python3" and press


Enter.

 In the bash shell (Linux): type export PATH="$PATH:/usr/local/bin/python3"


and press Enter.

 In the sh or ksh shell: type PATH="$PATH:/usr/local/bin/python3" and press


Enter.

Note: /usr/local/bin/python3 is the path of the Python directory.

Setting Path at Windows


To add the Python directory to the path for a particular session in Windows-

At the command prompt : type


path %path%;C:\Python and press Enter.

Note: C:\Python is the path of the Python directory.

Python Environment Variables


Here are important environment variables, which are recognized by Python-

Variable Description

It has a role similar to PATH. This variable tells the Python


interpreter where to locate the module files imported into a
PYTHONPATH program. It should include the Python source library directory and
the directories containing Python source code. PYTHONPATH is
sometimes, preset by the Python installer.

It contains the path of an initialization file containing Python


source code. It is executed every time you start the interpreter. It
PYTHONSTARTUP
is named as .pythonrc.py in Unix and it contains commands that
load utilities or modify PYTHONPATH.

10
Python 3

It is used in Windows to instruct Python to find the first case-


PYTHONCASEOK insensitive match in an import statement. Set this variable to any
value to activate it.

It is an alternative module search path. It is usually embedded in


PYTHONHOME the PYTHONSTARTUP or PYTHONPATH directories to make
switching module libraries easy.

Running Python
There are three different ways to start Python-

(1) Interactive Interpreter


You can start Python from Unix, DOS, or any other system that provides you a command-
line interpreter or shell window.

Enter python the command line.

Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS

Here is the list of all the available command line options-

Option Description

-d provide debug output

-O generate optimized bytecode (resulting in .pyo files)

-S do not run import site to look for Python paths on startup

-v verbose output (detailed trace on import statements)

disable class-based built-in exceptions (just use strings); obsolete starting


-X
with version 1.6

-c cmd run Python script sent in as cmd string

11
Python 3

file run Python script from given file

(2) Script from the Command-line


A Python script can be executed at the command line by invoking the interpreter on your
application, as shown in the following example.

$python script.py # Unix/Linux


or
python% script.py # Unix/Linux
or
C:>python script.py # Windows/DOS

Note: Be sure the file permission mode allows execution.

(3) Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have
a GUI application on your system that supports Python.

 Unix: IDLE is the very first Unix IDE for Python.

 Windows: PythonWin is the first Windows interface for Python and is an IDE with
a GUI.

 Macintosh: The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.

If you are not able to set up the environment properly, then you can take the help of your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.

Note: All the examples given in subsequent chapters are executed with Python 3.4.1
version available on Windows 7 and Ubuntu Linux.

We have already set up Python Programming environment online, so that you can execute
all the available examples online while you are learning theory. Feel free to modify any
example and execute it online.

12
4. Python 3 – Basic Syntax Python 3

The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages.

First Python Program


Let us execute the programs in different modes of programming.

Interactive Mode Programming


Invoking the interpreter without passing a script file as a parameter brings up the following
prompt-

$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
>>>

Type the following text at the Python prompt and press Enter-

>>> print ("Hello, Python!")

If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result-

Hello, Python!

Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no longer
active.

Let us write a simple Python program in a script. Python files have the extension.py. Type
the following source code in a test.py file-

print ("Hello, Python!")

13
Python 3

We assume that you have the Python interpreter set in PATH variable. Now, try to run
this program as follows-

On Linux

$ python test.py

This produces the following result-

Hello, Python!

On Windows

C:\Python34>Python test.py

This produces the following result-

Hello, Python!

Let us try another way to execute a Python script in Linux. Here is the modified test.py
file-

#!/usr/bin/python3
print ("Hello, Python!")

We assume that you have Python interpreter available in the /usr/bin directory. Now, try
to run this program as follows-

$ chmod +x test.py # This is to make file executable


$./test.py

This produces the following result-

Hello, Python!

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.

Here are naming conventions for Python identifiers-

 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.

 Starting an identifier with a single leading underscore indicates that the identifier
is private.
14
Python 3

 Starting an identifier with two leading underscores indicates a strong private


identifier.

 If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.

Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot
use them as constants or variables or any other identifier names. All the Python keywords
contain lowercase letters only.

and exec Not

as finally or

assert for pass

break from print

class global raise

continue if return

def import try

del in while

elif is with

else lambda yield

except

Lines and Indentation


Python does not use braces({}) to indicate blocks of code for class and function definitions
or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example-

15
Python 3

if True:
print ("True")
else:
print ("False")

However, the following block generates an error-

if True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")

Thus, in Python all the continuous lines indented with the same number of spaces would
form a block. The following example has various statement blocks-

Note: Do not try to understand the logic at this point of time. Just make sure you
understood the various blocks even if they are without braces.

#!/usr/bin/python3
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print ("There was an error writing to", file_name)
sys.exit()
print ("Enter '", file_finish,)
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = input("Enter filename: ")
if len(file_name) == 0:
print ("Next time please enter something")

16
Python 3

sys.exit()
try:
file = open(file_name, "r")
except IOError:
print ("There was an error reading file")
sys.exit()
file_text = file.read()
file.close()
print (file_text)

Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use of
the line continuation character (\) to denote that the line should continue. For example-

total = item_one + \
item_two + \
item_three

The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example-

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the
following are legal-

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and the
Python interpreter ignores them.

#!/usr/bin/python3
17
Python 3

# First comment
print ("Hello, Python!") # second comment

This produces the following result-

Hello, Python!

You can type a comment on the same line after a statement or expression-

name = "Madisetti" # This is again comment

Python does not have multiple-line commenting feature. You have to comment each line
individually as follows-

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Using Blank Lines


A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to terminate
a multiline statement.

Waiting for the User


The following line of the program displays the prompt and the statement saying “Press the
enter key to exit”, and then waits for the user to take action −

#!/usr/bin/python3
input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the
user presses the key, the program ends. This is a nice trick to keep a console window open
until the user is done with an application.

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on a single line given that no statement
starts a new code block. Here is a sample snip using the semicolon-

import sys; x = 'foo'; sys.stdout.write(x + '\n')

18
Python 3

Multiple Statement Groups as Suites


Groups of individual statements, which make a single code block are called suites in
Python. Compound or complex statements, such as if, while, def, and class require a
header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite. For example −

if expression :
suite
elif expression :
suite
else :
suite

Command Line Arguments


Many programs can be run to provide you with some basic information about how they
should be run. Python enables you to do this with -h:

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]

You can also program your script in such a way that it should accept various
options. Command Line Arguments is an advance topic. Let us understand it.

Command Line Arguments


Python provides a getopt module that helps you parse command-line options and
arguments.

$ python test.py arg1 arg2 arg3

The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes-

 sys.argv is the list of command-line arguments.

 len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program i.e. the script name.

19
Python 3

Example
Consider the following script test.py-

#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

Now run the above script as follows −

$ python test.py arg1 arg2 arg3

This produces the following result-

Number of arguments: 4 arguments.


Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

NOTE: As mentioned above, the first argument is always the script name and it is also
being counted in number of arguments.

Parsing Command-Line Arguments


Python provided a getopt module that helps you parse command-line options and
arguments. This module provides two functions and an exception to enable command line
argument parsing.

getopt.getopt method
This method parses the command line options and parameter list. Following is a simple
syntax for this method-

getopt.getopt(args, options, [long_options])

Here is the detail of the parameters-

 args: This is the argument list to be parsed.

 options: This is the string of option letters that the script wants to recognize, with
options that require an argument should be followed by a colon (:).

 long_options: This is an optional parameter and if specified, must be a list of


strings with the names of the long options, which should be supported. Long
options, which require an argument should be followed by an equal sign ('='). To
accept only long options, options should be an empty string.

 This method returns a value consisting of two elements- the first is a list
of (option, value) pairs, the second is a list of program arguments left after the
option list was stripped.

20
Python 3

 Each option-and-value pair returned has the option as its first element, prefixed
with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '-
-long-option').

Exception getopt.GetoptError
This is raised when an unrecognized option is found in the argument list or when an option
requiring an argument is given none.

The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option.

Example
Suppose we want to pass two file names through command line and we also want to give
an option to check the usage of the script. Usage of the script is as follows-

usage: test.py -i <inputfile> -o <outputfile>

Here is the following script to test.py-

#!/usr/bin/python3
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])

21
Python 3

Now, run the above script as follows-

$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile -o outputfile
Input file is " inputfile
Output file is " outputfile

22
5. Python 3 – Variable Types Python 3

Variables are nothing but reserved memory locations to store values. It means that when
you create a variable, you reserve some space in the memory.

Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to the
variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used
to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example-

#!/usr/bin/python3
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name variables, respectively. This produces the following result −

100
1000.0
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.

For example-

a = b = c = 1

Here, an integer object is created with the value 1, and all the three variables are assigned
to the same memory location. You can also assign multiple objects to multiple variables.

23
Python 3

For example-

a, b, c = 1, 2, "john"

Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them
and the storage method for each of them.

Python has five standard data types-

 Numbers
 String
 List
 Tuple
 Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example-

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.

For example-

del var
del var_a, var_b

Python supports three different numerical types −

 int (signed integers)


 float (floating point real values)
 complex (complex numbers)

24
Python 3

All integers in Python 3 are represented as long integers. Hence, there is no separate
number type as long.

Examples
Here are some examples of numbers-

int float complex

10 0.0 3.14j

100 15.20 45.j

-786 -21.9 9.322e-36j

080 32.3+e18 .876j

-0490 -90. -.6545+0J

-0x260 -32.54e100 3e+26J

0x69 70.2-E12 4.53e-7j

A complex number consists of an ordered pair of real floating-point numbers denoted by


x + yj, where x and y are real numbers and j is the imaginary unit.

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of strings
can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example-

#!/usr/bin/python3
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

25
Python 3

This will produce the following result-

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging
to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example-

#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

This produces the following result-

['abcd', 786, 2.23, 'john', 70.200000000000003]


abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

26
Python 3

Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parenthesis.

The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists. For example-

#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

This produces the following result-

('abcd', 786, 2.23, 'john', 70.200000000000003)


abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −

#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.

27
Python 3

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example-

#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

This produces the following result-

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type-name as a function.

There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Function Description

int(x [,base]) Converts x to an integer. The base specifies the base if x is a


string.

float(x) Converts x to a floating-point number.

complex(real Creates a complex number.


[,imag])

28
Python 3

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

set(s) Converts s to a set.

dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s) Converts s to a frozen set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

29
6. Python 3 – Basic Operators Python 3

Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called the operator.

Types of Operator
Python language supports the following types of operators-

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us have a look at all the operators one by one.

Python Arithmetic Operators


Assume variable a holds the value 10 and variable b holds the value 21, then-

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 31

- Subtraction Subtracts right hand operand from left hand a – b = -11


operand.

* Multiplication Multiplies values on either side of the operator a * b = 210

/ Division Divides left hand operand by right hand b / a = 2.1


operand

% Modulus Divides left hand operand by right hand b%a=1


operand and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

30
Python 3

// Floor Division - The division of operands where 9//2 = 4 and


the result is the quotient in which the digits 9.0//2.0 = 4.0
after the decimal point are removed.

Example
Assume variable a holds 10 and variable b holds 20, then-

#!/usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)

c = a - b
print ("Line 2 - Value of c is ", c )

c = a * b
print ("Line 3 - Value of c is ", c)

c = a / b
print ("Line 4 - Value of c is ", c )

c = a % b
print ("Line 5 - Value of c is ", c)

a = 2
b = 3
c = a**b
print ("Line 6 - Value of c is ", c)

a = 10
b = 5
c = a//b
print ("Line 7 - Value of c is ", c)

When you execute the above program, it produces the following result-

Line 1 - Value of c is 31
Line 2 - Value of c is 11
31
Python 3

Line 3 - Value of c is 210


Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

Python Comparison Operators


These operators compare the values on either side of them and decide the relation among
them. They are also called Relational operators.

Assume variable a holds the value 10 and variable b holds the value 20, then-

Operator Description Example

(a == b)
If the values of two operands are equal, then the condition
== is not
becomes true.
true.

If values of two operands are not equal, then condition (a!= b) is


!=
becomes true. true.

If the value of left operand is greater than the value of right (a > b) is
>
operand, then condition becomes true. not true.

If the value of left operand is less than the value of right (a < b) is
<
operand, then condition becomes true. true.

(a >= b)
If the value of left operand is greater than or equal to the
>= is not
value of right operand, then condition becomes true.
true.

If the value of left operand is less than or equal to the value (a <= b)
<=
of right operand, then condition becomes true. is true.

Example
Assume variable a holds 10 and variable b holds 20, then-

#!/usr/bin/python3
a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:

32
Python 3

print ("Line 1 - a is not equal to b")

if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")

if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")

if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")

When you execute the above program, it produces the following result-

Line 1 - a is not equal to b


Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b
Line 5 - a is either less than or equal to b
Line 6 - b is either greater than or equal to b

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then-

Operator Description Example

= Assigns values from right side operands to c = a + b assigns


left side operand value of a + b into c

+= Add AND It adds right operand to the left operand c += a is equivalent


and assign the result to left operand to c = c + a

33
Python 3

-= Subtract AND It subtracts right operand from the left c -= a is equivalent


operand and assign the result to left to c = c - a
operand

*= Multiply AND It multiplies right operand with the left c *= a is equivalent


operand and assign the result to left to c = c * a
operand

/= Divide AND It divides left operand with the right c /= a is equivalent


operand and assign the result to left to c = c / ac /= a is
operand equivalent to c = c /
a

%= Modulus AND It takes modulus using two operands and c %= a is equivalent


assign the result to left operand to c = c % a

**= Exponent AND Performs exponential (power) calculation c **= a is


on operators and assign value to the left equivalent to c = c
operand ** a

//= Floor Division It performs floor division on operators and c //= a is equivalent
assign value to the left operand to c = c // a

Example
Assume variable a holds 10 and variable b holds 20, then-

#!/usr/bin/python3

a = 21
b = 10
c = 0

c = a + b
print ("Line 1 - Value of c is ", c)

c += a
print ("Line 2 - Value of c is ", c )

c *= a
print ("Line 3 - Value of c is ", c )

34
Python 3

c /= a
print ("Line 4 - Value of c is ", c )

c = 2
c %= a
print ("Line 5 - Value of c is ", c)

c **= a
print ("Line 6 - Value of c is ", c)

c //= a
print ("Line 7 - Value of c is ", c)

When you execute the above program, it produces the following result-

Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Python Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and
b = 13; Now in binary format they will be as follows-

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

Pyhton's built-in function bin() can be used to obtain binary representation of an integer
number.

35
Python 3

The following Bitwise operators are supported by Python language-

Operator Description Example

& Binary AND Operator copies a bit to the result, if it (a & b) (means 0000
exists in both operands 1100)

| Binary OR It copies a bit, if it exists in either (a | b) = 61 (means


operand. 0011 1101)

^ Binary XOR It copies the bit, if it is set in one operand (a ^ b) = 49 (means


but not both. 0011 0001)

~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means
Complement bits. 1100 0011 in 2's
complement form
due to a signed
binary number.

<< Binary Left Shift The left operand’s value is moved left by a << = 240 (means
the number of bits specified by the right 1111 0000)
operand.

>> Binary Right Shift The left operand’s value is moved right a >> = 15 (means
by the number of bits specified by the 0000 1111)
right operand.

Example
#!/usr/bin/python3

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0

c = a & b; # 12 = 0000 1100


print ("result of AND is ", c,':',bin(c))

c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))

36
Python 3

c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))

c = ~a; # -61 = 1100 0011


print ("result of COMPLEMENT is ", c,':',bin(c))

c = a << 2; # 240 = 1111 0000


print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2; # 15 = 0000 1111


print ("result of RIGHT SHIFT is ", c,':',bin(c))

When you execute the above program, it produces the following result-

a= 60 : 0b111100 b= 13 : 0b1101
result of AND is 12 : 0b1100
result of OR is 61 : 0b111101
result of EXOR is 49 : 0b110001
result of COMPLEMENT is -61 : -0b111101
result of LEFT SHIFT is 240 : 0b11110000
result of RIGHT SHIFT is 15 : 0b111

Python Logical Operators


The following logical operators are supported by Python language. Assume variable a holds
True and variable b holds False then-

Operator Description Example

and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.

or Logical OR If any of the two operands are non-zero then (a or b) is


condition becomes true. True.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b)
is True.

37
Python 3

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists,
or tuples. There are two membership operators as explained below-

Operator Description Example

in Evaluates to true, if it finds a variable x in y, here in results in


in the specified sequence and false a 1 if x is a member of
otherwise. sequence y.

not in Evaluates to true, if it does not find a x not in y, here not in


variable in the specified sequence and results in a 1 if x is not
false otherwise. a member of sequence
y.

Example
#!/usr/bin/python3

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")

if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")

c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")

38
Python 3

When you execute the above program, it produces the following result-

Line 1 - a is not available in the given list


Line 2 - b is not available in the given list
Line 3 - a is available in the given list

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below:

Operator Description Example

is Evaluates to true if the variables on x is y, here is results


either side of the operator point to the in 1 if id(x) equals
same object and false otherwise. id(y).

is not Evaluates to false if the variables on x is not y, here is


either side of the operator point to the not results in 1 if id(x)
same object and true otherwise. is not equal to id(y).

Example
#!/usr/bin/python3

a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")

if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")

39
Python 3

b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")

When you execute the above program, it produces the following result-

Line 1 a= 20 : 1594701888 b= 20 : 1594701888


Line 2 - a and b have same identity
Line 3 - a and b have same identity
Line 4 a= 20 : 1594701888 b= 30 : 1594702048
Line 5 - a and b do not have same identity

Python Operators Precedence


The following table lists all the operators from highest precedence to the lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Ccomplement, unary plus and minus (method names for


the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

40
Python 3

= %= /= //= -= += *= Assignment operators


**=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects the evaluation of an an expression.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator * has
higher precedence than +, so it first multiplies 3*2 and then is added to 7.

Here, the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.

Example
#!/usr/bin/python3

a = 20
b = 10
c = 15
d = 5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))


e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d) # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

When you execute the above program, it produces the following result-

a:20 b:10 c:15 d:5


Value of (a + b) * c / d is 90.0

41
Python 3

Value of ((a + b) * c) / d is 90.0


Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

42
7. Python 3 – Decision Making Python 3

Decision-making is the anticipation of conditions occurring during the execution of a


program and specified actions taken according to the conditions.

Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the
outcome. You need to determine which action to take and which statements to execute if
the outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages-

Python programming language assumes any non-zero and non-null values as TRUE, and
any zero or null values as FALSE value.

Python programming language provides the following types of decision-making


statements.

Statement Description

An if statement consists of a Boolean expression followed by


if statements
one or more statements.

An if statement can be followed by an optional else


if...else statements statement, which executes when the boolean expression is
FALSE.

43
Python 3

You can use one if or else if statement inside


nested if statements
another if or else if statement(s).

Let us go through each decision-making statement quickly.

IF Statement
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result
of the comparison.

Syntax
if expression:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. In Python, statements in a block are uniformly indented after the
: symbol. If boolean expression evaluates to FALSE, then the first set of code after the
end of block is executed.

Flow Diagram

Example
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)

44
Python 3

var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")

When the above code is executed, it produces the following result −

1 - Got a true expression value


100
Good bye!

IF...ELIF...ELSE Statements
An else statement can be combined with an if statement. An else statement contains a
block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSE value.

The else statement is an optional statement and there could be at the most only
one else statement following if.

Syntax
The syntax of the if...else statement is-

if expression:
statement(s)
else:
statement(s)

45
Python 3

Flow Diagram

Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)

print ("Net payable:",amount-discount)

In the above example, discount is calculated on the input amount. Rate of discount is 5%,
if the amount is less than 1000, and 10% if it is above 10000. When the above code is
executed, it produces the following result-

Enter amount: 600


Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
46
Python 3

Net payable: 1080.0

The elif Statement


The elif statement allows you to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE.

Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at the most one statement, there can be an arbitrary number of elif statements
following an if.

Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows-

Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))

if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)

When the above code is executed, it produces the following result-

47
Python 3

Enter amount: 600


Discount 30.0
Net payable: 570.0

Enter amount: 3000


Discount 300.0
Net payable: 2700.0

Enter amount: 6000


Discount 900.0
Net payable: 5100.0

Nested IF Statements
There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct.

In a nested if construct, you can have an if...elif...else construct inside another


if...elif...else construct.

Syntax
The syntax of the nested if...elif...else construct may be-

if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)

Example
# !/usr/bin/python3
num=int(input("enter number"))
48
Python 3

if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

When the above code is executed, it produces the following result-

enter number8
divisible by 2 not divisible by 3

enter number15
divisible by 3 not divisible by 2

enter number12
Divisible by 3 and 2

enter number5
not Divisible by 2 not divisible by 3

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.

Here is an example of a one-line if clause-

#!/usr/bin/python3
var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")

When the above code is executed, it produces the following result-

Value of expression is 100


Good bye!
49
Python 3

50
8. Python 3 – Loops Python 3

In general, statements are executed sequentially- The first statement in a function is


executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several number of times.

Programming languages provide various control structures that allow more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.


The following diagram illustrates a loop statement.

Python programming language provides the following types of loops to handle looping
requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.

for loop Executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

51
Python 3

nested loops You can use one or more loop inside any another while, or
for loop.

while Loop Statements


A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is-

while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements with uniform


indent. The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.

In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

Flow Diagram

52
Python 3

Here, a key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.

Example
#!/usr/bin/python3

count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1

print ("Good bye!")

When the above code is executed, it produces the following result-

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4

53
Python 3

The count is: 5


The count is: 6
The count is: 7
The count is: 8
Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly
until count is no longer less than 9. With each iteration, the current value of the index
count is displayed and then increased by 1.

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious
when using while loops because of the possibility that this condition never resolves to a
FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.

#!/usr/bin/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")

When the above code is executed, it produces the following result-

Enter a number :20


You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number :"))
KeyboardInterrupt

54
Python 3

The above example goes in an infinite loop and you need to use CTRL+C to exit the
program.

Using else Statement with Loops


Python supports having an else statement associated with a loop statement.

 If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.

 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else statement
gets executed.

#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")

When the above code is executed, it produces the following result-

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single statement,
it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause-

#!/usr/bin/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")

The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
55
Python 3

for Loop Statements


The for statement in Python has the ability to iterate over the items of any sequence, such
as a list or a string.

Syntax
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.

Flow Diagram

56
Python 3

The range() function


The built-in function range() is the right function to iterate over a sequence of numbers.
It generates an iterator of arithmetic progressions.

>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a
list object of the sequence, it is typecasted to list(). Now this list can be iterated using the
for statement.

>>> for var in list(range(5)):


print (var)

This will produce the following output.

0
1
2
3
4

Example
#!/usr/bin/python3
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)

print ("Good bye!")

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y

57
Python 3

Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n

Current fruit : banana


Current fruit : apple
Current fruit : mango
Good bye!

Iterating by Sequence Index


An alternative way of iterating through each item is by index offset into the sequence
itself. Following is a simple example-

#!/usr/bin/python3
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")

When the above code is executed, it produces the following result-

Current fruit : banana


Current fruit : apple
Current fruit : mango
Good bye!

Here, we took the assistance of the len() built-in function, which provides the total number
of elements in the tuple as well as the range() built-in function to give us the actual
sequence to iterate over.

Using else Statement with Loops


Python supports having an else statement associated with a loop statement.

 If the else statement is used with a for loop, the else block is executed only if for
loops terminates normally (and not by encountering break statement).

 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

58
Python 3

The following example illustrates the combination of an else statement with a for
statement that searches for even number in given list.

#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number')

When the above code is executed, it produces the following result-

the list does not contain even number

Nested loops
Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.

Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as
follows-

while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that you can put any type of loop inside any other type of
loop. For example a for loop can be inside a while loop or vice versa.

Example
The following program uses a nested-for loop to display multiplication tables from 1-10.

#!/usr/bin/python3
import sys

59
Python 3

for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

The print() function inner loop has end=' ' which appends a space instead of default
newline. Hence, the numbers will appear in one row.

Last print() will be executed at the end of inner for loop.

When the above code is executed, it produces the following result −

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
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Loop Control Statements


The Loop control statements change the execution from its normal sequence. When the
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.

Python supports the following control statements.

Control Statement Description

break statement Terminates the loop statement and transfers


execution to the statement immediately
following the loop.

continue statement Causes the loop to skip the remainder of its


body and immediately retest its condition prior
to reiterating.

60
Python 3

pass statement The pass statement in Python is used when a


statement is required syntactically but you do
not want any command or code to execute.

Let us go through the loop control statements briefly.

break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the traditional
break statement in C.

The most common use of break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost
loop and starts executing the next line of the code after the block.

Syntax
The syntax for a break statement in Python is as follows-

break

Flow Diagram

61
Python 3

Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)

var = 10 # Second Example


while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break

print ("Good bye!")

When the above code is executed, it produces the following result-

Current Letter : P
Current Letter : y
Current Letter : t
62
Python 3

Current variable value : 10


Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

The following program demonstrates the use of break in a for loop iterating over a list.
User inputs a number, which is searched in the list. If it is found, then the loop terminates
with the 'found' message.

#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')

The above program will produce the following output-

any number: 33
number found in list
any number: 5
number not found in list

continue Statement
The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.

The continue statement can be used in both while and for loops.

Syntax
continue

63
Python 3

Flow Diagram

Example
#!/usr/bin/python3

for letter in 'Python': # First Example


if letter == 'h':
continue
print ('Current Letter :', letter)

var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!")

When the above code is executed, it produces the following result-

Current Letter : P

64
Python 3

Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!

pass Statement
It is used when a statement is required syntactically but you do not want any command
or code to execute.

The pass statement is a null operation; nothing happens when it executes. The
pass statement is also useful in places where your code will eventually go, but has not
been written yet i.e. in stubs).

Syntax
pass

Example
#!/usr/bin/python3

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)

print ("Good bye!")

When the above code is executed, it produces the following result-


65
Python 3

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Iterator and Generator


Iterator is an object, which allows a programmer to traverse through all the elements of
a collection, regardless of its specific implementation. In Python, an iterator object
implements two methods, iter() and next().

String, List or Tuple objects can be used to create an Iterator.

list=[1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this

A generator is a function that produces or yields a sequence of values using yield method.

When a generator function is called, it returns a generator object without even beginning
execution of the function. When the next() method is called for the first time, the function
starts executing, until it reaches the yield statement, which returns the yielded value. The
yield keeps track i.e. remembers the last execution and the second next() call continues
from previous value.

The following example defines a generator, which generates an iterator for all the Fibonacci
numbers.

!usr/bin/python3

66
Python 3

import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object

while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()

67
9. Python 3 – Numbers Python 3

Number data types store numeric values. They are immutable data types. This means,
changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example-

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example-

del var
del var_a, var_b

Python supports different numerical types-

 int (signed integers): They are often called just integers or ints. They are
positive or negative whole numbers with no decimal point. Integers in Python 3 are
of unlimited size. Python 2 has two integer types - int and long. There is no 'long
integer' in Python 3 anymore.

 float (floating point real values) : Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and the fractional
parts. Floats may also be in scientific notation, with E or e indicating the power of
10 (2.5e2 = 2.5 x 102 = 250).

 complex (complex numbers) : are of the form a + bJ, where a and b are floats
and J (or j) represents the square root of -1 (which is an imaginary number). The
real part of the number is a, and the imaginary part is b. Complex numbers are not
used much in Python programming.

It is possible to represent an integer in hexa-decimal or octal form.

>>> number = 0xA0F #Hexa-decimal


>>> number
2575

>>> number=0o37 #Octal


>>> number

68

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy