Python Programming Notes (1) - Booklet
Python Programming Notes (1) - Booklet
>>> student.write()
2) Writing first program:
Student
136 1
Statement2
Statement3
# Script Ends
Differences between scripting language and programming language:
• If a file named init .py is present in a package directory, it is invoked when the
package or a module in the package is imported. This can be used for execution of
package initialization code, such as initialization of package-level data.
• For example init .py
• A module in the package can access the global by importing it in turn
• We can import modules from packages using the dot (.) operator.
• For example, if want to import the start module in the above example, it is done as
Why to use Python: follows.
The following are the primary factors to use python in day-to-day life: • import Game.Level.start
1. Python is object-oriented • Now if this module contains a function named select_difficulty(), we must use the
Structure supports such concepts as polymorphism, operation overloading and full name to reference it.
multiple inheritance. • Game.Level.start.select_difficulty(2)
2. Indentation
Indentation is one of the greatest feature in python
2 135
>>> from math import pi, e 3. It’s free (open source)
Downloading python and installing python is free and easy
>>> pi
4. It’s Powerful
3.141592653589793 Dynamic typing
Built-in types and tools
>>> e
Library utilities
2.718281828459045 Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
Import all names:
5. It’s Portable
• We can import all names(definitions) from a module using the following construct. Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python
>>>from math import *
programs will run in exactly the same manner, irrespective of platform.
>>>print("The value of pi is", pi) 6. It’s easy to use and learn
No intermediate compile
• We imported all the definitions from the math module. This makes all names except
Python Programs are compiled automatically to an intermediate form called
those beginnig with an underscore, visible in our scope.
byte code, which the interpreter then reads.
Explore packages: This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
• We don't usually store all of our files in our computer in the same location. We use a
Structure and syntax are pretty intuitive and easy to grasp.
well-organized hierarchy of directories for easier access.
7. Interpreted Language
• Similar files are kept in the same directory, for example, we may keep all the songs in Python is processed at runtime by python Interpreter
the "music" directory. Analogous to this, Python has packages for directories 8. Interactive Programming Language
and modules for files. Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
• As our application program grows larger in size with a lot of modules, we place
The formation of python syntax is simple and straight forward which also makes it
similar modules in one package and different modules in different packages. This
popular.
makes a project (program) easy to manage and conceptually clear.
Installation:
• Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules. There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
• A directory must contain a file named init .py in order for Python to consider it as
from http://python.org/downloads/
a package. This file can be left empty but we generally place the initialization code for
Steps to be followed and remembered:
that package in this file. Step 1: Select Version of Python to Install.
• Here is an example. Suppose we are developing a game, one possible organization of Step 2: Download Python Executable Installer.
packages and modules could be as shown in the figure below. Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
134 3
Step 5: Verify Pip Was Installed. C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m.py =
Step 6: Add Python Path to Environment Variables (Optional)
Enter radius:4
Area of circle is: 50.26548245743669
>>> import math
>>> print("The value of pi is", math.pi)
O/P: The value of pi is 3.141592653589793
Import with renaming:
• We can import a module by renaming it as follows.
• For Eg:
>>> import math as m
>>> print("The value of pi is", m.pi)
Working with Python O/P: The value of pi is 3.141592653589793
Python Code Execution:
Python’s traditional runtime execution model: Source code you type is translated to byte • We have renamed the math module as m. This can save us typing time in some cases.
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted. • Note that the name math is not recognized in our scope. Hence, math.pi is
invalid, m.pi is the correct implementation.
Source Byte code Runtime
Python from...import statement:
PVM • We can import specific names from a module without importing the module as a
m.py m.pyc
whole. Here is an example.
>>> from math import pi
Source code extension is .py >>> print("The value of pi is", pi)
Byte code extension is .pyc (Compiled python code)
O/P: The value of pi is 3.141592653589793
There are two modes for using the Python interpreter: • We imported only the attribute pi from the module.
• Interactive Mode • In such case we don't use the dot operator. We could have imported multiple attributes
• Script Mode as follows.
4 133
Running Python in interactive mode:
Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
hello world
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
math module:
# write a python program which accepts the radius of a circle from user and computes
the area.
import math
r=int(input("Enter radius:")) The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter
area=math.pi*r*r replies 8.
print("Area of circle is:",area) Running Python in script mode:
Output:
132 5
Alternatively, programmers can store Python script source code in a file with #write a python program to display a particular month of a year using calendar
the .py extension, and use the interpreter to execute the contents of the file. To execute the module.
script by the interpreter, you have to tell the interpreter the name of the file. For example, if
import calendar
you have a script name MyFile.py and you're working on Unix, to run the script you have to
type: print(calendar.month(2020,1))
python MyFile.py Output:
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is more
than 2-4 lines, using the script for coding can help to modify and use the code in future.
Example:
# write a python program to check whether the given year is leap or not.
import calendar
print(calendar.isleap(2021))
Output:
Data types:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cl1.py
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python False
has various standard data types that are used to define the operations possible on them and
#write a python program to print all the months of given year.
the storage method for each of them.
import calendar
Int:
print(calendar.calendar(2020,1,1,1))
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length. Output:
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
6 131
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
Note: Temp1dir is removed 20
>>> 0b10
>>> os.remove("t3.py")
2
Note: We can check with the following cmd whether removed or not >>> a=10
>>> os.access("t3.py",os.F_OK) >>> print(a)
10
False
# To verify the type of any object in Python, use the type() function:
>>> os.listdir()
>>> type(10)
['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py', 'br.py', <class 'int'>
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py', 'cmndlinarg.py',
>>> a=11
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py', 'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py', 'ifelse.py', >>> print(type(a))
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py', 'lis.py', <class 'int'>
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py', 'paraarg.py', Float:
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py', 'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py', 'strr3.py', Float, or "floating point number" is a number, positive or negative, containing one or more
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py', 'wh4.py', 'wh5.py', decimals.
' pycache '] Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> os.listdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32') >>> y=2.8
['argpar.py', 'br.py', 'bu.py', 'cmndlinarg.py', 'DLLs', 'Doc', 'f1.py', 'f1.txt', 'filess', >>> y
'functupretval.py', 'funturet.py', 'gtopt.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'lisparam.py', 2.8
'mysite', 'NEWS.txt', 'niru', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'pyyy', >>> y=2.8
'Scripts', 'srp.py', 'sy.py', 'symod.py', 'tcl', 'the_weather', 'Tools', 'tupretval.py',
>>> print(type(y))
'vcruntime140.dll']
<class 'float'>
>>> type(.4)
Calendar module: <class 'float'>
>>> 2.
130 7
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y)) Note: temp1 dir is created
print(type(z))
>>> os.getcwd()
Output:
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
<class 'float'>
>>> open("t1.py","a")
<class 'float'>
<class 'float'> <_io.TextIOWrapper name='t1.py' mode='a' encoding='cp1252'>
Boolean: >>> os.access("t1.py",os.F_OK)
Objects of Boolean type may have one of two values, True or False: True
>>> type(True) >>> os.access("t1.py",os.W_OK)
<class 'bool'> True
>>> type(False) >>> os.rename("t1.py","t3.py")
<class 'bool'> >>> os.access("t1.py",os.F_OK)
String: False
1. Strings in Python are identified as a contiguous set of characters represented in the >>> os.access("t3.py",os.F_OK)
quotation marks. Python allows for either pairs of single or double quotes.
True
• 'hello' is the same as "hello".
>>> os.rmdir('temp1')
• Strings can be output to screen using the print function. For example: print("hello").
(or)
>>> print("mrcet college")
os.rmdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/temp1')
mrcet college
>>> type("mrcet college")
<class 'str'>
8 129
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13, tm_min=1, >>> print('mrcet college')
tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)
mrcet college
#write a python program to make a time stamp.
>>> " "
import time
''
a=(1999,5,27,7,20,15,1,27,0)
If you want to include either type of quote character within the string, the simplest way is to
print(time.mktime(a)) delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
Output:
>>> print("mrcet is an autonomous (') college")
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
mrcet is an autonomous (') college
927769815.0
>>> print('mrcet is an autonomous (") college')
#write a python program using sleep().
mrcet is an autonomous (") college
import time
Suppressing Special Character:
time.sleep(6) #prints after 6 seconds
Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
print("Python Lab")
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
Output: quote character:
>>> os.name The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:
'nt'
>>> print('a\
>>> os.getcwd()
....b')
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy' a....b
>>> os.mkdir("temp1") >>> print('a\
b\
c')
128 9
abc C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
>>> print('a \n b') 180 days, 0:00:00
a
#write an python program to print date, time using date and time functions
b
>>> print("mrcet \n college") import datetime
mrcet t=datetime.datetime.today()
college
print(t.date())
print(t.time())
Escape Usual Interpretation of
Sequence Character(s) After Backslash “Escaped” Interpretation Output:
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
\newline Terminates input line Newline is ignored 2019-11-29
\\ Introduces escape sequence Literal backslash (\) character
12:53:39.226763
In Python (and almost all other common computer languages), a tab character can be Time module:
specified by the escape sequence \t: #write a python program to display time.
>>> print("a\tb") import time
a b
print(time.time())
List:
Output:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate members. C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
(Grow and shrink as needed, sequence type, sortable).
1575012547.1584706
To use a list, you must declare it first. Do this using square brackets and separate
values with commas. #write a python program to get structure of time stamp.
We can construct / create list in many ways.
import time
Ex:
print(time.localtime(time.time()))
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
Output:
>>> print(list1)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
10 127
a=datetime.datetime.today()
print(a) >>> x
[]
print(b)
Output:
>>> tuple1=(1,2,3,4)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
>>> x=list(tuple1)
2019-11-29 12:49:52.235581
>>> x
2019-11-29 12:49:52.235581
[1, 2, 3, 4]
#write a python program to add some days to your present date and print the date Variables:
added.
Variables are nothing but reserved memory locations to store values. This means that when
import datetime you create a variable you reserve some space in memory.
a=datetime.date.today() Based on the data type of a variable, the interpreter allocates memory and decides what can
b=datetime.timedelta(days=7) be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
print(a+b)
Rules for Python variables:
Output:
• A variable name must start with a letter or the underscore character
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
• A variable name cannot start with a number
2019-12-06
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
#write a python program to print the no. of days to write to reach your birthday and _ )
import datetime • Variable names are case-sensitive (age, Age and AGE are three different variables)
a=datetime.date.today() Assigning Values to Variables:
b=datetime.date(2020,5,27) Python variables do not need explicit declaration to reserve memory space. The declaration
c=b-a happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
print(c)
The operand to the left of the = operator is the name of the variable and the operand to the
Output: right of the = operator is the value stored in the variable.
126 11
For example − >>> example. name
a= 100 # An integer assignment 'example'
b = 1000.0 # A floating point Datetime module:
c = "John" # A string # Write a python program to display date, time
print (a) >>> import datetime
print (b) >>> a=datetime.datetime(2019,5,27,6,35,40)
print (c) >>> a
This produces the following result − datetime.datetime(2019, 5, 27, 6, 35, 40)
100 # write a python program to display date
1000.0 import datetime
John a=datetime.date(2000,9,18)
Multiple Assignment: print(a)
Python allows you to assign a single value to several variables simultaneously. Output:
For example : C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
a=b=c=1 2000-09-18
Here, an integer object is created with the value 1, and all three variables are assigned to the # write a python program to display time
same memory location. You can also assign multiple objects to multiple variables.
import datetime
For example −
a=datetime.time(5,3)
a,b,c = 1,2,"mrcet“
print(a)
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
Output:
and one string object with the value "john" is assigned to the variable c.
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
Output Variables:
05:03:00
The Python print statement is often used to output variables.
#write a python program to print date, time for today and now.
Variables do not need to be declared with any particular type and can even change type after
they have been set. import datetime
12 125
>>> import add x=5 # x is of type int
x = "mrcet " # x is now of type str
>>> import add
print(x)
>>>
Output: mrcet
Python provides a neat way of doing this. We can use the reload() function inside
To combine both text and a variable, Python uses the “+” character:
the imp module to reload a module. This is how its done.
Example
• >>> import imp
x = "awesome"
• >>> import my_module
print("Python is " + x)
• This code got executed >>> import my_module >>> imp.reload(my_module) This
Output
code got executed <module 'my_module' from '.\\my_module.py'>how its done.
Python is awesome
You can also use the + character to add a variable to another variable:
>>> import imp
Example
>>> import add
x = "Python is "
>>> imp.reload(add)
y = "awesome"
8 z=x+y
print(z)
<module 'add' from 'C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy\\add.py'> Output:
[' annotations ', ' builtins ', ' doc ', ' file ', ' loader ', ' name ', >>> z=x+20
' package ', ' spec ', ' warningregistry ', 'add', 'example', 'hi', 'imp']
>>> z
It shows all built-in and user-defined modules.
30
For ex:
124 13
>>> x=10
>>> y=20
>>> c=x+y
Here, we have defined a function add() inside a module named example. The function takes
>>> c in two numbers and returns their sum.
30 How to import the module is:
A value all by itself is a simple expression, and so is a variable. • We can import the definitions inside a module to another module or the Interactive
interpreter in Python.
>>> y=20
• We use the import keyword to do this. To import our previously defined
>>> y
module example we type the following in the Python prompt.
20
• Using the module name we can access the function using dot (.) operation. For Eg:
Python also defines expressions only contain identifiers, literals, and operators. So,
>>> import example
Identifiers: Any name that is used to define a class, function, variable module, or object is
>>> example.add(5,5)
an identifier.
10
Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer • Python has a ton of standard modules available. Standard modules can be imported
literals, floating point literals, and imaginary literals. the same way as we import our user-defined modules.
Operators: In Python you can implement the following operations using the corresponding Reloading a module:
tokens.
def hi(a,b):
print(a+b)
hi(4,4)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/add.py
8
>>> import add
8
14 123
• We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
Operator Token
• We can define our most used functions in a module and import it, instead of copying
their definitions into different programs.
add +
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules. subtract -
Advantages :
multiply *
• Simplicity: Rather than focusing on the entire problem at hand, a module typically
focuses on one relatively small portion of the problem. If you’re working on a single Integer Division /
module, you’ll have a smaller problem domain to wrap your head around. This makes
development easier and less error-prone. remainder %
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a way that Binary left shift <<
minimizes interdependency, there is decreased likelihood that modifications to a
single module will have an impact on other parts of the program. This makes it more Binary right shift >>
viable for a team of many programmers to work collaboratively on a large application.
and &
• Reusability: Functionality defined in a single module can be easily reused (through
an appropriately defined interface) by other parts of the application. This eliminates
or \
the need to recreate duplicate code.
• Scoping: Modules typically define a separate namespace, which helps avoid Less than <
collisions between identifiers in different areas of a program.
Greater than >
• Functions, modules and packages are all constructs in Python that promote code
modularization.
Less than or equal to <=
A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.
Greater than or equal to >=
>>> def add(a,b):
122 15
Some of the python expressions are: #
a=5
Generator expression:
b=0
Syntax: ( compute(var) for var in iterable )
try:
print("resource open")
>>> x = (i for i in 'abc') #tuple comprehension print(a/b)
>>> x k=int(input("enter a number"))
<generator object <genexpr> at 0x033EEC30> print(k)
except ZeroDivisionError as e:
>>> print(x) print("the value can not be divided by zero",e)
<generator object <genexpr> at 0x033EEC30>
except ValueError as e:
print("invalid input")
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
except Exception as e:
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
print("something went wrong...",e)
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
finally:
print("resource closed")
Conditional expression:
Output:
Syntax: true_value if Condition else false_value
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex11.py
>>> x = "1" if True else "2" resource open
the value can not be divided by zero division by zero
>>> x resource closed
'1'
Change the value of b to 2 and give the input as some character or string (other
Statements: than int)
A statement is an instruction that the Python interpreter can execute. We have normally two C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex12.py
basic statements, the assignment statement and the print statement. Some other kinds of resource open
statements that are if statements, while statements, and for statements generally called as 2.5
control flows. enter a number p
invalid input
Examples: resource closed
An assignment statement creates new variables and gives them values:
Modules (Date, Time, os, calendar, math):
>>> x=10
• Modules refer to a file containing Python statements and definitions.
16 121
print("resource open") >>> college="mrcet"
print(a/b)
An print statement is something which is an input from the user, to be printed / displayed on
k=int(input("enter a number"))
to the screen (or ) monitor.
print(k)
except ZeroDivisionError as e: >>> print("mrcet colege")
print("the value can not be divided by zero",e)
finally: mrcet college
print("resource closed") Precedence of Operators:
Output:
Operator precedence affects how an expression is evaluated.
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
the value can not be divided by zero division by zero precedence than +, so it first multiplies 3*2 and then adds into 7.
resource closed
Example 1:
change the value of b to 2 for above program, you see the output like >>> 3+4*2
11
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open Multiplication gets evaluated before the addition operation
2.5
enter a number 6 >>> (10+10)*2
6 40
resource closed
Parentheses () overriding the precedence of the arithmetic operators
Instead give input as some character or string for above program, check the Example 2:
output
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py a = 20
resource open b = 10
c = 15
2.5
d=5
enter a number p e=0
resource closed
Traceback (most recent call last): e = (a + b) * c / d #( 30 * 15 ) / 5
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py", line print("Value of (a + b) * c / d is ", e)
7, in <module>
e = ((a + b) * c) / d # (30 * 15 ) / 5
k=int(input("enter a number"))
print("Value of ((a + b) * c) / d is ", e)
ValueError: invalid literal for int() with base 10: ' p'
e = (a + b) * (c / d); # (30) * (15/5)
120 17
print("Value of (a + b) * (c / d) is ", e) C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex8.py
e = a + (b * c) / d; # 20 + (150/5) resource opened
print("Value of a + (b * c) / d is ", e)
number can not be divided by zero division by zero
Output: resource closed
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/opprec.py
Value of (a + b) * c / d is 90.0 The result is fine that the file is opened and closed, but again change the value of
Value of ((a + b) * c) / d is 90.0 b to back (i.e., value 2 or other than zero)
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0 a=5
b=2
Comments: try:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the print("resource opened")
whole line should be considered as a comment until the end of line. print(a/b)
except Exception as e:
A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting. print("number can not be divided by zero",e)
print("resource closed")
Example:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5
But again the same problem file/resource is not closed
To overcome this python has a feature called finally:
Output:
This block gets executed though we get an error or not
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py
Note: Except block executes, only when try block has an error, but finally block
30 executes, even though you get an exception.
a=5
b=0
try:
18 119
Note: the file is opened and closed well, but see by changing the value of b to 0, Modules:
a=5 Modules: Python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that our
b=0
python code file saved with the extension (.py) is treated as the module. We may have a
try: runnable code inside the python module. A module in Python provides us the flexibility to
organize the code in a logical way. To use the functionality of one module into another, we
print("resource opened") must have to import the specific module.
print(a/b) Syntax:
print("resource closed") import <module-name>
except Exception as e: Every module has its own functions, those can be accessed with . (dot)
print("number can not be divided by zero",e) Note: In python we have help ()
Output: Enter the name of any module, keyword, or topic to get help on writing Python programs
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex7.py and using Python modules. To quit this help utility and return to the interpreter, just type
"quit".
resource opened
Some of the modules like os, date, and calendar so on……
number can not be divided by zero division by zero
>>> import sys
Note: resource not closed
>>> print(sys.version)
To overcome this, keep print(“resource closed”) in except block, see it
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
a=5 >>> print(sys.version_info)
b=0 sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> print(calendar.month(2021,5))
try:
print("resource opened")
print(a/b)
except Exception as e:
a=5 C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py
welcome
b=2
0
try: 1
print(a/b) 2
Good morning college
except Exception:
The flow/order of execution is: 2,3,4,3,4,3,4,5
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py
2.5
For example if you want to print the message like what is an error in a program
then we use “e” which is the representation or object of an exception.
a=5
b=0
try:
116 21
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py
For ex:
hi
a=5
hello
Good morning b=2
mrcet print(a/b)
done!
print("Bye")
The flow/order of execution is: 2,5,6,7,2,3,4,7,8
Output:
Parameters and arguments: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py
Parameters are passed during the definition of function while Arguments are passed during 2.5
the function call.
Bye
Example:
#here a and b are parameters The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below
def add(a,b): #//function definition
return a+b a=5
b=0
#12 and 13 are arguments
#function call print(a/b)
result=add(12,13)
print(result) print("bye") #this has to be printed, but abnormal termination
Output: Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py Traceback (most recent call last):
25 File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex2.py", line
3, in <module>
There are three types of Python function arguments using which we can call a function.
print(a/b)
1. Default Arguments
ZeroDivisionError: division by zero
2. Keyword Arguments
3. Variable-length Arguments To overcome this we handle exceptions using except keyword
Syntax: a=5
def functionname(): b=0
22 115
Handling Exceptions: statements
The cause of an exception is often external to the program itself. For example, an incorrect .
.
input, a malfunctioning IO device etc. Because the program abruptly terminates on
.
encountering an exception, it may cause damage to system resources, such as files. Hence, functionname()
the exceptions should be properly handled so that an abrupt termination of the program is
prevented. Function definition consists of following components:
Python uses try and except keywords to handle exceptions. Both keywords are followed by 1. Keyword def indicates the start of function header.
indented blocks. 2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
Syntax: 3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
try :
5. Optional documentation string (docstring) to describe what the function does.
#statements in try block 6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
except : 7. An optional return statement to return a value from the function.
Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but if To get the statements of function need to be use print().
the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
#calling function in python:
This is not easy compared to the above two errors because it is not done by the
system, it is (mistake) done by the user. def hf():
1. You should be able to understand the mistakes; the error might be done by user, DB hf()
connection or server.
Output:
2. Whenever there is an error execution should not stop.
Ex: Banking Transaction hello world
3. The aim is execution should not stop even though an error occurs.
114 23
def hf(): IndentationError:
print("hw") Unexpected indent. As mentioned in the "expected an indentedblock" section, Python not
only insists on indentation, it insists on consistentindentation. You are free to choose the
print("gh kfjg 66666")
number of spaces of indentation to use, but you then need to stick with it.
hf()
Syntax errors:
hf()
These are the most basic type of error. They arise when the Python parser is unable to
hf() understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a
way to successfully execute a piece of code containing syntax errors.
Output:
Run-time error:
hw
gh kfjg 66666 A run-time error happens when Python understands what you are saying, but runs into
hw trouble when following your instructions.
gh kfjg 66666
hw Key Error :
gh kfjg 66666
Python raises a KeyError whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary.
def add(x,y):
Value Error:
c=x+y
In Python, a value is the information that is stored within a certain object. To encounter a
print(c) ValueError in Python means that is a problem with the content of the object you tried to
add(5,4) assign the value to.
Output: Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
9 class. This exception class has to be derived, either directly or indirectly,
def add(x,y): from Exception class.
c=x+y Different types of exceptions:
return c ArrayIndexOutOfBoundException.
ClassNotFoundException.
print(add(5,4)) FileNotFoundException.
IOException.
Output: InterruptedException.
9 NoSuchFieldException.
NoSuchMethodException
24 113
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py ==
def add_sub(x,y):
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py']
c=x+y
d=x-y
Errors and Exceptions:
return c,d
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will print(add_sub(10,5))
encounter errors. Error caused by not following the proper structure (syntax) of the language
is called syntax error or parsing error Output:
ZeroDivisionError: (15, 5)
ZeroDivisionError in Python indicates that the second argument used in a division (or The return statement is used to exit a function and go back to the place from where it was
modulo) operation was zero. called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
OverflowError: def hf():
OverflowError in Python indicates that an arithmetic operation has exceeded the limits of return "hw"
the current Python runtime. This is typically due to excessively large float values, as integer
values that are too big will opt to raise memory errors instead. print(hf())
ImportError: Output:
It is raised when you try to import a module which does not exist. This may happen if you hw
made a typing mistake in the module name or the module doesn't exist in its standard path.
In the example below, a module named "non_existing_module" is being imported but it
doesn't exist, hence an import error exception is raised.
An IndexError exception is raised when you refer a sequence which is out of range. In the return "hw"
example below, the list abc contains only 3 entries, but the 4th index is being accessed, hf()
which will result an IndexError exception.
Output:
TypeError:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu.py
When two unrelated type of objects are combined, TypeErrorexception is raised.In example
below, an int and a string is added, which will result in TypeError exception. >>>
112 25
import argparse
def hello_f(): parser = argparse.ArgumentParser()
print(parser.parse_args())
return "hellocollege"
print(hello_f().upper())
‘getopt’ module :
Output:
Python argparse module is the preferred way to parse command line arguments. It provides a
HELLOCOLLEGE lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc
# Passing Arguments
def hello(wish): It parses the command line options and parameter list. The signature of this function is
mentioned below:
return '{}'.format(wish)
getopt.getopt(args, shortopts, longopts=[ ])
print(hello("mrcet"))
args are the arguments to be passed.
Output: shortopts is the options this script accepts.
Optional parameter, longopts is the list of String parameters this function accepts
mrcet
which should be supported. Note that the -- should not be prepended with option
names.
Here, the function wish() has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors. -h------------ print help and usage message
-m----------- accept custom option value
def wish(name,msg): -d------------ run the script in debug mode
"""This function greets to import getopt
import sys
the person with the provided message"""
print("Hello",name + ' ' + msg) argv = sys.argv[0:]
try:
wish("MRCET","Good morning!") opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
Output: print(args)
except getopt.GetoptError:
Hello MRCET Good morning! # Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
26 111
Note: Since my list consist of only one element at ‘0’ index so it prints only that list Below is a call to this function with one and no arguments along with their respective error
element, if we try to access at index position ‘1’ then it shows the error like, messages.
IndexError: list index out of range >>> wish("MRCET") # only one argument
TypeError: wish() missing 1 required positional argument: 'msg'
>>> wish() # no arguments
import sys TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i) def hello(wish,hello):
Python getopt module is very similar in working as the C getopt() function for parsing There are two advantages - one, using the function is easier since we do not need to
command-line parameters. Python getopt module is useful in parsing command line worry about the order of the arguments. Two, we can give values to only those
arguments where we want user to enter some options too. parameters which we want, provided that the other parameters have default argument
values.
>>> parser = argparse.ArgumentParser(description='Process some integers.')
def func(a, b=5, c=10):
# print 'a is', a, 'and b is', b, 'and c is', c
110 27
func(3, 7) Command line arguments:
func(25, c=24)
func(c=50, a=100) The command line arguments must be given whenever we want to give the input before the
start of the script, while on the other hand, raw_input() is used to get the input while the
python program / script is running.
Output:
The command line arguments in python can be processed by using either ‘sys’ module,
a is 3 and b is 7 and c is 10 ‘argparse’ module and ‘getopt’ module.
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50 ‘sys’ module :
Python sys module stores the command line arguments into a list, we can access it
Note: using sys.argv. This is very useful and simple way to read command line arguments as
String.
The function named func has one parameter without default argument values, sys.argv is the list of commandline arguments passed to the Python program. argv represents
followed by two parameters with default argument values. all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10. >>> sys.modules.keys() -- this prints so many dict elements in the form of list.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the # Python code to demonstrate the use of 'sys' module for command line arguments
position of the argument. Then, the parameter c gets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5. import sys
In the third usage func(c=50, a=100), we use keyword arguments completely to # command line arguments are stored in the form
specify the values. Notice, that we are specifying value for parameter c before that # of list in sys.argv
for a even though a is defined before c in the function definition. argumentList = sys.argv
print(argumentList)
For example: if you define the function like below
# Print the name of file
def func(b=5, c=10,a): # shows error : non-default argument follows default argument
print(sys.argv[0])
# Print the first argument after the name of file
def print_name(name1, name2): #print(sys.argv[1])
""" This function prints the name """ Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
print (name1 + " and " + name2 + " are friends")
#calling the function ['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
print_name(name2 = 'A',name1 = 'B')
28 109
But when we try to write some data on to the same file it overwrites and saves with the Output:
current data (check output)
B and A are friends
#Default Arguments
# Write a python program to open and write the content to file and read it. Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=)
fo=open("abc.txt","w+")
def hello(wish,name='you'):
fo.write("Python Programming")
return '{},{}'.format(wish,name)
print(fo.read())
print(hello("good morning"))
fo.close()
Output:
Output:
good morning,you
def hello(wish,name='you'):
Output:
Note: It creates the abc.txt file automatically and writes the data into it good morning,nirosha // good morning nirosha
Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:
#Program to find area of a circle using function use single return value function with
Note: All the program files and text files need to saved together in a particular file then argument.
only the program performs the operations in the given file mode
pi=3.14
def areaOfCircle(r):
return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter radius of circle 3
28.259999999999998
f.close() ---- This will close the instance of the file somefile.txt stored
#Program to write sum different product and using arguments with return value
function.
# Write a python program to open and write “hello world” into a file?
def calculete(a,b):
f=open("1.txt","a") total=a+b
f.close() prod=a*b
Output: div=a/b
mod=a%b
106 31
return total,diff,prod,div,mod
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)
#print("diff= ",d) (or)
#print("mul= ",p)
#print("div= ",q)
Hit on enter then it shows the following whether to open or not?
#print("mod= ",m)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
#program to find biggest of two numbers using functions.
def biggest(a,b):
if a>b :
return a
else :
return b
Click on “yes” to open else “no” to cancel
a=int(input("Enter a value"))
b=int(input("Enter b value")) # Write a python program to open and read a file
#function call
big= biggest(a,b)
print("big number= ",big) a=open(“one.txt”,”r”)
Output: print(a.read())
32 105
The available option beside "w" are "r" for read and "a" for append and plus sign C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
means if it is not there then create it Enter a value 5
Enter b value-2
big number= 5
File Modes in Python:
#program to find biggest of two numbers using functions. (nested if)
Mode Description
def biggest(a,b,c):
'r' This is the default mode. It Opens file for reading. if a>b :
if a>c :
return a
'w' This Mode Opens file for writing. else :
If file does not exist, it creates a new file. return c
If file exists it truncates the file. else :
if b>c :
return b
'x' Creates a new file. If file already exists, the operation fails. else :
return c
'a' Open file in append mode.
If file does not exist, it creates a new file. a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
't' This is the default mode. It opens in text mode.
#function call
big= biggest(a,b,c)
'b' This opens in binary mode. print("big number= ",big)
Output:
'+' This will open a file for reading and writing (updating) C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7
Reading and Writing files:
The following image shows how to create and open a text file in notepad from command #Writer a program to read one subject mark and print pass or fail use single return
prompt values function with argument.
def result(a):
if a>40:
return "pass"
104 33
else: UNIT – V
return "fail"
a=int(input("Enter one subject marks")) FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments, errors
print(result(a))
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module),
Output: Explore packages.
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter one subject marks 35 Files, Exceptions, Modules, Packages:
fail Files and exception:
A file is some information or data which stays in the computer storage devices. Python gives
#Write a program to display mrecet cse dept 10 times on the screen. (while loop) you easy ways to manipulate these files. Generally files divide in two categories,
def usingFunctions(): text file and binary file. Text files are simple text where as the binary files contain binary
count =0 data which is only readable by computer.
while count<10:
Text files: In this type of file, Each line of text is terminated with a special character
print("mrcet cse dept",count)
count=count+1 called EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored
usingFunctions()
after converting it into machine understandable binary language.
Output:
An exception is an event, which occurs during the execution of a program that disrupts the
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
mrcet cse dept 0 normal flow of the program's instructions. In general, when a Python script encounters a
mrcet cse dept 1 situation that it cannot cope with, it raises an exception. An exception is a Python object
mrcet cse dept 2 that represents an error.
mrcet cse dept 3
mrcet cse dept 4 Text files:
mrcet cse dept 5
mrcet cse dept 6 We can create the text files by using the syntax:
mrcet cse dept 7
mrcet cse dept 8 Variable name=open (“file.txt”, file mode)
mrcet cse dept 9
For ex: f= open ("hello.txt","w+")
We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
Here we used "w" letter in our argument, which indicates write and the plus sign that
means it will create a file if it does not exist in library
34 103
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password': UNIT – II
'123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
CONTROL FLOW, LOOPS
## Delete a field
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
>>> del customers[1]
>>> print(customers) conditional (if-elif-else); Iteration: while, for, break, continue.
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
Control Flow, Loops:
'123456'}]
Boolean Values and Operators:
>>> del customers[1]
>>> print(customers) A boolean expression is an expression that is either true or false. The following examples
[{'uid': 1, 'name': 'John', 'password': '123456'}] use the operator ==, which compares two operands and produces True if they are equal and
False otherwise:
## Delete all fields
>>> 5 == 5
>>> for x in customers:
del x["uid"] True
>>> 5 == 6
>>> x False
{'name': 'John', 'password': '123456'}
True and False are special values that belong to the type bool; they are not strings:
Comprehension:
>>> type(True)
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
<class 'bool'>
value expressions:
>>> type(False)
>>> z={x: x**2 for x in (2,4,6)}
>>> z <class 'bool'>
{2: 4, 4: 16, 6: 36}
The == operator is one of the relational operators; the others are: x != y # x is not equal to y
>>> dict11 = {x: x*x for x in range(6)} x > y # x is greater than y x < y # x is less than y
>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} x >= y # x is greater than or equal to y x <= y # x is less than or equal to y
Note:
All expressions involving relational and logical operators will evaluate to either true or false
102 35
Conditional (if): 4 16
5 25
The if statement contains a logical expression using which data is compared and a decision >>> for k,v in x.items():
is made based on the result of the comparison. print(k,v)
Syntax:
if expression: 11
statement(s) 24
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if 39
statement is executed. If boolean expression evaluates to FALSE, then the first set of 4 16
code after the end of the if statement(s) is executed. 5 25
if Statement Flowchart: List of Dictionaries:
>>> customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]
## Print the uid and name of each customer
>>> for x in customers:
print(x["uid"], x["name"])
1 John
2 Smith
Fig: Operation of if statement 3 Andersson
Example: Python if Statement ## Modify an entry, This will change the name of customer 2 from Smith to Charlie
a=3 >>> customers[2]["name"]="charlie"
if a > 2: >>> print(customers)
print(a, "is greater") [{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]
print("done")
## Add a new field to each entry
a = -1
if a < 0: >>> for x in customers:
print(a, "a is smaller") x["password"]="123456" # any initial value
print("Finish")
Output: >>> print(customers)
36 101
Remove
Length C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
Delete 3 is greater
done
Add/change values: You can change the value of a specific item by referring to its key -1 a is smaller
name Finish
Delete: Deletes a particular item. An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25} resolves to 0 or a FALSE value.
>>> del x[5]
>>> x The else statement is an optional statement and there could be at most only one else
Statement following if.
Length: we use len() method to get the length of dictionary.
Syntax of if - else :
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16} if test expression:
>>> y=len(x) Body of if stmts
>>> y
else:
4
Iterating over (key, value) pairs: Body of else stmts
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25} If - else Flowchart :
>>> for key in x:
print(key, x[key])
11
24
39
100 37
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'mrcet'
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1.keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1.values()
dict_values(['mrcet', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
Fig: Operation of if – else statement
Example of if - else: >>> for items in dict1.values():
print(items)
a=int(input('enter the number'))
if a>5:
print("a is greater") mrcet
college
else:
2004
print("a is smaller than the input given")
>>> for items in dict1.keys():
Output: print(items)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 2
a is smaller than the input given brand
model
----------------------------------------
year
a=10
b=20 >>> for i in dict1.items():
if a>b: print(i)
print("A is Greater than B")
else:
print("B is Greater than A") ('brand', 'mrcet')
('model', 'college')
Output: ('year', 2004)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if2.py
Some more operations like:
B is Greater than A
Add/change
38 99
copy() Return a shallow copy of the dictionary.
Chained Conditional: (If-elif-else):
Return a new dictionary with keys from seq and
The elif statement allows us to check multiple expressions for TRUE and execute a
fromkeys(seq[, v]) value equal to v (defaults to None).
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
Return the value of key. If key doesnot exit, statement, there can be an arbitrary number of elif statements following an if.
get(key[,d]) return d (defaults to None).
Syntax of if – elif - else :
Remove the item with key and return its value Flowchart of if – elif - else:
or d if key is not found. If d is not provided
pop(key[,d]) and key is not found, raises KeyError.
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr> while(expression):
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a Statement(s)
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE. Flowchart:
So, given the code
a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
96 41
Example Programs: We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
1. Run the above code- It gives name mrcet for first tuple while for second tuple it gives
i=1 number (2, 3, 4)
while i<=6:
Tuple as return values:
print("Mrcet college")
i=i+1 A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh1.py # A Python program to return multiple values from a method using tuple
Mrcet college # This function returns a tuple
Mrcet college def fun():
Mrcet college str = "mrcet college"
x = 20
Mrcet college return str, x; # Return tuple, we could also
Mrcet college # write (str, x)
# Driver code to test above method
Mrcet college
str, x = fun() # Assign returned tuple
2. print(str)
i=1 print(x)
while i<=3: Output:
print("MRCET",end=" ") C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval.py
j=1 mrcet college
while j<=1: 20
print("CSE DEPT",end="")
j=j+1
i=i+1 Functions can return tuples as return values.
print()
def circleInfo(r):
Output:
""" Return (circumference, area) of a circle of radius r """
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh2.py
c = 2 * 3.14159 * r
MRCET CSE DEPT a = 3.14159 * r * r
MRCET CSE DEPT return (c, a)
MRCET CSE DEPT print(circleInfo(10))
Output:
3.
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/functupretval.py
i=1 (62.8318, 314.159)
42 95
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) j=1
>>> x.index(2) while i<=3:
1 print("MRCET",end=" ")
i=1
Tuple Assignment while (i < 10):
print (i)
Python has tuple assignment feature which enables you to assign more than one variable at a i = i+1
time. In here, we have assigned tuple 1 with the college information like college name, year, Output:
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh4.py
For Example, 1
2
Here is the code, 3
4
>>> tup1 = ('mrcet', 'eng college','2004','cse', 'it','csit'); 5
6
>>> tup2 = (1,2,3,4,5,6,7); 7
>>> print(tup1[0]) 8
9
mrcet
2.
>>> print(tup2[1:4]) a=1
b=1
(2, 3, 4) while (a<10):
print ('Iteration',a)
Tuple 1 includes list of information of mrcet
a=a+1
Tuple 2 includes list of numbers in it b=b+1
94 43
if (b == 4):
break Access tuple items: Access tuple items by referring to the index number, inside square
print ('While loop terminated') brackets
>>> x=('a','b','c','g')
Output:
>>> print(x[2])
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh5.py c
Iteration 1
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
Iteration 2
Iteration 3 are unchangeable.
While loop terminated
>>> x=(2,5,7,'4',8)
count = 0 >>> x[1]=10
while (count < 9): Traceback (most recent call last):
print("The count is:", count) File "<pyshell#41>", line 1, in <module>
count = count + 1
x[1]=10
print("Good bye!")
TypeError: 'tuple' object does not support item assignment
Output: >>> x
(2, 5, 7, '4', 8) # the value is still the same
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh.py =
The count is: 0
The count is: 1 Loop through a tuple: We can loop the values of tuple using for loop
The count is: 2 >>> x=4,5,6,7,2,'aa'
The count is: 3 >>> for i in x:
The count is: 4 print(i)
The count is: 5
The count is: 6
The count is: 7 4
The count is: 8 5
Good bye! 6
7
For loop: 2
aa
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other Count (): Returns the number of times a specified value occurs in a tuple
iterable objects >>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
Syntax: for var in sequence: 4
Statement(s) A sequence of values assigned to var in each iteration
Holds the value of item Index (): Searches the tuple for a specified value and returns the position of where it
in sequence in each iteration was found
44 93
accidently being added, changed, or deleted. Sample Program:
Tuples are more efficient than list due to python’s implementation.
numbers = [1, 2, 4, 6, 11, 20]
We can construct tuple in many ways: seq=0
X=() #no item tuple for val in numbers:
X=(1,2,3) seq=val*val
X=tuple(list1) print(seq)
X=1,2,3,4
Example: Output:
>>> x=(1,2,3) C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr.py
>>> print(x) 1
4
(1, 2, 3)
16
>>> x 36
(1, 2, 3) 121
400
>>> x=()
>>> x
Flowchart:
()
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
92 45
Iterating over a list: Similarily some examples:
#list of items
list = ['M','R','C','E','T'] >>> x=[m for m in range(8)]
i=1 >>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]
#Iterating over the list
for item in list: >>> x=[z**2 for z in range(10) if z>4]
print ('college ',i,' is ',item)
>>> print(x)
i = i+1
[25, 36, 49, 64, 81]
Output: >>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
>>> print(x)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
[1, 9, 25, 49, 81]
college 1 is M
college 2 is R
>>> a=5
college 3 is C
>>> table = [[a, b, a * b] for b in range(1, 11)]
college 4 is E >>> for i in table:
college 5 is T print(i)
Iterating over a Tuple:
tuple = (2,3,5,7) [5, 1, 5]
print ('These are the first four prime numbers ') [5, 2, 10]
#Iterating over the tuple [5, 3, 15]
for a in tuple: [5, 4, 20]
print (a) [5, 5, 25]
[5, 6, 30]
Output: [5, 7, 35]
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py [5, 8, 40]
These are the first four prime numbers [5, 9, 45]
2 [5, 10, 50]
3
5
7 Tuples:
Iterating over a dictionary: A tuple is a collection which is ordered and unchangeable. In Python tuples are written
#creating a dictionary with round brackets.
college = {"ces":"block1","it":"block2","ece":"block3"} Supports all operations for sequences.
Immutable, but member objects may be mutable.
#Iterating over the dictionary to print keys
print ('Keys are:') If the contents of a list shouldn’t change, use a tuple to prevent items from
46 91
for keys in college:
print (keys)
List comprehension:
#Iterating over the dictionary to print values
List: print ('Values are:')
for blocks in college.values():
List comprehensions provide a concise way to create lists. Common applications are to make
print(blocks)
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a Output:
certain condition. C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
For example, assume we want to create a list of squares, like: ces
it
>>> list1=[] ece
Values are:
>>> for x in range(10): block1
block2
list1.append(x**2) block3
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new
list. In this case the slice happens to consist of the whole list.
Example:
[1, 2, 10, 4, 6, 7] #
for letter in "Python": # First Example
if letter == "h":
>>> x.insert(4,['a',11]) break
print("Current Letter :", letter )
>>> x
7 Continue:
>>> x The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
[1, 2, 10, 4, 6]
Flowchart:
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6] The following shows the working of break statement in for and while loop:
86 51
for var in sequence: length = len(list)
# code inside for loop i=0
If condition:
# Iterating using while loop
continue (if break condition satisfies it jumps to outside loop)
while i < length:
# code inside for loop print(list[i])
# code outside for loop i += 1
while test expression Mutability:
# code inside while loop A mutable object can be changed after it is created, and an immutable object can't.
If condition:
continue(if break condition satisfies it jumps to outside loop) Append: Append an item to a list
# code inside while loop >>> x=[1,5,8,4]
# code outside while loop
>>> x.append(10)
>>> x
Example:
[1, 5, 8, 4, 10]
# Program to show the use of continue statement inside loops
Extend: Append a sequence to a list.
for val in "string": >>> x=[1,2,3,4]
if val == "i":
continue >>> y=[3,6,9,1]
print(val)
>>> x.extend(y)
print("The end") >>> x
Output: Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s >>> del(x[1]) #deletes the index position 1 in a list
t
r >>> x
n [5, 8, 6]
g
The end Insert: To add an item at the specified index, use the insert () method:
# program to display only odd numbers >>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)
for num in [20, 11, 9, 66, 4, 89, 44]:
52 85
i=1 # Skipping the iteration when number is even
if num%2 == 0:
#Iterating over the list continue
for item in list: # This statement will be skipped for all even numbers
print ('college ',i,' is ',item) print(num)
i = i+1
Output: Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py
college 1 is M 11
college 2 is R 9
college 3 is C 89
college 4 is E
#
college 5 is T
for letter in "Python": # First Example
if letter == "h":
Method #2: For loop and range() continue
In case we want to use the traditional for loop which iterates from number x to number y. print("Current Letter :", letter)
# Python3 code to iterate over a list Output:
list = [1, 3, 5, 7, 9]
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/con1.py
# getting length of list Current Letter : P
length = len(list) Current Letter : y
Current Letter : t
# Iterating the index Current Letter : o
# same as 'for i in range(len(list))' Current Letter : n
for i in range(length):
print(list[i]) Pass:
>>> x.pop() Any function that returns a value is called Fruitful function. A Function that does not return
a value is called a void function
7
Return values:
>>> x
The Keyword return is used to return back the value to the called function.
[1, 2, 10, 4, 6]
# returns the area of a circle with the given radius:
>>> x=[1,33,2,10,4,6]
Sometimes it is useful to have multiple return statements, one in each branch of a
>>> x.remove(33) conditional:
>>> x def absolute_value(x):
if x < 0:
82 55
return -x Append()
else: Extend()
return x Insert()
Pop()
Since these return statements are in an alternative conditional, only one will be executed.
Remove()
As soon as a return statement executes, the function terminates without executing any Reverse()
subsequent statements. Code that appears after a return statement, or any other place the Sort()
flow of execution can never reach, is called dead code. Delete: Delete a list or an item from a list
In a fruitful function, it is a good idea to ensure that every possible path through the program >>> x=[5,3,8,6]
hits a return statement. For example:
>>> del(x[1]) #deletes the index position 1 in a list
def absolute_value(x):
>>> x
if x < 0:
return -x [5, 8, 6]
if x > 0:
return x
>>> del(x)
This function is incorrect because if x happens to be 0, both conditions is true, and the
function ends without hitting a return statement. If the flow of execution gets to the end of a >>> x # complete list gets deleted
function, the return value is None, which is not the absolute value of 0.
Append: Append an item to a list
>>> print absolute_value(0) >>> x=[1,5,8,4]
None
>>> x.append(10)
By the way, Python provides a built-in function called abs that computes absolute values.
>>> x
# Write a Python function that takes two lists and returns True if they have at least one
[1, 5, 8, 4, 10]
common member.
Extend: Append a sequence to a list.
def common_data(list1, list2):
for x in list1: >>> x=[1,2,3,4]
for y in list2:
>>> y=[3,6,9,1]
if x == y:
result = True >>> x.extend(y)
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5])) >>> x
print(common_data([1,2,3,4,5], [1,7,8,9,510])) [1, 2, 3, 4, 3, 6, 9, 1]
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Insert: To add an item at the specified index, use the insert () method:
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py >>> x=[1,2,4,6,7]
56 81
L[-2] college Negative: count from the right True
True
None
L[1:] ['college', 'MRCET!'] Slicing fetches sections
#
def area(radius):
List slices:
b = 3.14159 * radius**2
>>> list1=range(1,6)
return b
>>> list1
Parameters:
range(1, 6)
>>> print(list1) Parameters are passed during the definition of function while Arguments are passed during
the function call.
range(1, 6)
Example:
>>> list1=[1,2,3,4,5,6,7,8,9,10]
#here a and b are parameters
>>> list1[1:]
def add(a,b): #//function definition
[2, 3, 4, 5, 6, 7, 8, 9, 10] return a+b
>>> list1[:1]
#12 and 13 are arguments
[1] #function call
>>> list1[2:5] result=add(12,13)
print(result)
[3, 4, 5]
Output:
>>> list1[:6]
[1, 2, 3, 4, 5, 6] C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py
>>> list1[1:2:4] 25
[2]
>>> list1[1:8:2] Some examples on functions:
>>> x A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file.
[]
The variable defined inside a function can also be made global by using the global
statement.
>>> tuple1=(1,2,3,4)
def function_name(args):
>>> x=list(tuple1)
.............
>>> x
global x #declaring global variable inside a function
[1, 2, 3, 4] ..............
78 59
x = "global"
def f(): Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
print("x inside :", x)
Example:
f() >>> college=["mrcet","it","cse"]
print("x outside:", x)
>>> college.append("autonomous")
Output:
>>> college
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
['mrcet', 'it', 'cse', 'autonomous']
x inside : global
>>> college.append("eee")
x outside: global
>>> college.append("ece")
>>> college
# create a local variable
['mrcet', 'it', 'cse', 'autonomous', 'eee', 'ece']
def f1():
>>> college.pop()
y = "local"
'ece'
print(y)
>>> college
f1()
['mrcet', 'it', 'cse', 'autonomous', 'eee']
Output:
local >>> college.pop(4)
'eee'
If we try to access the local variable outside the scope for example,
>>> college
def f2():
y = "local" ['mrcet', 'it', 'cse', 'autonomous']
f2() >>> college.remove("it")
print(y) >>> college
Then when we try to run it shows an error, ['mrcet', 'cse', 'autonomous']
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py", line
6, in <module>
60 77
Output: print(y)
NameError: name 'y' is not defined
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py
10 The output shows an error, because we are trying to access a local variable y in a global
30 scope whereas the local variable only works inside f2() or local scope.
f3()
copy() Returns a copy of the list
Output:
count() Returns the number of elements with the specified value C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
globalglobal
local
extend() Add the elements of a list (or any iterable), to the end of the current list
In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
index() Returns the index of the first element with the specified value
both x and y.
After calling the f3(), the value of x becomes global global because we used the x *
insert() Adds an element at the specified position 2 to print two times global. After that, we print the value of local variable y i.e local.
pop() Removes the element at the specified position # use Global variable and Local variable with same name
x=5
remove() Removes the first item with the specified value
def f4():
reverse() Reverses the order of the list x = 10
print("local x:", x)
76 61
c Represents character of size 1 byte
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py i Represents signed integer of size 2 bytes
local x: 10
global x: 5 I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
Function Composition:
d Represents floating point of size 8 bytes
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
Creating an array:
FunctionB(FunctionA(x))
from array import *
Here x is the input for FunctionA and the result of that is the input for FunctionB. array1 = array('i', [10,20,30,40,50])
for x in array1:
Example 1: print(x)
#create a function compose2
Output:
>>> def compose2(f, g):
return lambda x:f(g(x)) >>>
>>> def d(x): RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/arr.py
return x*2 10
20
>>> def e(x): 30
return x+1 40
50
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5) # FunctionC(x)
12 Access the elements of an Array:
Accessing Array Element
In the above program we tried to compose n functions with the main function created.
We can access each element of an array using the index of the element.
Example 2:
from array import *
>>> colors=('red','green','blue') array1 = array('i', [10,20,30,40,50])
print (array1[0])
>>> fruits=['orange','banana','cherry'] print (array1[2])
>>> zip(colors,fruits)
62 75
Arrays can be declared in various ways in different languages. Below is an illustration. <zip object at 0x03DAC6C8>
Elements
>>> list(zip(colors,fruits))
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
[('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]
def calc_factorial(x):
Typecode Value """This is a recursive function
to find the factorial of an integer"""
b Represents signed integer of size 1 byte/td>
if x == 1:
B Represents unsigned integer of size 1 byte
return 1
else:
return (x * calc_factorial(x-1))
74 63
print(string.hexdigits)
num = 4 #print(string.whitespace)
print("The factorial of", num, "is", calc_factorial(num)) print(string.punctuation)
Output: Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec.py C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
The factorial of 4 is 24 =========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Strings: abcdefghijklmnopqrstuvwxyz
A string is a group/ a sequence of characters. Since Python has no provision for arrays, ABCDEFGHIJKLMNOPQRSTUVWXYZ
we simply use strings. This is how we declare a string. We can use a pair of single or
0123456789
double quotes. Every string object is of the type ‘str’.
0123456789abcdefABCDEF
>>> type("name") !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
<class 'str'>
>>> name=str()
>>> name Python String Module Classes
''
Python string module contains two classes – Formatter and Template.
>>> a=str('mrcet')
>>> a Formatter
'mrcet'
>>> a=str(mrcet) It behaves exactly same as str.format() function. This class becomes useful if you want to
>>> a[2] subclass it and define your own format string syntax.
'c'
>>> fruit = 'banana' Syntax: from string import Formatter
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The Template
expression in brackets is called an index. The index indicates which character in the
This class is used to create a string template for simpler string substitutions
sequence we want
Syntax: from string import Template
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character: Python arrays:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 Array is a container which can hold a fix number of items and these items should be of the
in the beginning of the string and working their way from -1 at the end. same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Slice out substrings, sub lists, sub Tuples using index.
Element− Each item stored in an array is called an element.
Syntax:[Start: stop: steps] Index − Each location of an element in an array has a numerical index, which is used
to identify the element.
Slicing will start from index and will go up to stop in step of steps.
Array Representation
Default value of start is 0,
64 73
Syntax: Stop is last index of list
String.startswith(„string‟)
And for step default is 1
Example:
>>> string="Nikhil Is Learning"
For example 1−
>>> string.startswith('N')
True str = 'Hello World!'
String module: H
This module contains a number of functions to process standard Python strings. In recent llo
versions, most functions are available as string methods as well.
llo World!
It’s a built-in module and we have to import it before using any of its constants and classes Hello World!Hello World!
Note: Example 2:
help(string) --- gives the information about all the variables ,functions, attributes and classes >>> x='computer'
to be used in string module.
>>> x[1:4]
Example:
'omp'
import string
print(string.ascii_letters) >>> x[1:6:2]
print(string.ascii_lowercase)
print(string.ascii_uppercase) 'opt'
print(string.digits) >>> x[3:]
72 65
'puter' ['Nikhil', 'Is', 'Learning']
>>> x[:5]
11. count()
'compu' count() method counts the occurrence of a string in another string Syntax:
>>> x[-1] String.count()
'r'
Example:
>>> x[-3:] >>> string='Nikhil Is Learning'
'ter' >>> string.count('i')
3
>>> x[:-2]
'comput' 12. find()
>>> x[::-2] Find() method is used for finding the index of the first occurrence of a string in another
string
'rtpo'
>>> x[::-1] Syntax:
String.find(„string‟)
'retupmoc'
Example:
Immutability: >>> string="Nikhil Is Learning"
It is tempting to use the [] operator on the left side of an assignment, with the intention of
>>> string.find('k')
changing a character in a string.
For example: 2
13. swapcase()
>>> greeting='mrcet college!' converts lowercase letters in a string to uppercase and viceversa
>>> greeting[0]='n'
Syntax:
TypeError: 'str' object does not support item assignment String.find(„string‟)
The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the original: Example:
>>> string="HELLO"
>>> greeting = 'Hello, world!' >>> string.swapcase()
>>> new_greeting = 'J' + greeting[1:] 'hello'
>>> new_greeting
'Jello, world!' 14. startswith()
Determines if string or a substring of string (if starting index beg and ending index end are
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator given) starts with substring str; returns true if so and false otherwise.
66 71
Example:
>>> string="Nikhil Is Learning" String functions and methods:
>>> string.istitle()
There are many methods to operate on String.
True
S.no Method name Description
8. isupper() 1. isalnum() Returns true if string has at least 1 character and all
isupper() returns true if string has characters that are in uppercase and false otherwise. characters are alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
Syntax: 3. isdigit() Returns true if string contains only digits and false
String.isupper() otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
Example: characters are in lowercase and false
otherwise.
>>> string="HELLO"
5. isnumeric() Returns true if a string contains only numeric
>>> string.isupper() characters and false otherwise.
True 6. isspace() Returns true if string contains only whitespace
characters and false otherwise.
7. istitle() Returns true if string is properly “titlecased” and
9. replace() false otherwise.
replace() method replaces all occurrences of old in string with new or at most max 8. isupper() Returns true if string has at least one cased character and all
occurrences if max given. cased characters are in uppercase
and false otherwise.
Syntax: 9. replace(old, new Replaces all occurrences of old in string with new
[, max]) or at most max occurrences if max given.
String.replace() 10. split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
Example: 11. count() Occurrence of a string in another string
>>> string="Nikhil Is Learning" 12. find() Finding the index of the first occurrence of a string
in another string
>>> string.replace('Nikhil','Neha') 13. swapcase() Converts lowercase letters in a string to uppercase
'Neha Is Learning' and viceversa
14. startswith(str, Determines if string or a substring of string (if starting index
10. split() beg=0,end=le beg and ending index end are given) starts with substring str;
split() method splits the string according to delimiter str (space if not provided) n(string)) returns true if so and false
otherwise.
Syntax: Note:
String.split() All the string methods will be returning either true or false as the result
Example: 1. isalnum():
>>> string="Nikhil Is Learning"
>>> string.split()
70 67
Isalnum() method returns true if string has at least 1 character and all characters are String.islower()
alphanumeric and false otherwise.
Example:
Syntax: >>> string="nikhil"
String.isalnum() >>> string.islower()
True
Example:
>>> string="123alpha" 5. isnumeric():
>>> string.isalnum() True isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are Syntax:
alphabetic and false otherwise. String.isnumeric()
Syntax: Example:
String.isalpha() >>> string="123456789"
>>> string.isnumeric()
Example: True
>>> string="nikhil"
>>> string.isalpha() 6. isspace():
True isspace() returns true if string contains only whitespace characters and false otherwise.
3. isdigit(): Syntax:
isdigit() returns true if string contains only digits and false otherwise. String.isspace()
Syntax: Example:
String.isdigit() >>> string=" "
>>> string.isspace()
Example: True
>>> string="123456789"
>>> string.isdigit() 7. istitle()
True istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise. Syntax:
String.istitle()
Syntax:
68 69