Python Reading Material
Python Reading Material
Python .......................................................................................................................................................... 9
Audience ...................................................................................................................................................... 9
Prerequisites ................................................................................................................................................ 9
Python Overview......................................................................................................................................... 9
History of Python .............................................................................................................................. 10
Python Features................................................................................................................................ 10
Python - Environment Setup................................................................................................................... 11
Local Environment Setup............................................................................................................... 11
Getting Python................................................................................................................................... 12
Installing Python .............................................................................................................................. 12
Unix and Linux Installation ................................................................................................ 12
Windows Installation............................................................................................................. 13
Macintosh Installation .......................................................................................................... 13
Setting up PATH ................................................................................................................................ 14
Setting path at Unix/Linux............................................................................................................ 14
Setting path at Windows ............................................................................................................... 14
Python Environment Variables .................................................................................................... 17
Running Python................................................................................................................................. 19
Interactive Interpreter ......................................................................................................... 19
Script from the Command-line ......................................................................................... 20
Integrated Development Environment ....................................................................... 21
Python Basic Syntax................................................................................................................................. 21
First Python Program ...................................................................................................................... 21
Interactive Mode Programming ...................................................................................... 22
Script Mode Programming .................................................................................................. 22
Python Identifiers............................................................................................................................. 23
Reserved Words................................................................................................................................ 24
Lines and Indentation..................................................................................................................... 25
Multi-Line Statements..................................................................................................................... 26
Quotation in Python......................................................................................................................... 26
Comments in Python....................................................................................................................... 27
Using Blank Lines ............................................................................................................................. 28
Waiting for the User Input ............................................................................................................ 28
Multiple Statements on a Single Line ........................................................................................ 30
Multiple Statement Groups as Suites ........................................................................................ 30
Command Line Arguments ........................................................................................................... 33
Python Variable Types.............................................................................................................................. 34
Assigning Values to Variables ...................................................................................................... 34
Multiple Assignment ........................................................................................................................ 35
Standard Data Types ....................................................................................................................... 35
Python Numbers............................................................................................................................... 37
Integer Objects ......................................................................................................................................... 37
Examples ....................................................................................................................................... 44
Python Strings ................................................................................................................................... 47
Python Numbers ....................................................................................................................................... 49
Integer Objects ......................................................................................................................................... 49
Examples ....................................................................................................................................... 51
Number Type Conversion .............................................................................................................. 51
Mathematical Functions ................................................................................................................. 52
Random Number Functions .......................................................................................................... 54
Mathematical Constants................................................................................................................. 56
Python Strings........................................................................................................................................... 57
Accessing Values in Strings .......................................................................................................... 57
Updating Strings ............................................................................................................................... 58
Escape Characters ............................................................................................................................ 58
String Special Operators ................................................................................................................ 61
String Formatting Operator .......................................................................................................... 62
Unicode String ................................................................................................................................... 67
unicode() GLOBAL FUNCTION# ................................................................................................................ 67
Built-in String Methods................................................................................................................... 67
Python Lists ............................................................................................................................................... 74
Python Lists ........................................................................................................................................ 74
Accessing Values in Lists ............................................................................................................... 74
Updating Lists .................................................................................................................................... 75
Delete List Elements ........................................................................................................................ 75
Basic List Operations ....................................................................................................................... 76
Indexing, Slicing, and Matrixes ................................................................................................... 76
Built-in List Functions & Methods:.............................................................................................. 77
Python Tuples............................................................................................................................................ 79
Accessing Values in Tuples: .......................................................................................................... 79
Updating Tuples ................................................................................................................................ 80
Delete Tuple Elements .................................................................................................................... 80
Basic Tuples Operations................................................................................................................. 81
Indexing, Slicing, and Matrixes ................................................................................................... 81
No Enclosing Delimiters ................................................................................................................. 82
Built-in Tuple Functions.................................................................................................................. 82
Python Dictionary...................................................................................................................................... 83
Accessing Values in Dictionary:................................................................................................... 83
Updating Dictionary ......................................................................................................................... 84
Delete Dictionary Elements........................................................................................................... 84
Properties of Dictionary Keys....................................................................................................... 85
Built-in Dictionary Functions & Methods −.............................................................................. 87
Python Date & Time ................................................................................................................................. 89
What is Tick? ...................................................................................................................................... 89
Example ............................................................................................................................................... 89
What is TimeTuple? ......................................................................................................................... 89
Getting current time ........................................................................................................................ 91
Getting calendar for a month ....................................................................................................... 92
The time Module ............................................................................................................................... 92
The calendar Module ....................................................................................................................... 98
Other Modules & Functions: ....................................................................................................... 104
Data Type Conversion ................................................................................................................... 104
Python Basic Operators.......................................................................................................................... 121
Types of Operator........................................................................................................................... 121
Python Arithmetic Operators ..................................................................................................... 122
Python Comparison Operators .................................................................................................. 122
Python Assignment Operators................................................................................................... 123
Python Logical Operators ............................................................................................................ 124
Python Bitwise Operators............................................................................................................ 125
Python Membership Operators.................................................................................................. 127
Example ....................................................................................................................................... 127
Python Identity Operators .......................................................................................................... 128
Example ....................................................................................................................................... 129
Python Operators Precedence ................................................................................................... 130
Example ....................................................................................................................................... 132
Python Decision Making......................................................................................................................... 134
Syntax: ............................................................................................................................................... 136
Single Statement Suites ............................................................................................................... 138
Python Loops........................................................................................................................................... 139
Syntax .................................................................................................................................................. 140
Syntax of for Loop .............................................................................................................................. 142
Syntax of pass .................................................................................................................................... 144
Python Functions .................................................................................................................................... 146
Defining a Function ........................................................................................................................ 146
Syntax................................................................................................................................................. 146
Example ............................................................................................................................................. 147
Calling a Function ........................................................................................................................... 147
Pass by reference vs value.......................................................................................................... 147
Function Arguments ...................................................................................................................... 149
Required arguments...................................................................................................................... 149
Keyword arguments (parameter named notation) ........................................................... 150
Default arguments ......................................................................................................................... 151
Variable-length arguments ......................................................................................................... 152
The Anonymous Functions.......................................................................................................... 155
Syntax................................................................................................................................................. 155
The return Statement.................................................................................................................... 156
Scope of Variables .......................................................................................................................... 157
Global vs. Local variables............................................................................................................. 157
Python Modules....................................................................................................................................... 159
Example ............................................................................................................................................. 159
How to import modules in Python? .................................................................................................. 160
Import with renaming ......................................................................................................................... 160
Python from...import statement ...................................................................................................... 161
The from...import * Statement: ....................................................................................................... 162
Locating Modules............................................................................................................................ 163
The PYTHONPATH Variable: ....................................................................................................... 165
Namespaces and Scoping............................................................................................................ 166
The dir( ) Function ......................................................................................................................... 168
The globals() and locals() Functions ....................................................................................... 168
The reload() Function ................................................................................................................... 170
Python Files I/O ......................................................................................................................................... 175
Printing to the Screen ................................................................................................................... 175
Reading Keyboard Input.............................................................................................................. 175
The raw_input Function ............................................................................................................... 175
The input Function ......................................................................................................................... 176
Opening and Closing Files............................................................................................................ 176
The open Function.......................................................................................................................... 177
Syntax ........................................................................................................................................... 177
The file Object Attributes ............................................................................................................. 178
Example ....................................................................................................................................... 179
The close() Method ........................................................................................................................ 180
Syntax ........................................................................................................................................... 180
Example ....................................................................................................................................... 180
Reading and Writing Files............................................................................................................ 181
The write() Method........................................................................................................................ 181
Example ....................................................................................................................................... 181
The read() Method ......................................................................................................................... 182
Syntax ........................................................................................................................................... 182
Example ....................................................................................................................................... 182
File Positions .................................................................................................................................... 184
Example ....................................................................................................................................... 184
Renaming and Deleting Files...................................................................................................... 185
The rename() Method................................................................................................................... 185
Syntax ........................................................................................................................................... 185
Example ....................................................................................................................................... 185
The copyfile() Method................................................................................................................... 186
The remove() Method................................................................................................................... 186
Syntax ........................................................................................................................................... 186
Example ....................................................................................................................................... 186
Directories in Python..................................................................................................................... 186
The mkdir() Method ...................................................................................................................... 187
Syntax ........................................................................................................................................... 187
Example ....................................................................................................................................... 187
The chdir() Method ........................................................................................................................ 187
Syntax ........................................................................................................................................... 187
Example ....................................................................................................................................... 187
The getcwd() Method ................................................................................................................... 188
Syntax ........................................................................................................................................... 188
Example ....................................................................................................................................... 188
The rmdir() Method ....................................................................................................................... 188
Syntax: ......................................................................................................................................... 188
Example ....................................................................................................................................... 188
File & Directory Related Methods.............................................................................................. 189
Python Exceptions Handling ..................................................................................................................... 198
Assertions in Python ............................................................................................................ 200
The assert Statement .......................................................................................................... 201
Example 1. .................................................................................................................................. 201
Example 2. .................................................................................................................................. 202
What is Exception?......................................................................................................................... 202
Handling an exception .................................................................................................................. 203
Syntax ........................................................................................................................................... 203
Example ....................................................................................................................................... 203
The except Clause with No Exceptions ................................................................................... 204
The except Clause with Multiple Exceptions ......................................................................... 205
The try-finally Clause..................................................................................................................... 206
Example ....................................................................................................................................... 206
Argument of an Exception........................................................................................................... 207
Example ....................................................................................................................................... 208
Raising an Exception ..................................................................................................................... 208
Syntax ........................................................................................................................................... 209
Example ....................................................................................................................................... 209
User-Defined Exceptions.............................................................................................................. 209
Python 3 - Object Oriented ................................................................................................................... 210
Overview of OOP Terminology .................................................................................................. 210
Creating Classes.............................................................................................................................. 211
Example ....................................................................................................................................... 212
Creating Instance Objects........................................................................................................... 212
Accessing Attributes...................................................................................................................... 213
Built-In Class Attributes ............................................................................................................... 215
Destroying Objects (Garbage Collection) .............................................................................. 216
Example ....................................................................................................................................... 217
Class Inheritance............................................................................................................................ 219
Syntax ........................................................................................................................................... 219
Example ....................................................................................................................................... 219
Overriding Methods ....................................................................................................................... 221
Example ....................................................................................................................................... 221
Base Overloading Methods ......................................................................................................... 221
Overloading Operators ................................................................................................................. 222
Example ....................................................................................................................................... 222
Data Hiding ....................................................................................................................................... 223
Example ....................................................................................................................................... 223
Python 3 - Regular Expressions............................................................................................................ 225
Basic patterns that match single chars .................................................................... 225
Compilation flags ................................................................................................................... 226
The match Function ....................................................................................................................... 227
Example 1. .................................................................................................................................. 228
Example 2. .................................................................................................................................. 229
Example 3. .................................................................................................................................. 229
The search Function ...................................................................................................................... 229
Example 1. .................................................................................................................................. 231
Example 2. .................................................................................................................................. 231
Matching Versus Searching......................................................................................................... 232
Example ....................................................................................................................................... 232
The Search and Replace function (sub).................................................................................. 232
Syntax ........................................................................................................................................... 232
Example ....................................................................................................................................... 232
The split Function ........................................................................................................................... 233
Syntax ........................................................................................................................................... 233
The Findall Function....................................................................................................................... 235
Syntax ........................................................................................................................................... 235
The Finditer Function .................................................................................................................... 236
Syntax ........................................................................................................................................... 236
Regular Expression Modifiers: Option Flags.......................................................................... 237
Regular Expression Patterns ...................................................................................................... 239
Regular Expression Examples.................................................................................................... 239
Literal characters ................................................................................................................... 239
Character classes............................................................................................................................ 239
Special Character Classes ............................................................................................................ 240
Repetition Cases ............................................................................................................................. 241
Nongreedy repetition .................................................................................................................... 241
Grouping with Parentheses ........................................................................................................ 242
Backreferences................................................................................................................................ 242
Alternatives....................................................................................................................................... 243
Anchors .............................................................................................................................................. 243
Special Syntax with Parentheses.............................................................................................. 244
Python
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).
Audience
Software programmers who need 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.
Python Overview
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 other languages use punctuation, and it has fewer
syntactical constructions than other languages.
• Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL).
Python Features
Python's features include:
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• 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.
• 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, few are listed below:
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
• Win 9x/NT/2000
• OS/2
• Windows CE
• Acorn/RISC OS
• BeOS
• Amiga
• VMS/OpenVMS
• QNX
• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines
Getting Python
The most up-to-date and current source code, binaries, documentation,
news, etc., is available on the official website of
Python https://www.python.org/ .
Installing Python
Python distribution is available for a wide variety of platforms. You need to
download only the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler
to compile the source code manually. Compiling the source code offers more
flexibility in terms of choice of features that you require in your installation.
• make
• make install
Windows Installation
Here are the steps to install Python on Windows machine.
• Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
• To use this installer python-XYZ.msi, the Windows system must support Microsoft
Installer 2.0. Save the installer file to your local machine and then run it to find
out if your machine supports MSI.
• Run the downloaded file. This brings up the Python install wizard, which is really
easy to use. Just accept the default settings, wait until the install is finished, and
you are done.
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of
date. See http://www.python.org/download/mac/ for instructions on getting
the current version along with extra tools to support development on the Mac.
For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is
available.
Jack Jansen maintains it and you can have full access to the entire
documentation at his website − http://www.cwi.nl/~jack/macpython.html.
You can find complete installation details for Mac OS installation.
Setting up PATH
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.
At the command prompt − type path echo %path% and press Enter.
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\Users\rharlalk>cd ..
C:\Users>cd..
C:\Program Files\Python36>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
Welcome to Python!
Rakhee Harlalka
>>>
Or
Python 3.6.2
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>>import sys
>>>print(sys.version);
>>>import platform
>>>platform.python_version();
'3.6.2'
>>> help()
1 PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter
where to locate the module files imported into a program. It should include
the Python source library directory and the directories containing Python
source code. PYTHONPATH is sometimes preset by the Python installer.
2 PYTHONSTARTUP
3
PYTHONCASEOK
4 PYTHONHOME
Create a file named startupImports.py and write the below code in it.
import os
cls = lambda: os.system('cls')
print('Welcome to Python')
print('Rakhee Harlalka')
Copy this file in the directory where python binaries are installed. In my case
it is:
C:\Program Files\Python36
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python
Rakhee Harlalka
>>>
Welcome to Python
Rakhee Harlalka
>>>
Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you
a command-line interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1 -d
2 -O
3
-S
4
-v
5 -X
6
-c cmd
7 file
or
• 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
help from 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 2.4.3 version available on CentOS flavor of Linux.
$ python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python
Rakhee Harlalka
>>>
Type the following text at the Python prompt and press the Enter:
If you are running new version of Python 3, then you would need to use print
statement with parenthesis as in print ("Hello, Python!");.
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.
We assume that you have Python interpreter set in PATH variable. Now, try
to run this program as follows −
$ python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py
file −
#!/usr/bin/python
For window
C:\Program Files\Python36>chdir D:/Users/rharlalk/Desktop/Python
C:\Program Files\Python36>D:
D:\Users\rharlalk\Desktop\Python>python -i test.py
Hello, Python!
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).
• 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.
• 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 constant or variable or any other identifier names.
All the Python keywords contain lowercase letters only.
assert finally or
def if return
else is with
Python provides no 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 with the same amount space. For example −
if True:
print("True")
else:
print("False")
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False")
C:\>python -i D:\Users\haryadav\Desktop\Python\test.txt
File "D:\Users\haryadav\Desktop\Python\test.txt", line 6
print("False")
^
IndentationError: unindent does not match any outer indentation level
>>>exit()
Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however,
allow the use of the line continuation character (\) to denote that the line
should continue. For example −
total = 100 + \
200 + \
300 + \
400
print(total)
1000
name = 'hari','ram','dev', \
'mark', \
'shyam', \
'irshad'
print(name)
('hari', 'ram', 'dev', 'mark', 'shyam', 'irshad')
Statements contained within the [], {}, or () do not need to use the line
continuation character. For example −
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 = 'India'
sentence = "India is our country. It’s capital is New Delhi"
print(word)
print(sentence)
paragraph
'India is our country. It has\n29 states and seven union territories.'
print(paragraph)
India is our country. It has
29 states and seven union territories.
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print("Hello, Python!") # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
# This is a comment line.
if False:
""" This is to
show you
multiline comments."""
if False:
print("True")
print ("Hello, Python!")
print ("This is our first program!")
else:
print("False")
print ("Hello, Python!")
print ("This is our first program!")
#!/usr/bin/python
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.
NOTE:
In Python 3.x, input() replaces raw_input(), for input from the console. It returns the
user's response as string, so when an int or a float is needed, it is necessary to convert
the returned value from the str type using int() or float().
Python provides the function input(). input has an optional parameter, which
is the prompt string.
If the input function is called, the program flow will be stopped until the user
has given an input and has ended the input with the return key. The text of
the optional parameter, i.e. the prompt, will be printed on the screen.
The input of the user will be interpreted. If the user e.g. puts in an integer
value, the input function returns this integer value. If the user on the other
hand inputs a list, the function will return a list.
C:\>python -i D:\Users\haryadav\Desktop\Python\input_test.txt
What's your name? Rakhee
Your age? 35
Rakhee <class 'str'>
35 <class 'str'>
Your favourite colours? ["Red","Blue",'Green','Yellow',"Pink"]
["Red","Blue",'Green','Yellow',"Pink"]
["Red","Blue",'Green','Yellow',"Pink"] <class 'str'>
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: # This is header line
suite # This is suite line and it should be indented equally.
elif expression:
suite
else:
suite
NOTE: if , elif, else keyword should be lined up and suite line should be indented.
else :
print("Outstanding.");
print("Well done.");
# Output
C:\>python -i D:\Users\haryadav\Desktop\Python\input_test.txt
He is fail.
He should work hard.
>>> exit()
C:\>python -i D:\Users\haryadav\Desktop\Python\input_test.txt
He stood 2nd.
He need improvments.
>>> exit()
C:\>python -i D:\Users\haryadav\Desktop\Python\input_test.txt
He stood 1st.
>>> exit()
C:\>python -i D:\Users\haryadav\Desktop\Python\input_test.txt
Outstanding.
Well done.
>>> exit()
x = 10 ; y = 20 ; z = 30
if x < y < z: print(x); print(y); print(z);
...
10
20
30
NOTE: if , elif, else keyword should be lined up and suite line should be indented.
if z < y < x:
... print(x);
... print(y);
... print(z);
... else:
... print("else execution");
File "<stdin>", line 6
print("else execution");
^
IndentationError: expected an indented block
if z < y < x:
... print(x);
... print(y);
... print(z);
... else:
... print("else execution");
...
else execution
$ 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.
Python Variable Types
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in 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 variables, you can store integers, decimals or
characters in these 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 −
Here, 100, 1000.55 and "Dev" are the values assigned to v_counter, v_miles,
and v_name variables, respectively. This produces the following result −
a = b = c = 1
print(a, b, c)
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects
to multiple variables. For example −
a,b,c = 1,2,"john"
print(a, b, c)
Here, two integer objects with values 1 and 2 are assigned to variables a and
b respectively, and one string object with the value "john" is assigned to the
variable c.
Python has many native datatypes. Here are the important ones:
int 24
float 24
dict 240
set 224
tuple 48
list 64
str 50
unicode 50
decimal 104
object 16
Python Numbers
Integer Objects
All integers are implemented as “long” integer objects of arbitrary size.
Python has arbitrary precision integers so there is no true fixed maximum.
You're only limited by available memory.
Integer representations
bin(19)
'0b10011'
If the number of bits used is fixed, the range of integers that can be
represented would be fixed and can potentially overflow. That is the case for
many languages such as C/C++.
Short answers:
No
if the operations are done in pure python, because python integers have
arbitrary precision
Yes
if the operations are done in the pydata stack (numpy/pandas), because they
use C-style fixed-precision integers.
Arbitrary precision
In python 2, there were actually two integers types: int and long, where int
is the C-style fixed-precision integer and long is the arbitrary-precision
integer. Operations are automatically promoted to long if int is not sufficient,
so there's no risk of overflowing. In python 3, int is the only integer type,
long is obsoleted and it is arbitrary-precision.
Number data types store numeric values. Number objects are created when
you assign a value to them. For example −
var1 = 20
var2 = 40
var3 = 60
var4 = 70
var5 = 80
print(var1, '\t', var2, '\t', var3, '\t', var4, '\t', var5)
20 40 60 70 80
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x0000023858E3F0B8>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, '__cached__': None,
'os': <module 'os' from 'C:\\Program Files\\Python36\\lib\\os.py'>,
'cls': <function <lambda> at 0x0000023858DB3E18>, 'name': 'var5',
'value': 80, 'var1': 20, 'var2': 40, 'var3': 60, 'var4': 70, 'var5':
80, 'vars': 'vars'}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x0000023858E3F0B8>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, '__cached__': None,
'os': <module 'os' from 'C:\\Program Files\\Python36\\lib\\os.py'>,
'cls': <function <lambda> at 0x0000023858DB3E18>, 'name': 'var5',
'value': 80, 'var1': 20, 'var2': 40, 'var3': 60, 'var4': 70, 'var5':
80, 'vars': 'vars'}
>>> locals('%var%')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: locals() takes no arguments (1 given)
{'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__cached__': None,
'__doc__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x0000023858E3F0B8>,
'__name__': '__main__',
'__package__': None,
'__spec__': None,
'cls': <function <lambda> at 0x0000023858DB3E18>,
'name': 'var5',
'os': <module 'os' from 'C:\\Program Files\\Python36\\lib\\os.py'>,
'pprint': <module 'pprint' from 'C:\\Program
Files\\Python36\\lib\\pprint.py'>,
'sys': <module 'sys' (built-in)>,
'value': 80,
'var1': 20,
'var2': 40,
'var3': 60,
'var4': 70,
'var5': 80,
'vars': 'vars'}
var1
var2
var3
var4
var5
vars
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 var1
del var2, var5
>>> print(var1, '\t', var2, '\t', var3, '\t', var4, '\t', var5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
• long (long integers, they can also be represented in octal and hexadecimal)
NOTE: The long() function is no longer supported by Python 3. It only has one built-in
integral type, named int; but it behaves mostly like the old long type. So you just need
to use int() built-in function in python-3.x.
import sys
sys.maxsize
9223372036854775807
sys.maxint
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'sys' has no attribute 'maxint'
vnum=9223372036854775807999999999999999999999999999999999999999999999999999999
999999999999999999999;
vnum
922337203685477580799999999999999999999999999999999999999999999999999999999999
9999999999999999
sys.getsizeof(sys.maxsize);
36
sys.getsizeof(vnum);
68
Examples
Here are some examples of numbers −
• Python allows you to use a lowercase l with long, but it is recommended that you
use only an uppercase L to avoid confusion with the number 1. Python displays
long integers with an uppercase L.
v_num = 99999;
print(v_num, type(v_num))
99999 <class 'int'>
v_num = '99999';
print(v_num, type(v_num))
99999 <class 'str'>
v_num = float(99999);
print(v_num, type(v_num))
99999.0 <class 'float'>
del v_num
v_num = long(5.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'long' is not defined
v_comp = complex(2,3)
print(v_comp, type(v_comp))
(2+3j) <class 'complex'>
v_comp.real
2.0
v_comp.imag
3.0
v_comp.conjugate() # Change the sign of imaginary part.
(2-3j)
pow(3 + 4j, 2)
(-7+24j)
y = complex(3,4)
print y
(3+4j)
z = x+y
print z
(4+6j)
z = x-y
print(z)
(-2-2j)
z = x*y
print z
(-5+10j)
z = x/y
print z
(0.44+0.08j)
print x.conjugate()
(1-2j)
print x.real
1.0
print x.imag
2.0
print x>y
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
print x>y
TypeError: no ordering relation is defined for complex numbers
print x==y
False
Python Strings
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs 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 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
orl
str[5] = '-'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
del str[2:5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item deletion
Python Numbers
Integer Objects
All integers are implemented as “long” integer objects of arbitrary size.
https://docs.python.org/3/c-api/long.html
Number data types store numeric values. They are immutable data types,
means that changing the value of a number data type results in a new
allocated object.
Number objects are created when you assign a value to them. For example
−
var1 = 1
var2 = 10
id(var1)
1539688112
id(var2)
1539688400
id(var1)
1539691280
id(var2)
1539694480
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
• int (signed integers): They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
• long (long integers ): Also called longs, they are integers of unlimited size,
written like integers and followed by an uppercase or lowercase L. No longer
supported in Version 3.x.
• float (floating point real values) : Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and 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.
Python has arbitrary precision integers so there is no true fixed maximum. You're only
limited by available memory. sys.maxint does not even exist in Python 3, since int and
long were unified into a single arbitrary precision int type.
v_num =
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
999999999999999999999999999;
print(v_num);
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999
999999999999999999999999999
Examples
Here are some examples of numbers
• Type complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions
float(2);
2.0
float(5.55);
5.55
complex(5)
(5+0j)
complex(5,2)
(5+2j)
Mathematical Functions
Python includes following functions that perform mathematical calculations.
y)
math.floor(4.4);
4
math.floor(4.8);
4
math.log(5);
1.6094379124341003
max(x1, The largest of its arguments: the value closest to positive infinity
x2,...) max(10,20,66,45,87,55,23,58)
87
min(x1, The smallest of its arguments: the value closest to negative infinity
x2,...) min(10,20,66,45,87,55,23,58)
10
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign
math.modf(1,5);
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: modf() takes exactly one argument (2 given)
y) math.pow(2,5);
32.0
round(7676567.6556757,3);
7676567.656
round(7676567.6544757,3);
7676567.654
Function Description
x=(1, 2, 3, 5, 9);
print(type(x))
<class 'tuple'>
random.choice([1, 2, 3, 5, 9]);
5
random.choice([1, 2, 3, 5, 9]);
1
random.choice((1, 2, 3, 5, 9));
5
random.choice((1, 2, 3, 5, 9));
2
random.choice('India is my country.');
'd'
random.choice('India is my country.');
'm'
random() A random float r, such that 0 is less than or equal to r and r is less than 1
print("random() : ", random.random());
random() : 0.0623392041549814
seed([x]) Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.
random.seed( 10 )
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.5714025946899135
random.seed( 10 )
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.5714025946899135
random.seed( 10 )
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.5714025946899135
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.4288890546751146
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.20609823213950174
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.81332125135732
print("Random number with seed 10 : ", random.random())
Random number with seed 10 : 0.8235888725334455
A random float r, such that x is less than or equal to r and r is less than y
uniform(x, y)
print("Random Float uniform(1, 10) : ", random.uniform(1, 10))
print("Random Float uniform(1, 10) : ", random.uniform(1, 10))
Random Float uniform(1, 10) : 6.418091089533576
Random Float uniform(1, 10) : 8.37482423567478
Mathematical Constants
The module also defines two mathematical constants −
Constants Description
import math
math.pi
3.141592653589793
math.e
2.718281828459045
Python Strings
Strings are amongst the most popular types in Python. We can create them
simply by enclosing characters in quotes. Python treats single quotes the
same as double quotes. Creating strings is as simple as assigning a value to
a variable. For example −
To access substrings, use the brackets for slicing along with the index or
indices to obtain your substring. For example −
#!/usr/bin/python
var1[0]: H
var2[1:5]: ytho
var2[:10]: Python Pro
Updating Strings
You can "update" an existing string by (re)assigning a variable to another
string. The new value can be related to its previous value or to a completely
different string altogether. You cannot update a character of a string. For
example −
var1 = 'ABC';
var1[2] = 'D'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.
\e 0x1b Escape
\f 0x0c Formfeed
\n 0x0a Newline
Calling Bell!
Open the door
\s 0x20 Space
\t 0x09 Tab
print('Hello''\t''World');
Hello World
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
print('Hello''\xad''World');
Hello-World
print('Hello''\xae''World');
Hello®World
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
a+b
'HelloPython'
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the a[1:4] will give ell
given range
'w' in var1
False
not in Membership - Returns true if a character does M not in a will give 1 (True)
not exist in the given string
'w' not in var1
True
r/R Raw String - Suppresses actual meaning of print r'\n' prints \n and print R'\n'prin
Escape characters. The syntax for raw strings is
exactly the same as for normal strings with the print('\n')
exception of the raw string operator, the letter
"r," which precedes the quotation marks. The "r"
print(r'\n')
can be lowercase (r) or uppercase (R) and must
\n
be placed immediately preceding the first quote
mark.
% Format - Performs String formatting v_num = 100;
print('v_num is: %d' %(v_num));
#!/usr/bin/python
print("Heavyweight boxer %s, total win %d/58" % ('Michael Gerard Tyson', 50));
Heavyweight boxer Michael Gerard Tyson, total win 50/58
Here is the list of complete set of symbols which can be used along with % −
%c Character
fname='Rakhee'
lname='Harlalka'
print("My name initial is %c%c and weight is %d kg!" %
(fname[0],lname[0], 65));
My name initial is RH and weight is 65 kg!
print('%s' % ('test',))
test
print('%10s' % ('test',))
test
%o octal integer
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
- left justification
print('%010d' %(+837.64));
0000000837
print('%+010d' %(837.64));
+000000837
print('%010d' %(-837.64));
-000000837
000000837
print("%#x" % 17 )
0x11
print("%#x" % 18 )
0x12
print("%x" % 17 )
11
print("%x" % 18 )
12
print('%10d' %(837.64));
837
print('%010d' %(837.64));
0000000837
print('%f' %(837.64759678));
837.647597
print('%.1f' %(837.64759678));
837.6
print('%.2f' %(837.64759678));
837.65
print('%.4f' %(837.64759678));
837.6476
print('%010.2f' %(837.64759678));
0000837.65
print('%010.4f' %(837.64759678));
00837.6476
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span
multiple lines, including verbatim NEWLINEs, TABs, and any other special
characters.
The syntax for triple quotes consists of three consecutive single or double
quotes.
When the above code is executed, it produces the following result. Note how
every single special character has been converted to its printed form, right
down to the last NEWLINE at the end of the string between the "up." and
closing triple quotes. Also note that NEWLINEs occur either with an explicit
carriage return at the end of a line or its escape code (\n) –
Raw strings do not treat the backslash as a special character at all. Every
character you put into a raw string stays the way you wrote it −
print('C:\\nowhere')
C:\nowhere
print(r'C:\\nowhere')
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode
strings are stored as 16-bit Unicode. This allows for a more varied set of
characters, including special characters from most languages in the world.
print(u'Hello, world!')
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the
prefix r.
1 capitalize()
Capitalizes first letter of string
print(vname.center(30,' '));
print(vname.center(30,' x '));
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
4
decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding.
5
encode(encoding='UTF-8',errors='strict')
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if
tabsize not provided.
10 isalnum()
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
12
isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false
otherwise.
15 isspace()
16
istitle()
17 isupper()
Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
18
join(seq)
19 len(string)
20
ljust(width[, fillchar])
21
lower()
22
lstrip()
Removes all leading whitespace in string.
23 maketrans()
24 max(str)
25 min(str)
27
rfind(str, beg=0,end=len(string))
28
rindex( str, beg=0, end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list
of substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with
NEWLINEs removed.
33
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending
index end are given) starts with substring str; returns true if so and false
otherwise.
34 strip([chars])
35
swapcase()
36
title()
Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.
37 translate(table, deletechars="")
39
zfill (width)
40
isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
Python Lists
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero,
the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are
lists and tuples, which we would see here.
There are certain things you can do with all sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership.
In addition, Python has built-in functions for finding the length of a sequence
and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written
as a list of comma-separated values (items) between brackets. Important
thing about a list is that items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the
left-hand side of the assignment operator, and you can add to elements in a
list with the append() method. For example −
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print (list[2])
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
1 cmp(list1, list2)
2 len(list)
3
max(list)
4
min(list)
5 list(seq)
1 list.append(obj)
2 list.count(obj)
3
list.extend(seq)
4
list.index(obj)
5
list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use parentheses, whereas lists use
brackets.
tup1 = ();
To write a tuple containing a single value you must include a comma, even
though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values
of tuple elements. You are able to take portions of existing tuples to create
new tuples as the following example demonstrates −
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples,
as indicated in these short examples −
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz'
x, y = 1, 2;
print "Value of x , y : ", x,y
1 cmp(tuple1, tuple2)
2 len(tuple)
4 min(tuple)
5 tuple(seq)
Python Dictionary
Each key is separated from its value by a colon (:), the items are separated
by commas, and the whole thing is enclosed in braces. An empty dictionary
without any items is written with just two braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in
the simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
dict['Age']: 8
dict['School']: DPS School
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because
after del dict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
(a) More than one entry per key not allowed. Which means no duplicate key
is allowed. When duplicate keys encountered during assignment, the last
assignment wins. For example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed. Following
is a simple example:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
3 str(dict)
4
type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then
it would return a dictionary type.
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
5
dict.has_key(key)
6 dict.items()
7
dict.keys()
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9
dict.update(dict2)
10 dict.values()
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular
instants in time are expressed in seconds since 12:00am, January 1, 1970.
Example
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks);
Date arithmetic is easy to do with ticks. However, dates before the epoch
cannot be represented in this form. Dates in the far future also cannot be
represented this way - the cutoff point is sometime in 2038 for UNIX and
Windows.
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as
shown below:
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print("Local current time :", localtime);
This would produce the following result, which could be formatted in any other
presentable form −
#!/usr/bin/python
import time;
localtime = time.asctime( time.localtime(time.time()) )
print("Local current time :", localtime)
#!/usr/bin/python
import calendar
cal = calendar.month(2017, 1)
print(cal)
January 2017
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
1 time.altzone
The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative
if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use
this if daylight is nonzero.
2 time.asctime([tupletime])
Accepts a time-tuple and returns as character readable 24-character string such as 'Tue Dec
11 18:07:14 2008'.
print(time.gmtime())
time.asctime(time.gmtime())
time.asctime(time.localtime())
3
time.clock( )
time.clock( )
2.1935462828870445
time.clock( )
4.097568009977395
time.clock( )
5.349900923483391
4 time.ctime([secs])
time.asctime(time.gmtime())
'Fri Oct 13 11:25:41 2017'
time.asctime(time.localtime())
'Fri Oct 13 16:57:43 2017'
time.ctime()
'Fri Oct 13 16:57:52 2017'
5
time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the
UTC time. Note : t.tm_isdst is always 0
time.gmtime()
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the
local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local
rules).
time.localtime()
7 time.mktime(tupletime)
The method mktime() is the inverse function of localtime(). Its argument is the
struct_time or full 9-tuple and it returns a floating point number, for compatibility
with time().
t =(2017,10,13,17,18,50,4,286,0);
time.mktime(t);
1507895330.0
time.mktime(time.localtime())
1507895862.0
8
time.sleep(secs)
time.sleep( 5 )
9
time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and returns a string representing
the instant as specified by string fmt.
Syntax
Following is the syntax for strftime() method:
time.strftime(format[, t])
Format elements
• %D - same as %m/%d/%y
• %h - same as %b
• %M - minute
• %n - newline character
• %S - second
• %t - tab character
• %U - week number of the current year, starting with the first Sunday as the first day
of the first week
• %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the
first week that has at least 4 days in the current year, and with Monday as the first
day of the week
• %W - week number of the current year, starting with the first Monday as the first day
of the first week
t =(2017,10,13,17,18,50,4,286,0);
t = time.mktime(t)
Parses str according to format string fmt and returns the instant in time-tuple format. The
method strptime() parses a string representing a time according to a format. The return
value is a struct_time as returned by gmtime() or localtime().
The format parameter uses the same directives as those used by strftime(); it defaults to
"%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
If string cannot be parsed according to format, or if it has excess data after parsing,
ValueError is raised.
Syntax
time.strptime(string[, format]
print(t)
11 time.time( )
Returns the current time instant, a floating-point number of seconds since the epoch.
time.time( )
1507904917.6235135
12 time.tzset()
Resets the time conversion rules used by the library routines. The environment variable TZ
specifies how this is done.
Availability: Unix.
There are following two important attributes available with time module:
1 time.timezone
Attribute time.timezone is the offset in seconds of the local time zone (without
DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).
time.timezone
-19800
2 time.tzname
time.tzname
('India Standard Time', 'India Daylight Time')
By default, calendar takes Monday as the first day of the week and Sunday
as the last one. To change this, call calendar.setfirstweekday() function.
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a multiline string with a calendar for year year formatted into three columns separated
by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l
is the number of lines for each week.
print(calendar.calendar(2017,w=1,l=1,c=1));
2017
2 calendar.firstweekday( )
Returns the current setting for the weekday that starts each week. By default, when calendar
is first imported, this is 0, meaning Monday.
calendar.firstweekday( )
0
3 calendar.isleap(year)
calendar.isleap(2016)
True
calendar.isleap(2017)
False
4 calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
calendar.leapdays(2000,2017)
5 calendar.month(year,month,w=2,l=1)
Returns a multiline string with a calendar for month month of year year, one line per week
plus two header lines. w is the width in characters of each date; each line has length 7*w+6.
l is the number of lines for each week.
print(calendar.month(2017,10,w=2,l=1))
October 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year
year are set to 0; days within the month are set to their day-of-month, 1 and up.
print(calendar.monthcalendar(2017,10))
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20,
21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 0, 0, 0, 0]]
7 calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the first day of the month
month in year; the second one is the number of days in the month. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 to 12.
>>> print(calendar.calendar(2017,w=1,l=1,c=1));
2017
calendar.monthrange(2017,1)
(6, 31)
calendar.monthrange(2017,2)
(2, 28)
calendar.monthrange(2017,3)
(2, 31)
calendar.monthrange(2017,4)
(5, 30)
calendar.monthrange(2017,5)
(0, 31)
calendar.monthrange(2017,6)
(3, 30)
8 calendar.prcal(year,w=2,l=1,c=6)
Like print(calendar.calendar(year,w,l,c));
calendar.prcal(2017,w=2,l=1,c=2)
2017
9 calendar.prmonth(year,month,w=2,l=1)
Like print(calendar.month(year,month,w=1,l=1));
print(calendar.month(2017,1,w=1,l=1));
January 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
calendar.prmonth(2017,1,w=2,l=1)
January 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to
6 (Sunday).
import calendar
calendar.firstweekday( )
0
calendar.setfirstweekday(calendar.SUNDAY);
calendar.firstweekday( )
6
11 calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same
instant as a floating-point number of seconds since the epoch.
import calendar
import time
import datetime
1509408000
time.mktime(d.timetuple())
1509388200.0
d = datetime.datetime(2017, 10, 31, 16, 30, 30)
calendar.timegm(d.timetuple())
1509467430
time.mktime(d.timetuple())
1509447630.0
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday);
month numbers are 1 (January) to 12 (December).
print(calendar.month(2017,10,w=2,l=1));
October 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
calendar.weekday(2017,10,3)
Function Description
# integer
print("int(123) is:", int(123))
# float
print("int(123.23) is:", int(123.23))
# string
print("int('123') is:", int('123'))
# binary 0b or 0B
# hexadecimal
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string. As Python
3 treats all integers as long integer this long() has been removed. (Python 3's
int is the same as Python 2's long). there is no distinction between long and int
in python3. (long does not exist...)
long('234')
234
float('12345')
12345.0
float('12345.55')
12345.55
(3+5j)
str(12)
'12'
str(99.99)
'99.99'
str('abc')
'abc'
user = "Dev"
lines = 50
print("Congratulations, " + user + "! You just wrote " + str(lines)
+ " lines of code.")
lines_yesterday = "50"
lines_today = "108"
print(lines_more)
58
repr(x) ▪ Converts object x to an expression string. repr() compute the “official”
string representation of an object (a representation that has all
information about the object) and str() is used to compute the “informal”
string representation of an object (a representation that is useful for
printing the object).
import datetime
today = datetime.datetime.now()
Output:
2016-02-22 19:32:04.078030
x = 1
eval('x+1')
In Python:
print(type(sea_creatures))
<class 'list'>
x = tuple(sea_creatures);
In Python:
print(type(sea_creatures));
<class 'tuple'>
x = list(sea_creatures);
print(x, '\t', type(x));
<class 'list'>
print(type(lang));
<class 'tuple'>
x = set(lang)
We can define sets (since Python2.6) without using the built-in set function. We
can use braces instead:
x = {"cheap","expensive","inexpensive","economical"}
x
{'economical', 'inexpensive', 'expensive', 'cheap'}
print(x,'\t',type(x))
{'economical', 'inexpensive', 'expensive', 'cheap'} <class 'set'>
Immutable Sets Sets are implemented in a way, which doesn't allow mutable objects. The
following example demonstrates that we can include tuples as elements in the
sets but cannot include multiple lists as elements (single list is allowed):
x = {"cheap","expensive","inexpensive","economical"}
print(cities)
{('Paris', 'Berlin', 'London'), ('Python', 'Perl')}
Though sets can't contain mutable objects (list), multiple lists are not allowed
single list is allowed, sets are mutable:
Frozensets are like sets except that they cannot be changed, i.e. they are
immutable:
cities.add("Rome")
colours = {"red","green"}
colours.add("yellow")
colours
colours.add("yellow")
colours
clear
colours.clear()
colours
set()
copy
cities = {"Delhi","Mumbai","Chennai","Kolkata"};
metro = cities.copy();
metro
difference()
This method returns the difference of two or more sets as a new set.
x = {"a","b","c","d","e"}
y = {"b","c"}
z = {"c","d"}
x.difference(y)
{'a', 'e', 'd'}
x.difference(y).difference(z)
{'a', 'e'}
Instead of using the method difference, we can use the operator "-":
x - y
{'a', 'e', 'd'}
x - y - z
{'a', 'e'}
difference_update()
The method difference_update removes all elements of another set from this
set. x.difference_update(y) is the same as "x = x - y"
x = {"a","b","c","d","e"}
y = {"b","c"}
x.difference_update(y)
x
x = {"a","b","c","d","e"}
y = {"b","c"}
x = x - y
x
{'a', 'e', 'd'}
discard(el)
x = {"a","b","c","d","e"}
x.discard("a")
x
{'c', 'b', 'e', 'd'}
x.discard("z")
x
{'c', 'b', 'e', 'd'}
x["b"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable
del x["b"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support item deletion
remove(el)
works like discard(), but if el is not a member of the set, a KeyError will be
raised.
x = {"a","b","c","d","e"}
x.remove("a")
x
{'c', 'b', 'e', 'd'}
x.remove("z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
union(s)
This method returns the union of two sets as a new set, i.e. all elements that
are in either set.
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
x.union(y)
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
x | y
intersection(s)
Returns the intersection of the instance set and the set s as a new set. In other
words: A set with all the elements which are contained in both sets is returned.
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
x.intersection(y)
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
x & y
isdisjoint()
x = {"a","b","c"}
y = {"c","d","e"}
x.isdisjoint(y)
False
x = {"a","b","c"}
y = {"d","e","f"}
x.isdisjoint(y)
True
issubset()
x = {"a","b","c","d","e"}
y = {"c","d"}
x.issubset(y)
False
y.issubset(x)
True
x < y
False
x <= x
True
issuperset()
x = {"a","b","c","d","e"}
y = {"c","d"}
x.issuperset(y)
True
x > y
True
x >= y
True
x >= x
True
x > x
False
x.issuperset(x)
True
pop()
pop() removes and returns an arbitrary set element. The method raises a
KeyError if the set is empty
x = {"a","b","c","d","e"}
x.pop()
'a'
x.pop()
'c'
x.pop()
'e'
x.pop()
'd'
x.pop()
'b'
x.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop from an empty set'
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
print(type(state_population))
<class 'dict'>
state_population["UP"]
199581477
state_population["MH"]
112372972
state_population["Punjab"] = 27704236;
state_population["Punjab"] = 27704236;
state_population
x = dict(t);
print(x, type(x))
{'a': 'Apple', 'b': 'Ball', 'c': 'Cat', 'd': 'Dog'} <class 'dict'>
{'a': 'Apple', 'b': 'Ball', 'c': 'Cat', 'd': 'Dog'} <class 'dict'>
y['a']
'Apple'
y['d']
'Dog'
z = dict(map(reversed, t));
print(z, type(z))
{'Apple': 'a', 'Ball': 'b', 'Cat': 'c', 'Dog': 'd'} <class 'dict'>
x=[('hi','goodbye')]
print(x,type(x));
y = dict(x);
print(y,type(y));
{'hi': 'goodbye'} <class 'dict'>
Character Values in ASCII
print(chr(97));
print(chr(65));
print(chr(90));
print(chr(1119));
print(chr(63))
a
A
Z
џ
?
print(unichr(1119));
ord(x) The ord() method returns an integer representing Unicode code point for the
given Unicode character.
print(ord('1'))
49
print(ord('5'))
53
print(ord('A'))
65
print(ord('Z'))
90
print(hex(110));
print(hex(111));
print(hex(112));
print(hex(113));
print(hex(114));
print(hex(115));
0x6e
0x6f
0x70
0x71
0x72
0x73
print(float.hex(2.5));
0x1.4000000000000p+1
print(float.hex(5.5));
0x1.6000000000000p+2
print(oct(555));
0o1053
print(oct(555.55));
Types of Operator
Python language supports the following types of operators.
• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
a = 10
b = 20
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is 9//2 = 4 and
the quotient in which the digits after the decimal point are 9.0//2.0 =
removed. But if one of the operands is negative, the result is 4.0, -11//3 =
floored, i.e., rounded away from zero (towards negative -4, -11.0//3
infinity): = -4.0
> 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 operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b)
right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value of (a <= b)
right operand, then condition becomes true. is true.
+= Add AND It adds right operand to the left operand and c += a is equivalent to
assign the result to left operand c=c+a
-= Subtract AND It subtracts right operand from the left c -= a is equivalent to
operand and assign the result to left operand c=c-a
/= Divide AND It divides left operand with the right operand c /= a is equivalent to
and assign the result to left operand c=c/a
//= Floor Division It performs floor division on operators and c //= a is equivalent to
assign value to the left operand (return c = c // a
quotient)
c=58;
c %=a;
print(c);
c=58;
c //=a;
print(c);
and Logical AND If both the operands are true then condition becomes true. (a and b) is
true.
or Logical OR If any of the two operands are non-zero then condition (a or b) is
becomes true. true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b)
is false.
Example.
x = True;
y = False;
print('x and y is ',x and y);
x and y is False
-----------------
& Binary AND Operator copies a bit to the result if it exists in (a & b) (means
both operands 0000 1100)
a = 60;
b = 13;
x = a&b;
print(x);
12
x = a|b;
print(x);
61
x = a^b;
print(x);
49
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61
Complement (means 1100
0011 in 2's
complement
form due to a
signed binary
number.
x = ~a;
print(x);
-61
<< Binary Left Shift The left operands value is moved left by the a << 2 = 240
number of bits specified by the right operand. (means 1111
0000)
x = a << 2 ;
print(x);
240
>> Binary Right Shift The left operands value is moved right by the a >> 2 = 15
number of bits specified by the right operand. (means 0000
1111)
x = a >> 2 ;
print(x);
15
not in Evaluates to true if it does not finds a variable x not in y, here not in results in a 1
in the specified sequence and false otherwise. if x is not a member of sequence y.
Example
a = 10
b = 20
l_num = [1, 2, 3, 4, 5 ];
if ( a in l_num ):
print("a is available in the given list");
else:
print("a is not available in the given list");
if ( b not in l_num ):
print("b is not available in the given list");
else:
print("b is available in the given list");
x = 2
if ( x in l_num ):
print("x is available in the given list");
else:
print("x is not available in the given list");
When you execute the above program it produces the following result:
print( a in l_num );
False
print( b in l_num );
False
x = 2
print( x in l_num );
True
(1) is
(2) is not.
is not Evaluates to false if the variables on either side x is not y, here is not results in
of the operator point to the same object and true 1 if id(x) is not equal to id(y).
otherwise.
Example
a = 20
b = 20
if ( a is b ):
print("Line 1 - a and b have same identity")
else:
print("Line 1 - a and b do not have same identity")
if ( id(a) == id(b) ):
print("Line 2 - a and b have same identity")
else:
print("Line 2 - a and b do not have same identity")
b = 30
if ( a is b ):
print("Line 3 - a and b have same identity")
else:
print("Line 3 - a and b do not have same identity")
if ( a is not b ):
print("Line 4 - a and b do not have same identity")
else:
print("Line 4 - a and b have same identity")
When you execute the above program it produces the following result −
a = 20
b = 20
id(a)
1539688720
id(b)
1539688720
a = 555
b = 555
id(a)
1390899932912
id(b)
1390901046000
a = 1000
b = 1000
id(a)
1390901046096
id(b)
1390899932912
a = 20
b = 20
id(a)
1539688720
id(b)
1539688720
id(1000)
1390899932912
b = 1000
id(b)
1390899930224
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@
and -@)
a = 20
b = 1000
-a
-20
+a
20
-b
-1000
+b
1000
~a
-21
~b
-1001
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom.
Example
a = 20
b = 10
c = 15
d = 5
e = 0
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 −
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
a if condition else b
1. True
False
2. 0 for False
1 for True
3. <condition expression>
Python programming language assumes any non-zero and non-null values
as TRUE, and if it is either zero or null, then it is assumed as FALSE value.
Statement Description
nested if statements You can use one if or else if statement inside another if or else
if statement(s).
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 most one statement, there can be an
arbitrary number of elif statements following an if.
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)
var1 = 5555
if var1:
print("1 – Condition evaluated true");
print(var1);
var2 = 0
if var2:
print("2 - Condition evaluated false");
print(var2);
else:
print("Good bye!");
v_marks = 85
if (v_marks<50) :
print("He is fail.");
print("He should work hard.");
elif (v_marks>=50 and v_marks<60) :
print("He stood 2nd."); print("He need improvements.");
elif (v_marks>=60 and v_marks<80) :
print("He stood 1st.");
else :
print("Outstanding.");
print("Well done.");
Good bye!
Outstanding.
Well done.
# Another Example
var = 100
if var < 200:
print("Expression value is less than 200");
if var == 150:
print("Which is 150");
elif var == 100:
print("Which is 100");
elif var == 50:
print("Which is 50");
elif var < 50:
print("Expression value is less than 50");
else:
print("Could not find true expression");
var = 100
if ( var == 100 ) : print "Value of expression is 100"
^
if ( var == 100 ) : print("Value of expression is 100"); print("hello");
else: print("good bye")
good bye
Python Loops
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.
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know beforehand, the number of times to
iterate.
Syntax
while test_expression:
Body of while
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
# Output
1
2
3
4
5
Good Bye While Loop
In Python, break and continue statements can alter the flow of a normal
loop. The break statement terminates the loop containing it and pass the
control of the program to the statement immediately after the body of the
loop.
If break statement is inside a nested loop (loop inside another loop), break
will terminate the innermost loop.
# Prints out 1,2,3,4,5
count = 1
while True:
print(count)
count += 1
if count > 5:
break
# Output
1
2
3
4
5
Good Bye While Loop
count = 1
while (count<=10):
if (count==5):
count=count+1
continue
else:
print(count)
count=count+1
# Output
1
2
3
4
6
7
8
9
10
When the loop condition of "for" or "while" statement fails then code part in
"else" is executed. If break statement is executed inside for loop then the
"else" part is skipped. Note that "else" part is executed even if there is a
continue statement.
# While loop with else.
# Print out 1,2,3,4,5 and then it prints "count value reached 5"
count=1
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Output
1
2
3
4
count value reached 5
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
Here, val is the variable that takes the value of the item inside the sequence on each
iteration. Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
for x in (1,2,3,4,5):
print(x)
# Output
1
2
3
4
5
for x in [1,2,3,4,5]:
print(x)
# Output
1
2
3
4
5
for x in ['a','b','c','d','e']:
print(x)
# Output
a
b
c
d
e
for x in range(5):
print(x)
# Output
0
1
2
3
4
# Output
3
4
5
# Output
3
5
7
9
# Output
1
3
5
7
9
# Output
1
2
3
4
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val;
else:
print("The sum is", sum);
# Output
The sum is 48
Syntax of pass
pass
As you already know, Python gives you many built-in functions like print(),
etc. but you can also create your own functions. These functions are
called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function_name and
parentheses ( ( ) ).
• The code block within every function starts with a colon (:) and is indented.
Syntax
def function_name(parameter1, parameter2, …parametern):
"""function_docstring"""
function_suite
return [expression]
def print_myname(str):
"This function prints your name."
print(str)
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. Following is the
example to call print_myname() function −
#!/usr/bin/python
# Function definition is here
def print_myname( str ):
"This function print your name."
print(str)
return;
Output:
Capgemini India
#!/usr/bin/python
# Function definition is here
def change_mylist(mylist):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
print(id(mylist))
# Now you can call change_mylist function by using a list variable mylist as
reference
v_list = [10,20,30];
print("Values before passing in the function: ", v_list)
change_mylist( v_list );
print("Values after passing in the function: ", v_list)
There is one more example where argument is being passed by reference and
the reference is being overwritten inside the called function.
#!/usr/bin/python
Function Arguments
You can call a function by using the following types of formal arguments:
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
#!/usr/bin/python
# Function definition is here
def print_myname(str):
"This prints a passed string into this function"
print(str);
return;
# Now you can call print_myname function
print_myname()
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.
You can also make keyword calls to the print_myname() function in the
following ways −
#!/usr/bin/python
# Function definition is here
def print_myname(str):
"This prints a passed string into this function"
print(str)
return;
# Now you can call print_myname function
print_myname( str = "Michael Gerard Tyson")
#!/usr/bin/python
# Function definition is here
def personal_info(name,age):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;
Default arguments
A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument. The following example
gives an idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
An asterisk (*) is placed before the variable name that holds the values of all
non keyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple
example −
#!/usr/bin/python
# Function definition is here
def student_marks( name, *score_tuple ):
"This prints a variable length passed arguments"
print("Student subject details is: ")
print(type(score_tuple))
print("Student name ",name)
student_marks("Dev Singh")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: student_marks() missing 1 required keyword-only argument: 'name'
student_marks(name="Dev Singh")
Student subject details is:
Dev Singh
• Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is bypassing
function stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as
follows −
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
Value of total : 30
Value of total : 40
it_rate10 = lambda arg1: (arg1*10)/100;
it_rate20 = lambda arg1: (arg1*20)/100;
it_rate30 = lambda arg1: (arg1*30)/100;
it_rate10(300000)
30000.0
it_rate20(600000)
120000.0
it_rate30(2000000)
600000.0
All the above examples are not returning any value. You can return a value
from a function as follows −
#!/usr/bin/python
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in
Python:
• Global variables
• Local variables
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope. Following is a simple
example −
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
print(id(total))
return total;
# Now you can call sum function
print(sum(10, 20))
print("Outside the function global total : ", total)
We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
Example
Let’s create a module. Type the following and save it as example.py.
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
>>> example.add(50,45.5);
95.5
Using the module name we can access the function using dot (.) operation.
A module is loaded only once, regardless of the number of times it is
imported.
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
>>> from example import sub
>>> sub(50,45.5);
4.5
>>> add(50,45.5);
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'add' is not defined
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
>>> example._income_tax(400000,10)
Your tax is Rs :
40000.0
>>> exit()
This import all object definition except those beginning with an underscore
(private objects), visible in our scope. Objects are access without dot operator
(.)
C:\Users\haryadav>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
>>> add(50,45.5);
95.5
>>> sub(50,45.5);
4.5
>>> _income_tax(400000,10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_income_tax' is not defined
Importing everything with the asterisk (*) symbol is not a good programming
practice. This can lead to duplicate definitions for an identifier.
Locating Modules
When you import a module, the Python interpreter searches for the module
in the following sequences −
• The current directory.
• If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory, PYTHONPATH,
and the installation-dependent default.
>>> sys.path
['', 'C:\\Program Files\\Python36\\python36.zip', 'C:\\Program
Files\\Python36\\DLLs', 'C:\\Program Files\\Python36\\lib',
'C:\\Program Files\\Python36', 'C:\\Program
Files\\Python36\\lib\\site-packages']
C:\Users\haryadav>echo %PATH%
C:\Program Files\Python36\Scripts\;C:\Program
Files\Python36\;C:\Program Files\Teradata\Client\15.10\bin;C:\Program
Files
(x86)\Teradata\Client\15.10\bin;C:\app\haryadav\product\11.2.0\dbhome_
1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDO
WS\System32\WindowsPowerShell\v1.0\;C:\Program Files
(x86)\QuickTime\QTSystem\;C:\Program Files\CapgeminiScripts\Support
Tools\;C:\Program Files (x86)\Microsoft SQL
Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL
Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL
Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL
Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files
(x86)\Microsoft Visual Studio
9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft
SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL
Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL
Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL
Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
Server\110\Tools\Binn\ManagementStudio\;C:\Program Files
(x86)\Microsoft Visual Studio
10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft
SQL
Server\110\DTS\Binn\;C:\Users\haryadav\AppData\Local\Microsoft\Windows
Apps;
import sys
sys.builtin_module_names
For example, we define a variable Money in the global namespace. Within the
function AddMoney, we assign Money a value, therefore Python
assumes Money as a local variable.
#!/usr/bin/python
Money = 2000
def AddMoney():
# local variable Money is referenced before assignment. It will throw error.
Money = Money + 1
return Money
print(Money)
2000
AddMoney()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in AddMoney
UnboundLocalError: local variable 'Money' referenced before assignment
def AddMoney():
# local variable Money is assigned:
Money = 5000
Money = Money + 1
return Money
AddMoney()
5001
print(Money)
2000
def AddMoney():
# Here global variable Money is referenced using global keyword
# local variable Money is commented
global Money
# Money = 5000
Money = Money + 1
return Money
AddMoney()
2001
print(Money)
2001
The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
The list contains the names of all the modules, variables and functions that
are defined in a module.
#!/usr/bin/python
Add the following lines in the example module which you defined in previous exercise.
import example
content = dir(example)
print(content)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '_income_tax', 'add', 'g_result',
'g_score', 'sub']
type(content)
<class 'list'>
If locals() is called from within a function, it will return all the names that can
be accessed locally from that function.
If globals() is called from within a function, it will return all the names that
can be accessed globally from that function.
g_result = 0
g_score = 0
def currency():
Rupees = 5000
Usd = 5000
Euro= 5000
Ruble=5000
v_result = Rupees + Usd + Euro + Ruble
print('Local variables are : ', '\n', locals() )
print('Global variables are : ', '\n', globals())
return v_result
currency()
Local variables are :
{'v_result': 20000, 'Ruble': 5000, 'Euro': 5000, 'Usd': 5000, 'Rupees': 5000}
The return type of both these functions is dictionary. Therefore, names can
be extracted using the keys() function.
def currency():
Rupees = 5000
Usd = 5000
Euro= 5000
Ruble=5000
v_result = Rupees + Usd + Euro + Ruble
print('Local variables are : ', '\n', locals() )
dict = locals()
print(dict.keys())
print(dict.values())
return v_result
currency()
Local variables are :
{'v_result': 20000, 'Ruble': 5000, 'Euro': 5000, 'Usd': 5000, 'Rupees': 5000}
dict_keys(['v_result', 'Ruble', 'Euro', 'Usd', 'Rupees'])
dict_values([20000, 5000, 5000, 5000, 5000])
20000
Therefore, if you want to re execute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously
imported module again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not
the string containing the module name. For example, to reload hello module,
do the following −
reload(hello)
reload(example)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'reload' is not defined
import example
import importlib
importlib.reload(example)
<module 'example' from 'C:\\Program Files\\Python36\\example.py'>
For Python2.x:
reload(example)
Packages in Python
A bundle of multiple modules together form a package.
Create a Phone directory where your package will be stored as shown below
:-
C:\Users\haryadav>cd ..
C:\Users>cd ..
C:\Program Files\Python36\Phone>
C:\Program Files\Python36\Phone>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
Create a file Basicphone.py available in Phone directory. This file has
following line of source code −
def Basicphone():
print("This is Basic Phone")
Similar way, we have another two files having different functions as shown
below :−
def Isdnphone():
print("This is ISDN Phone")
def IPphone():
print("This is IP Phone")
Phone/__init__.py
To make all of your functions available when you've imported Phone, you
need to put explicit import statements in __init__.py as follows −
After you add these lines to __init__.py, you have all of these functions
available when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Basicphone()
Phone.Isdnphone()
Phone.IPphone()
#!/usr/bin/python
print("Python is really a great language,", "it is very interesting?")
• input
#!/usr/bin/python
str = raw_input("Enter your input: ");
print("Received input is : ", str)
This prompts you to enter any string and it would display same string on the
screen. When I typed "Hello Python!", its output is like this −
#!/usr/bin/python
str = input("Enter your input: ");
print("Received input is : ", str)
This would produce the following result against the entered input –
Result is : 300
Syntax
file_object = open(file_name [, access_mode][, buffering])
• file_name: The file_name argument is a string value that contains the name of
the file that you want to access.
• access_mode: The access_mode determines the mode in which the file has to
be opened, i.e. read, write, append etc. A complete list of possible values is
given below in the table. This is optional parameter and the default file access
mode is read (r).
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at
the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer is placed at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and
writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end
of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.
Attribute Description
Example
#!/usr/bin/python
# Open a file
v_file = open("resume.txt", "w")
print("Name of the file: ", v_file.name)
print("Closed or not : ", v_file.closed)
print("Opening mode : ", v_file.mode)
v_file.close()
C:\Users\haryadav>cd ..
C:\Users>cd ..
C:\Program Files\Python36\fileIO>
C:\Program Files\Python36\fileIO>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Welcome to Python!
Hari Yadav
v_file = open("resume.txt", "wb")
print("Name of the file: ", v_file.name)
print("Closed or not : ", v_file.closed)
print("Open mode of the file : ", v_file.mode)
v_file.close()
print("File closed : ", v_file.closed)
We create a file object using open() function and get a list of all possible
methods that can be used with a file object, using Python built-in dir()
function. The dir() function accepts a Python object as an argument and
returns a list of attributes and methods related to them.
dir(v_file)
Syntax
fileObject.close();
Example
#!/usr/bin/python
# Open a file
v_file = open("resume.txt", "wb")
print("Name of the file: ", v_file.name)
The write() method does not add a newline character ('\n') to the end of the
string. You have to do it explicitly.
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
v_file = open("resume.txt", "w")
print("Open mode of the file : ", v_file.mode)
v_file.write( "Python is a great language.\nYeah its great!!\n");
The above method would create resume.txt file and would write given
content in that file and finally it would close that file. If you would open this
file, it would have following content.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened
file. This method starts reading from the beginning of the file and if count is
missing, then it tries to read as much as possible, maybe until the end of file.
Example
Let's read the data from our file resume.txt, which we created above.
#!/usr/bin/python
# Open a file
v_file = open("resume.txt", "r+")
str = v_file.read(10);
print("Read String is : ", str)
str = v_file.read();
print("Read String is : ", str)
2 means at the end of the file would be taken as the reference position.
Example
#!/usr/bin/python
# Open a file
v_file = open("resume.txt", "r+")
str = v_file.read(10);
print("Read String is : ", str)
To use this module you need to import it first and then you can call any
related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file resume.txt:
#!/usr/bin/python
import os
os.rename("New_Resume.txt","resume.txt")
copyfile("New_Resume_1.txt","New_Resume_2.txt")
New_Resume_2.txt'
Syntax
os.remove(file_name)
Example
#!/usr/bin/python
import os
os.remove("New_Resume_2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create,
remove, and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which
contains the name of the directory to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os
os.mkdir("fileIO_1")
os.mkdir("fileIO_2")
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir('C:\\Program Files\\Python36\\fileIO\\fileIO_1')
os.getcwd()
'C:\\Program Files\\Python36\\fileIO\\fileIO_1'
os.chdir('C:\\Program Files\\Python36\\fileIO')
os.getcwd()
'C:\\Program Files\\Python36\\fileIO'
Syntax
os.getcwd()
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
Syntax:
os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to
give fully qualified name of the directory, otherwise it would search for that
directory in the current directory.
#!/usr/bin/python
import os
os.listdir()
['fileIO_1', 'fileIO_2', 'New_Resume_1.txt', 'resume.txt']
os.rmdir("fileIO_1")
os.rmdir('C:\\Program Files\\Python36\\fileIO\\fileIO_2')
os.listdir()
['New_Resume_1.txt', 'resume.txt']
File Object Methods: The file object provides functions to manipulate files.
A file object is created using open function and here is a list of functions
which can be called on this object:
1 file.close()
Close the file. A closed file cannot be read or written any more.
2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on some
file-like objects.
3 file.fileno()
5 file.next()
Returns the next line from the file each time it is being called.
6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).
7 file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in
the string.
8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If
the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding
up to an internal buffer size) are read.
9 file.seek(offset[, whence])
10 file.tell()
11 file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file
is truncated to (at most) that size.
12 file.write(str)
13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable
object producing strings, typically a list of strings.
1 os.access(path, mode)
2 os.chdir(path)
3 os.chflags(path, flags)
4 os.chmod(path, mode)
Change the owner and group id of path to the numeric uid and gid.
6 os.chroot(path)
7 os.close(fd)
8 os.closerange(fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive),
ignoring errors.
9 os.dup(fd)
10 os.dup2(fd, fd2)
11 os.fchdir(fd)
12 os.fchmod(fd, mode)
Change the owner and group id of the file given by fd to the numeric uid
and gid.
14 os.fdatasync(fd)
16 os.fpathconf(fd, name)
17 os.fstat(fd)
18 os.fstatvfs(fd)
Return information about the filesystem containing the file associated with
file descriptor fd, like statvfs().
19 os.fsync(fd)
20 os.ftruncate(fd, length)
21 os.getcwd()
22 os.getcwdu()
23 os.isatty(fd)
24 os.lchflags(path, flags)
Set the flags of path to the numeric flags, like chflags(), but do not follow
symbolic links.
25 os.lchmod(path, mode)
Change the owner and group id of path to the numeric uid and gid. This
function will not follow symbolic links.
27 os.link(src, dst)
Return a list containing the names of the entries in the directory given by
path.
30 os.lstat(path)
31 os.major(device)
32 os.makedev(major, minor)
Compose a raw device number from the major and minor device numbers.
33 os.makedirs(path[, mode])
34 os.minor(device)
35 os.mkdir(path[, mode])
36 os.mkfifo(path[, mode])
Create a FIFO (a named pipe) named path with numeric mode mode. The
default mode is 0666 (octal).
Create a filesystem node (file, device special file or named pipe) named
filename.
38 os.open(file, flags[, mode])
Open the file file and set various flags according to flags and possibly its
mode according to mode.
39 os.openpty()
40 os.pathconf(path, name)
41 os.pipe()
Create a pipe. Return a pair of file descriptors (r, w) usable for reading
and writing, respectively.
43 os.read(fd, n)
Read at most n bytes from file descriptor fd. Return a string containing
the bytes read. If the end of the file referred to by fd has been reached,
an empty string is returned.
44 os.readlink(path)
Return a string representing the path to which the symbolic link points.
45 os.remove(path)
46 os.removedirs(path)
47 os.rename(src, dst)
49 os.rmdir(path)
50 os.stat(path)
51 os.stat_float_times([newvalue])
52 os.statvfs(path)
53 os.symlink(src, dst)
54 os.tcgetpgrp(fd)
Return the process group associated with the terminal given by fd (an
open file descriptor as returned by open()).
55 os.tcsetpgrp(fd, pg)
Set the process group associated with the terminal given by fd (an open
file descriptor as returned by open()) to pg.
56 os.tempnam([dir[, prefix]])
57 os.tmpfile()
58 os.tmpnam()
Return a unique path name that is reasonable for creating a temporary
file.
59 os.ttyname(fd)
Return a string which specifies the terminal device associated with file
descriptor fd. If fd is not associated with a terminal device, an exception
is raised.
60 os.unlink(path)
61 os.utime(path, times)
Set the access and modified times of the file specified by path.
Generate the file names in a directory tree by walking the tree either top-
down or bottom-up.
63 os.write(fd, str)
Write the string str to file descriptor fd. Return the number of bytes
actually written.
Python Exceptions Handling
Python provides two very important features to handle any unexpected error
in your Python programs and to add debugging capabilities in them −
• Exception Handling:
• Assertions:
StopIteration Raised when the next() method of an iterator does not point to any
object.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric
types.
EOFError Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+C.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but
no value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
IOError Raised when an input/ output operation fails, such as the print statement
or the open() function when trying to open a file that does not exist.
IOError
Raised for operating system-related errors.
SystemError Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function.
If not handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the
specified data type.
ValueError Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are
done with your testing of the program.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
Example 1.
Here is a function that converts a temperature from degrees Celsius to
Fahrenheit. Since zero degrees celsius is as cold as it gets, the function bails
out if it sees a negative temperature
#!/usr/bin/python
def CelsiusToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return (Temperature * 1.8)+32
print(CelsiusToFahrenheit(37))
print(int(CelsiusToFahrenheit(37)))
print(CelsiusToFahrenheit (-5))
print(CelsiusToFahrenheit(37))
98.60000000000001
print(int(CelsiusToFahrenheit(37)))
98
print(CelsiusToFahrenheit (-5))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in CelsiusToFahrenheit
AssertionError: Colder than absolute zero!
Example 2.
def value_comparison_f():
return 3
def test_value_comparison_f():
# argument not specified
assert value_comparison_f() == 4
test_value_comparison_f()
def test_set_comparison():
set1 = set("12345")
set2 = set("678910")
assert (set1 == set2), "Set elements should match."
test_set_comparison()
What is Exception?
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general, when
a Python script encounters a situation that it cannot cope with, it raises an
exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block. After the
try: block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
• A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's
protection.
Example
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all:
#!/usr/bin/python
try:
fh = open("testfile.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
C:\Program Files\Python36\fileIO>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
Hari Yadav
Welcome to python
try:
fh = open("testfile.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
try:
fh = open("testfile.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
try:
v_num =100/0
except:
print("Unknown error. Please check your program carefully.")
try:
fh = open("testfile.txt", "w")
# v_num =100/0
except:
print("Unknown error. Please check your program carefully.")
This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good
programming practice though, because it catches all exceptions but does not
make the programmer identify the root cause of the problem that may occur.
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
# f = open("dev_resume.txt")
name = input("Enter your name : ")
except (KeyboardInterrupt, FileNotFoundError, PermissionError):
print("\nPlease try again.")
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print("Error: can\'t find file or read data")
If you do not have permission to open the file in writing mode, then this will
produce the following result:
#!/usr/bin/python
try:
fh = open("testfile.txt", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print("Going to close the file")
fh.close()
except IOError:
print("Error: can\'t find file or read data")
Argument of an Exception
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by
exception. You capture an exception's argument by supplying a variable in
the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are trapping
multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause
of the exception. The variable can receive a single value or multiple values in
the form of a tuple. This tuple usually contains the error string, the error
number, and an error location.
Example
Following is an example for a single exception −
#!/usr/bin/python
Raising an Exception
You can raise exceptions in several ways by using the raise statement. The
general syntax for the raise statement is as follows.
Syntax
raise [Exception [, args [, traceback]]]
The final argument, traceback, is also optional (and rarely used in practice),
and if present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that
the Python core raises are classes, with an argument that is an instance of
the class. Defining new exceptions is quite easy and can be done as follows
−
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is
subclassed from RuntimeError. This is useful when you need to display more
specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror as e:
print e.args
• Data member − A class variable or instance variable that holds data associated
with a class and its objects.
• Instance variable − A variable that is defined inside a method and belongs only
to the current instance of a class.
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
class_suite
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
• The variable empCount is a class variable whose value is shared among all the
instances in this class. This can be accessed as Employee.empCount from
inside the class or outside the class.
• You declare other class methods like normal functions with the exception that the
first argument to each method is self. Python adds the self argument to the list
for you; you do not need to include it when you call the methods.
emp1.displayEmployee()
emp2.displayEmployee()
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
emp1.displayEmployee()
emp2.displayEmployee()
emp1.displayEmployee()
Name : Zara , Salary: 2000
emp1.displayEmployee()
Name : Mark Tully , Salary: 7000
emp1.displayEmployee()
Name : Mark Tully , Salary: 7000
emp1.displayEmployee()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in displayEmployee
AttributeError: 'Employee' object has no attribute 'salary'
emp2.displayEmployee()
Name : Manni , Salary: 5000
Instead of using the normal statements to access attributes, you can use the
following functions −
False
True
True
50
7000
• __bases__ − A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
For the above class let us try to access all these attributes:
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
You normally will not notice when the garbage collector destroys an orphaned
instance and reclaims its space. However, a class can implement the special
method __del__(), called a destructor, that is invoked when the instance is
about to be destroyed. This method might be used to clean up any non-
memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −
#!/usr/bin/python3
class Point:
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3)); # prints the ids of the obejcts
del pt1
del pt2
del pt3
Note − Ideally, you should define your classes in a separate file, then you
should import them in your main program file using import statement.
#!/usr/bin/python3
import point
p1 = point.Point()
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a
pre-existing class by listing the parent class in parentheses after the new
class name.
The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class. A child class can
also override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −
class_suite
Example
#!/usr/bin/python3
parentAttr = 100
def __init__(self):
def parentMethod(self):
Parent.parentAttr = attr
def getAttr(self):
def __init__(self):
def getAttr(self):
In a similar way, you can drive a class from multiple parent classes as follows
−
.....
.....
.....
Example
#!/usr/bin/python3
def myMethod(self):
def myMethod(self):
__del__( self )
2
Destructor, deletes an object
Sample Call : del obj
__repr__( self )
__str__( self )
__cmp__ ( self, x )
5 Object comparison
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional
vectors. What happens when you use the plus operator to add them? Most
likely Python will yell at you.
You could, however, define the __add__ method in your class to perform
vector addition and then the plus operator would behave as per expectation
−
Example
#!/usr/bin/python3
class Vector:
self.a = a
self.b = b
def __str__(self):
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)
Data Hiding
An object's attributes may or may not be visible outside the class definition.
You need to name attributes with a double underscore prefix, and those
attributes then will not be directly visible to outsiders.
Example
#!/usr/bin/python3
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)
.........................
print (counter._JustCounter__secretCount)
a, X, 9, <
1
ordinary characters just match themselves exactly.
. (a period)
2
matches any single character except newline '\n'
\w
3
matches a "word" character: a letter or digit or underbar [a-zA-Z0-9_].
\W
4
matches any non-word character.
\b
5
boundary between word and non-word
\s
6
matches a single whitespace character -- space, newline, return, tab
\S
7
matches any non-whitespace character.
\t, \n, \r
8
tab, newline, return
\d
9
decimal digit [0-9]
^
10
matches start of the string
$
11
match the end of the string
\
12
inhibit the "specialness" of a character.
Compilation flags
Compilation flags let you modify some aspects of how regular expressions
work. Flags are available in the re module under two names, a long name
such as IGNORECASE and a short, one-letter form such as I.
ASCII, A
1
Makes several escapes like \w, \b, \s and \d match only on ASCII
characters with the respective property.
DOTALL, S
2
Make, match any character, including newlines
IGNORECASE, I
3
Do case-insensitive matches
LOCALE, L
4
Do a locale-aware match
MULTILINE, M
5
Multi-line matching, affecting ^ and $
pattern
1
This is the regular expression to be matched.
string
2
This is the string, which would be searched to match the pattern at the
beginning of string.
flags
3
You can specify different flags using bitwise OR (|). These are modifiers,
which are listed in the table below.
group(num = 0)
1
This method returns entire match (or specific subgroup num)
groups()
2
This method returns all matching subgroups in a tuple (empty if there
weren't any)
Example 1.
#!/usr/bin/python3
import re
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")
# Sample strings.
list = ["dog dot", "do don't", "dumb-dumb", "no match"]
# Loop.
for element in list:
# Match if two words starting with letter d.
m = re.match("(d\w+)\W(d\w+)", element)
# See if success.
if m:
print(m.groups())
d Lowercase letter d.
\w+ One or more word characters.
\W A non-word character.
('dog', 'dot')
('do', 'don')
('dumb', 'dumb')
Example 3.
# Sample strings.
list = ["dog dot", "do don't", "dumb-dumb", "no match"]
# Loop.
for element in list:
# Match if two words starting with letter n and m.
m = re.match("(n\w+)\W(m\w+)", element)
# See if success.
if m:
print(m.groups())
Search scans through the input string and tries to match at any location.
pattern
1
This is the regular expression to be matched.
string
2
This is the string, which would be searched to match the pattern anywhere
in the string.
flags
3
You can specify different flags using bitwise OR (|). These are modifiers,
which are listed in the table below.
group(num = 0)
1
This method returns entire match (or specific subgroup num)
groups()
Example 2.
#!/usr/bin/python3
import re
# Input.
value = "voorheesville"
m = re.search("(vi.*)", value)
if m:
# This is reached.
print("search:", m.group(1))
m = re.match("(vi.*)", value)
if m:
# This is not reached.
print("match:", m.group(1))
Pattern: (vi.*)
Output
search: ville
Matching Versus Searching
Python offers two different primitive operations based on regular
expressions: match checks for a match only at the beginning of the string,
while search checks for a match anywhere in the string.
Example
#!/usr/bin/python3
import re
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl,
substituting all occurrences unless max is provided. This method returns
modified string.
Example
#!/usr/bin/python3
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print ("Phone Num : ", num)
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print ("Phone Num : ", num)
Syntax
re.split(pattern, string)
Example 1.
#!/usr/bin/python3
import re
# Input string.
value = "one 1 two 2 three 3"
# Print results.
for element in result:
print(element)
Pattern: \D+
import re
# Input string.
value = "DogCatElephant"
Cat
Elephant
Syntax
re.findall(pattern, string[, pos[, endpos]])
We scan a string for all words starting with the letter d or p, and with one or
more following word characters.
Example 1.
import re
# Input.
value = "abc 123 def 456 dot map pat"
Pattern: [dp]\w+
Syntax
re.findall(pattern, string[, pos[, endpos]])
We loop over a list of strings and call re.match. We detect all the strings that
start or end with a digit character "\d."
Tip:
The match method tests from the leftmost part of the string. So to test the
end, we use ".*" to handle these initial characters.
Example 1.
import re
Pattern details
START: 123
END: 123
START: 4cat
END: dog5
START: 6mouse
re.I
1
Performs case-insensitive matching.
re.L
re.M
3
Makes $ match the end of a line (not just the end of the string) and makes
^ match the start of any line (not just the start of the string).
re.S
4
Makes a period (dot) match any character, including a newline.
re.U
5
Interprets letters according to the Unicode character set. This flag affects
the behavior of \w, \W, \b, \B.
re.X
The following table lists the regular expression syntax that is available in
Python −
Here is the list of regular expression syntax in Python.
python
1
Match "python".
Character classes
S.No. Example & Description
[Pp]ython
1
Match "Python" or "python"
rub[ye]
2
Match "ruby" or "rube"
[aeiou]
3
Match any one lowercase vowel
[0-9]
4
Match any digit; same as [0123456789]
5 [a-z]
Match any lowercase ASCII letter
[A-Z]
6
Match any uppercase ASCII letter
[a-zA-Z0-9]
7
Match any of the above
[^aeiou]
8
Match anything other than a lowercase vowel
[^0-9]
9
Match anything other than a digit
.
1
Match any character except newline
\d
2
Match a digit: [0-9]
\D
3
Match a nondigit: [^0-9]
\s
4
Match a whitespace character: [ \t\r\n\f]
\S
5
Match nonwhitespace: [^ \t\r\n\f]
\w
6
Match a single word character: [A-Za-z0-9_]
\W
7
Match a nonword character: [^A-Za-z0-9_]
Repetition Cases
S.No. Example & Description
ruby?
1
Match "rub" or "ruby": the y is optional
ruby*
2
Match "rub" plus 0 or more ys
ruby+
3
Match "rub" plus 1 or more ys
\d{3}
4
Match exactly 3 digits
\d{3,}
5
Match 3 or more digits
\d{3,5}
6
Match 3, 4, or 5 digits
Nongreedy repetition
This matches the smallest number of repetitions −
S.No. Example & Description
<.*>
1
Greedy repetition: matches "<python>perl>"
<.*?>
2
Nongreedy: matches "<python>" in "<python>perl>"
\D\d+
1
No group: + repeats \d
(\D\d)+
2
Grouped: + repeats \D\d pair
([Pp]ython(,)?)+
3
Match "Python", "Python, python, python", etc.
Backreferences
This matches a previously matched group again −
([Pp])ython&\1ails
1
Match python&pails or Python&Pails
(['"])[^\1]*\1
2
Single or double-quoted string. \1 matches whatever the 1st group
matched. \2 matches whatever the 2nd group matched, etc.
Alternatives
S.No. Example & Description
python|perl
1
Match "python" or "perl"
rub(y|le)
2
Match "ruby" or "ruble"
Python(!+|\?)
3
"Python" followed by one or more ! or one ?
Anchors
This needs to specify match position.
^Python
1
Match "Python" at the start of a string or internal line
Python$
2
Match "Python" at the end of a string or line
\APython
3
Match "Python" at the start of a string
Python\Z
4
Match "Python" at the end of a string
\bPython\b
5
Match "Python" at a word boundary
\brub\B
6
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!)
7
Match "Python", if followed by an exclamation point.
Python(?!!)
8
Match "Python", if not followed by an exclamation point.
R(?#comment)
1
Matches "R". All the rest is a comment
R(?i)uby
2
Case-insensitive while matching "uby"
R(?i:uby)
3
Same as above
rub(?:y|le))
4
Group only without creating \1 backreference