0% found this document useful (0 votes)
5 views97 pages

Python Programming

The document provides an introduction to Python programming, highlighting its open-source nature, ease of learning, and historical development. It covers key features like variable declaration, data types, mutable and immutable objects, and basic input/output functions. Additionally, it explains string manipulation, type conversion, and the use of comments in Python code.

Uploaded by

anjalisamrat333
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views97 pages

Python Programming

The document provides an introduction to Python programming, highlighting its open-source nature, ease of learning, and historical development. It covers key features like variable declaration, data types, mutable and immutable objects, and basic input/output functions. Additionally, it explains string manipulation, type conversion, and the use of comments in Python code.

Uploaded by

anjalisamrat333
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming

Python Programming
Introduction of Python:
 Python is free (Open Source) and easy to learn.
 Python is an interpreted, interactive, object-oriented programming language.
 Python is a widely used general-purpose, high level programming language.
 The Name Python is taken from the “Monty Python’s Flying Circus”, a BBC comedy
series.
 Python was conceived in the late 1980s.
 Implementation was started in December 1989 by Guido Van Rossum(Developer
of Python).
 In February 1991, Van Rossum published the python version 0.9.0
 Python Version 1.0 was released in January 1994.
 In October 2000, python 2.0 was introduced.
 Python 3.0(also called Python 3000 or Py3K) was released on December 3, 2008.
 January 1, 2020 was the day that for sunset of python 2.x, i.e. from this date python 2
is no longer supported. In other word we can say that the any improvement will not
done after that day, even if someone finds a security problem in it.
 Latest version of python as of today i.e. 17/06/2020 is Python 3.8.3(release date: 13 may
2020)
 Python 2.7.18 is the latest version of python 2.x series release date (20 April 2020)
What Are Python’s Technical Strengths?

1. Python is free and open source.


2. Python has object oriented feature.
3. Python is portable.
4. Automatic memory management feature.
5. Large set of library, Python has a large collection of library tools which help user to
build the application for different area e.g networking, scientific calculation, data
analysis, AI etc.

Introduction to Python Interpreter and program execution

2
Comment in python:
A comment is used to enhance the readability and understandability of the Program.
A comment starts with a hash character (#) , and ends at the end of the physical line.
Syntax: # some text
Here after the symbol # everything is ignored till the end of the physical
line. Note: Python does not have multiline comment facility.
For multiline comment we can use the following method: -
1. Put a ‘#’ symbol at the beginning of each and every line which you want use
as comment line.
For ex:
#print(“Hello”)
#print(“NIELIT PATNA”)
#print(“Patna”)
Note: in Python IDLE use the shortcut key Alt+3 for comment multiline or single
line, and use Alt+4 key to uncomment the commented line.

2. Put the text which you want to use as comment between double quote(“) three times.

3
For ex: “““ some text”””

3. Put the text which you want to use as comment between single quote(“) three
times. For ex: ‘‘‘ some text’’’

Variable Declaration in Python


 Variables are containers for storing data values
 Python variable declaration is different in a way that we don’t need to define the type of
the variable
 Only name of the variable is enough
 Variable is created whenever a value is assigned
For example, if we want to declare a new variable named test_variable
test_variable=5
test_variable= ”nielit”

here test_variable is created which stores 5 initially and then nielit


 Variables do not need to be declared with any particular type and can even change
type after they have been set
 Every variable declared in python is an object of some class

a=5

there is a built in function type to know the class of the declared variable type(a)
>>> class int
a is an object of class int

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (new, num, radius).
Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

4
Python’s Built-in Data types
SL. No. Type Data Types name
1 Numeric int, float, complex
2 Sequence list, tuple, range
3 Map dict
4 Set set, frozenset
5 Boolean bool
6 Binary bytes, bytearray, memoryview

Mutable and immutable objects


Every variable in python holds an instance of an object. There are two types of objects in python
i.e. Mutable and Immutable objects.
Whenever a variable is declared it is assigned a unique id. a=5
id(a)
>>>30572348
mutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words,
an immutable object can’t be changed after it is created.
Example:
a=5 b=a
id(b)==id(a)
id(b)==id(10)
if we increase a by 1 a=a+1
id(b) != id(a)
as a is an integer and it is an immutable object. once we try to modify a, the object to which a was assigned is
changed i.e a is now pointing to a new object 11. 10 is still the same or it is not modified. So b is still
pointing to the same object 10.

Immutable object doesn’t allow modification after creation


immutable objects
Immutable objects are the ones whose content or elements can be changes after their creation like
list, dictionary and set
Example:

5
a=[1,2,3] (a is a list)
b=a
id(b) ==id(a)
[Link](4)
a=[1,2,3,4]
b=[1,2,3,4]
as a is a mutable object it’s content can be changed after it’s creation at the same location. So
after append operation a is still pointing to the same object thus content of b is also changed.
Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.

Use of mutable objects is recommended when there is a need to change the size or content of the
object.

printing statements
print(): this function is used to display the output to the standard output device i.e. monitor.
syntax:
print(value,...,sep=' ',end='\n', file=[Link], flush=False)

Example-1: print(“hello”,”world”)
Output: hello world # default separator is space.

Example-2: print(“hello”,”world”,sep=’’)
Output: helloworld # in this output there no separator between hello and world, we can
put any character in sep value..

Example-3: print(“hello”,”world”,sep=’@’)

6
Output: hello@world

Example-4: print(“patna”)
Print(“Bihta”)
Output:

Patna
Bihta
In the above example you can see that print statement end with new line character. Because
default end character is \n.
Example-5:
print("patna",end='
') print("Bihta")
Output:
Patna Bihta
In the above example you can see that print statement end with space character. Because we
have given end= ” ”.
Example-6: In this example I will try to print some statement with variable value in
between.
A=10
B=20
print(“value of a=”,A,”and value of B=”,B)
Output: value of a=10 and value of B=20

7
How to take input from keyboard:
input(): This function is used to take input from the standard input device i.e. keyboard , this
function return the input taken from the keyboard in the form of string.
Syntax: input(prompt)
Prompt means you can give a message before the input is taken from the keyboard. Prompt is
optional.
Example-1:
n1=input();
print(n1)
Output: ram kumar #This is input given by the user using Keyboard.
ram kumar # after Hit the enter Key we will get this line.
Example-2: if we want some message before input
print(“enter a name”);
n1=input()
print(n1)
Output: enter a name: ram kumar
ram kumar
Example-3: if we want some message before input (Recommended method)
n1=input(“enter a name”)
print(n1)
Output: enter a name: ram
kumar ram kumar
Note: If we want the other than string input from the keyboard we need type conversion.

Type Conversion
The process of converting one data type to another data type is called Type casting or Type
Conversion.

There are two type of Type Conversion:

8
1. Implicit Type conversion
2. Explicit Type conversion

Implicit Type Conversion


When the type conversion i.e. converting one data type to another is performed automatically by
the python interpreter, then this type of conversion is referred to as implicit type conversion. In
this type of conversion there is no involvement of human.

Example-1: a=15
b=17.5
c=a+b
print(c)
Output: 32.5

In above example here data type of variable a is int and data type of variable b is float . and here
data type of c is also float, python interpreter automatically converts the type of int to float and
store it into variable c, so that no data will be loss.

Explicit Type conversion:

In this type of conversion user need to convert one data type to another required data type. With
the help of some in-built function i.e int(), float(), str().

Syntax: <required_datatype>(expression)
Example-1:

Output: 5 p=int(5.6)
print(p)
Example-1:

a=”23”
b=int(a)
print(b)
Output: 23 #Here type of variable b is int.

type(): This function return class type of any object which is passed to it.
Example-1:
a=10
b=type(a)
print(b)
9
Output: <class, ‘int’>

10
Example-2:
a=10.56
b=type(a)
print(b)
Output: <class, ‘float’>

id():this is an inbuilt function in Python, this function return the identity/address of the object,
identity is an integer value and it is unique.
Example-1:
a=10.56
b=id(a)
print(b)
output: 41172656

Some simple program using input and output function:

Question-1: write a python program to find the sum of first n natural number.

n=int(input("Enter value of n : "))

res=(n*(n+1))//2

print("Sum of first ",n," natural number=",res)

Output: Enter value of n :5


Sum of first 5 natural number=15

Question-2: write a python program to convert temperature from degree Celsius to


equivalent Fahrenheit.

c = float(input("Enter temperature value in degree Celsius: "))


f = (c * 9/5) + 32
print(c," degree celsius =",f," degree Fahrenheit")
Output: Enter temperature value in degree Celsius:10
10.0 degree celsius = 50.0 degree Fahrenheit

11
String Manipulation in Python.
A string is a sequence of character.
In python strings are enclosed by single quotation mark(' ') or double quotation mark(" ").
Example-1:
n1="NIELIT"
n2='NIELIT'
print(type(n1))
print(type(n2))
Output: <class 'str'>
<class 'str'>
In the above example String Assign in variable n1 is enclosed with single quote,
while string assign in variable n2 is enclosed with double Quote. And both are valid
string in python.
Example-2:
n1='a' #here a is a string of length
1. print(type(n1))
Output: <class 'str'>
In some programming language single character enclosed in single quote treated as character, but
in python single character enclosed in single quote is treated as string of length 1. In python there
are no concept of character data type.

=>In python for multiline string, we can use " " "some text" " " or ' ' 'some text' ' '

Example-3:

n1="""Welcome to Bihta
District of Patna"""
print(n1)
Output: Welcome to Bihta
12
District of Patna
In the above Example, a string is located in two line so, if we will have enclosed two-line string
with single or double quote it will generate an Error. That’s the reason we have put double quote
three times at the beginning and at the end of the string.

How to access a character in a string:


In a string if you want to access individual character then you need to specify the name of
variable in which string is stored after that you have to put index number in Square bracket( [ ] ).

Positive Index of first Character in a string is Zero(i.e 0 ) and index of last character is n-1, where
n is the length of a string.

In the above figure we can see that the negative index of first character in a string is –n and
negative index of last character is -1.

Note: We can access String Element using either positive index or negative index.
Example-1:
str1="PATNA"
print(str1[3])
print(str1[0])
print(str1[-5])
print(str1[-1])

13
Output: N
P
P
A
Slicing in a string:
If you want to access the range of string, we need slicing. Range of string is mentioned using
colon(i.e. :).

Example-1: if you were given a string “NIELIT PATNA” and you will asked to print only
NIELIT, code is as follows:-

str1="NIELIT PATNA"
print(str1[0:6])
Output: NIELIT
From the above Example you can observed that , if I give a range 0:6 then they will print string
from index 0 to index 6-1 i.e 5.
Example-2:
str1="NIELIT PATNA"
print(str1[7:12])
print(str1[0:12])
print(str1[7:])
print(str1[0:])
print(str1[:6])
print(str1[:12])
Output: PATNA
NIELIT PATNA
PATNA
NIELIT PATNA
NIELIT
NIELIT PATNA

14
Example-3:

str1="NIELIT PATNA"
print(str1[-12:-6])
print(str1[-5:])
print(str1[-12:])
print(str1[-5:len(str1)]) #here end index is length of string i.e.
12 print(str1[-5:12])
print(str1[:])
Output: NIELIT
PATNA
NIELIT PATNA
PATNA
PATNA
NIELIT PATNA

Iterating Through a string


Example-1:print all character of a string one by one using for loop.
Str1="NIELIT PATNA"
for i in Str1:
print(i)
Output: N
I
E
L
I
T

15
P
A
T
N
A
Example-2: Above program can also be written as follows:
str1="NIELIT PATNA"
for i in range(0,len(str1)): #Here len(str1) denotes length of string i.e 12.
print(str1[i])
Output: N
I
E
L
I
T

P
A
T
N
A

Membership Test using in and not in operator:


=>in operator, return True if this operator finds a variable in the specified sequence. otherwise it
returns False.
Example-1:
Str1="Nielit Patna"
test_string="Patna"

16
Result= test_string in Str1
print(Result)
Output: True

Example-2:

Str1="Nielit Patna"
test_string="bihta"
Result= test_string in Str1
print(Result)
Output: False

=>not in-this operator returns True if this operator does not find a variable in the specified
sequence. otherwise it returns False.
Example-1:
Str1="Nielit Patna"
test_string="bihta"
Result= test_string not in Str1
print(Result)
Output: True

Concatenation of Strings:
If you want to concatenate two or more than two strings, then we can use + operator. Result after
the concatenation is always stored in a new variable, because string is immutable. Immutable
means, we cannot modify the content after creation.

Example-1: str1="Nielit"
str2="Patna"
str3=str1+str2

17
print(str3)
Output: NielitPatna

Repetition of String:
If you want to repeat a particular string to specified number of times, then we can use asterisk
sign(i.e *) to repeat the string as many times as user want.

Example-1: str1="Bihta"
print(str1*3) #string Bihta will be repeated three times.
Output: BihtaBihtaBihta

Example-2: str1="Patna"
str2= str1*5
print(str2)
Output: PatnaPatnaPatnaPatnaPatna

=>Some Important Function which is very helpful in manipulation of strings.


len(): This function is used to find the length of a string in python.
Example-1:
str1="nielit patna"
string_length=len(str1)
print(string_length)
output:
12

lower(): This method is used to change the string into lowercase.


Example-1:
str1="NIeLIt"
print([Link]())
18
Output: nielit
upper(): This method is used to change the string into uppercase.
Example-1:
n1="nIelIT"
print([Link]())
Output: NIELIT
swapcase():This method is used to change the lower case letter to upper case and Upper Case
letter into lowercase.
Example-1:
s1="HeLLO World";
print([Link]())
Output: hEllo wORLD
replace(): This method is used to replace all occurrence of a string with another specified string.
Example-1:
s1="hello World";
print([Link]("h","z"))

Output: zello World

split(): This method is used to split the string into substring based on the separator.
Example-1:
s1="11-05-2020";
print([Link]("-"))
list=[Link]("-")
print(list[0])
Output: ['11', '05', '2020']
11

19
find(): This method is used to know the existence of particular substring in a string. This
method returns the lowest index in the string where substring is available and return -1 if
substring is not found in the given string.
syntax: [Link](substring,start,end)
In the above syntax start and end value are optional.
Example-1:
test="Nielit"
print([Link]('i'))
Output: 1
Example-2:
test="Nielit"
print([Link]('i',2))
Output: 4

Example-3:

test="Nielit"
print([Link]('N',2,5))
Output: -1

capitalize(): This method is used to convert the first letter of a string into uppercase. and the
remaining letter in lowercase.
Example-1:
test="nielit Patna Center"
print([Link]())
Output: Nielit patna center

title(): This method converts the first character of each word to upper case and remaining letter
to lowercase.
20
Example-1:

21
test="niElit paTna center"
print([Link]())
Output: Nielit Patna Center

format():this method used to concatenate elements within a string via positional formatting.
Example-1:
str1="Raju"
test="My Name is {}".format(str1)
print(test)
Output: My Name is Raju

Example-2:

n="raju"
test="my name is {1} and age={0}".format(n,30)
print(test)
Output: my name is 30 and age=raju

Example-3:

n="raju"
test="my marks is {0} and age={0}".format(30)
print(test)
Output: my marks is 30 and age=30

*********************End of Chapter -3*********************

22
Operator in python:
Following is the list of operator in Python:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators (Relational Operators)
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
1. Arithmetic operators:
Operator Description Example
Example1:
a=1
b=2
+ Addition
s=a+b
print(s)
Output: 3
Example1:
a=10
b=2
- Subtraction
s=a-b
print(s)
Output: 8
Example1:
a=5
b=2
* multiplication
s=a*b
print(s)
Output: 10
Example1:
a=3
Division, Result always in b=2
/
float. s=a/b
print(s)
Output: 1.5
Example1:
a=3
Floor division, similar to b=2
//
integer division in c. s=a//b
print(s)
Output: 1

23
Example1:
a=5
b=3
% Modulus s=a%b
print(s)
Output: 2

Example1:
a=3
b=2
** Power
s=a**b
print(s)
Output: 9

Important Notes about Modulus operator:


Modulo Operator: This operator yields the remainder when the first operand is divided by the
second operand.
 In case of modulo operator Absolute value of the result should be smaller than
the Absolute value second operand.
 The modulo operator always yield a result with the same sign as its second operand
(or zero).
 Modulus operator can be used for fraction number also.

Modulo Operator Example:


Example-1 Example-2 Example-3 Example-4 Example-5
A= -39%5 A=39%5 A=39%-5 A=5%39 A=-5%-39
print(A) print(A) print(A) print(A) print(A)
Output: 1 Output: 4 Output: -1 Output:5 Output:-5
Example-6 Example-7 Example-8 Example-9 Example-10
A=37%-36 A=36%-37 A=1%-22 A=22%-1 A=-22%7
print(A) print(A) print(A) print(A) print(A)
Output: -35 Output: -1 Output: -21 Output: 0 Output: 6
Example-11 Example-12
A=3%52 A=3.14%0.7
print(A) print(A)
Output: 3 Output: 0.34

24
Assignment operators
Operator Example
= a=9 i.e. value 9 is assigned to variable a .
a=3
a+=5
+=
i.e. a=a+5
if we print value of a then we get 8
a=30
a-=5
-=
i.e. a=a-5
if we print value of a then we get 25
a=3
a+=5
*=
i.e. a=a+5
if we print value of a then we get 8
a=30
a/=5
/=
i.e. a=a/5
if we print value of a, then we will get 6.0
a=7
a%=5
%= i.e. a=a%5
if we print value of a, then we will get 2

a=7
a//=5
//=
i.e. a=a//5
if we print value of a, then we will get 1
a=2
a**=3
**=
i.e. a=a**5
if we print value of a, then we will get 8
a=2
a&=3
&=
i.e. a=a&3
if we print value of a, then we will get 2
a=2
a|=3
|=
i.e. a=a|3
if we print value of a, then we will get 3
a=4
a^=5
^=
i.e. a=a^3
if we print value of a, then we will get 1

25
a=5
a>>=2
>>=
i.e. a=a>>2
if we print value of a, then we will get 1
a=5
a<<=2
<<=
i.e. a=a<<2
if we print value of a, then we will get 20

Comparison operators (Relational Operators)


Operator Description Example
Example-1:
a=2
b=3
== Equal to
c=(a==b)
print(c)
Output: False
Example-1:
a=2
b=3
!= Not equal to
c=(a!=b)
print(c)
Output: True
Example-1:
a=2
b=3
> Greater than
c=(a>b)
print(c)
Output: False
Example-1:
a=2
b=3
< Less than
c=(a<b)
print(c)
Output: True
Example-1:
a=2
b=3
>= Greater than or equal to
c=(a>=b)
print(c)
Output: False

26
Example-1:
a=2
<= Less than or equal to
b=3
c=(a<=b)

print(c)
Output: True

Note: Comparison operators will give the answer either True or False.

4. Logical operators
Operator Description Example
This operator returns True if both the operands
are true otherwise it returns False.
Example-1:
and Logical and
z=(5>2) and (3<7)
print(z)
Output: True
This operator returns True if either of the
operands are true otherwise it returns
False. Example-1:
or Logical or z=(5>2) or (3>7)
print(z)
Output: True, Because first operand is
true.
This operator returns True if operands are False
and return False if operands are True.
Example-1:
not Logical not z=not (5>2)
print(z)
Output: False, Because expression 5>2
return True.

5. Identity operators
Operator Description Example

27
This operator return True if Example-1:
the both operand are N1 = 91
referred to the same object. N2=91
res=N1 is N2
is print(res)
Output: True
In the above example N1 and
N2 are referred to the same
object.

This operator return True if Example-1:


the both operand not N1=99
referred to same object. N2=98
is not
res=(N1 is not N2)
print(res)
Output: True

6. Membership operators
Operator Description Example
This operator return true if Example-1:
value is exist in a sequence list1=[1,2,3,4]
in (i.e. list, tuple, string etc.) z=2 in list1
print(z)
Output: True
This operator return true if Example-1:
value not exist in a sequence list1=[1,2,3,4]
not in (i.e. list, tuple, string etc.) z=2 not in list1
print(z)
Output: True

7. Bitwise operators
Operator Description Example
&
|
^
~
<<
>>

28
Operators and their precedence
1. Operators in the same box have the same precedence.

2. Operators in the same box group left to right (Except for exponentiation, which groups
from right to left).

Conditional statements:
There are three type of conditional statement which is as follows-
1. if
29
2. if..else
3. if..elif..else

1. Syntax of if statement:

if test_expression:
statements

In if statement first of all test_expression will be evaluated, if test_expression is true then statements
inside if will be executed and if test_expression is false then statements inside if will not be
executed.

Example-1:

age=70
if age>=18:
print(“you are eligible for the Govt. Job”)
if age<18:
print(“you are not eligible for Govt. job”)
Output: you are eligible for the Govt. Job

2. Syntax of if..else statement:

if test_expression:
statements
--- -- -- ---
else:
statements

30
first of all, test_expression will be evaluated, if test_expression is true then statements inside if
will be executed and if test_expression is false then statements inside else will be executed.
Example-1:
if 3<2:
print("Patna")
else:
print("Bihta")
Output: Bihta

3.
if..elif..els
e syntax:
if test_expression1:
body of the if
elif test_expression2:
body of the elif
elif test_expression3:
body of the elif
-----------
-----------
else:
body of the else

Example-1: write a python program to display whether a given integer is positive, zero or
negative.

n=int(input("Enter a integer number: "));


if n>0:
print("Given number is positive")

31
elif n==0:

32
print("Given number is zero")
else:
print("Negative")
Output: Enter a integer number: 5
Given number is positive
Example-2: write a python program to display the grade of a student based on the
following criteria:
A. Display Grade S, if marks obtained by the student is greater than or equal to 85.
B. Display Grade A, if marks obtained by the student is greater than or equal to 75 but
less than 85.
C. Display Grade B, if marks obtained by the student is greater than or equal to 65 but
less than 75.
D. Display Grade C, if marks obtained by the student is greater than or equal to 55 but
less than 65.
E. Display Grade D, if marks obtained by the student is greater than or equal to 50 but
less than 55.
F. Display Grade Fail, if marks obtained by the student is less than 50.

Code:

Marks=int(input(“Enter marks obtained by you : ”)


If(marks>=85):
Print(“Grade-S”)
elif(marks>=75):
print(“Grade-A”)
elif(marks>=65):
print(“Grade-B”)
elif(marks>=55):
print(“Grade-C”)
elif(marks>=50):
print(“Grade-D”)
else:
print(“Grade-FAIL”)

33
Output: Enter marks obtained by you: 76
Grade-A

range() function: This function is used to generate a sequence of integer.


Syntax:
range(start_value, stop_value, step_size)
 All arguments must be an integer value(positive number or negative number and zero) i.e
we can not give the start_value , stop_value, and step_size to fraction ,string etc..
 Value of step_size can not be zero. i.e we can not put zero in place of step_size.
 Negative value is allowed for start_value or stop_value or step_size.
 start_value is optional, if we do not mention start value then by default start_value is zero.
 stop_value: this value is mandatory.
 step_size: this is optional, if you do not mention step_size then by default value of
step_size is 1.

There are three way to call a range function:


1. range(stop_value)
Ex: range(4)
here by default start_value=0 and step_size=1 and stop_value=4, and
sequence generated is 0 1 2 3
in the sequence we can see that the stop_value is not included in the ans. i.e. last generated
number should always be less than stop_value.

2. range(start_value,stop_value)
Ex: range(1,4)
here start_value=1 and by default step_size=1 and stop_value=4, and sequence
generated is 1 2 3

34
in the sequence we can see that the stop_value is not included in the ans. i.e. last generated
number should always be less than stop_value.

3. range(start_value,stop_value,step_size)
Ex: range(2,10,2)
here start_value=2 and step_size=2 and stop_value=10, and sequence generated will be
2 4 6 8
in the sequence we can see that the stop_value i.e. 10 is not included in the ans. i.e last number
should always be less than stop_value.

Note: range is commonly used in Loop.

Loop in python:
Loop is used to execute a statement or block of statement in repeated manner until the end
condition is met.

There are two type of loop in python:


1. for loop
2. while loop

1. for loop
Syntax of for Loop:
for iterating_variable in sequence:
statements

in the above syntax sequence can be range, list, tuple, set etc.

Example-1:

35
for i in range(5):
print(i)

Output: 0
1
2
3
4
Example-2: write a python program to print Hello World 5 times.
for i in range(5):
print(“Hello World”);
Output: Hello World
Hello World
Hello World
Hello World
Hello World

Example-3: write a python program to print all odd number between 1 and 10 where 1 and
10 is also included if it is odd number.
Code:
for i in range(1,11,2):
print(i);
Output: 1
3
5
7
9
In the above example in place 11, if we put 10 then we also get the same result.

36
Example-4: write a python program to print all even number between 1 and 10 where 1
and 10 is also included if it is even number.
Code:
for i in range(2,11,2):
print(i);
Output: 2
4
6
8
10

Example-5: write a python program to print all numbers between 1 and 30 which is
divisible by 5, where 1 and 30 is also included if it is divisible by 5.
Code:
for i in range(5,31,5):
print(i);
output: 5
10
15
20
25
30

(2) While loop:


Syntax of while loop
while expression:

37
statements

Example-1: write a python program to print Word BIHTA five times using while loop.
Code:
i=1
while (i<=5):
print("BIHTA")
i=i+1;
Output: BIHTA

BIHTA
BIHTA
BIHTA
BIHTA

Example-2: Write a python program to print all numbers between 1 and 30 which is
divisible by 5, where 1 and 30 is also included if it is divisible by 5 using while loop.

Code:

i=5
while (i<=30):
print(i)
i=i+5;
Output:

5
10
15
20

38
25

39
30
Example-3: Write a python program to find the factorial of a number using while loop.
Code:
n=int(input("enter a number whose factorial value you want: "))
i=1
fact=1
while (i<=n):
fact=fact*i
i=i+1
print("factorial of ",n," is =",fact)
Output: enter a number whose factorial value you want: 5
factorial of 5 is = 120

break statement in python:


break is used to come out from the inner loop i.e. from for or while loop.
Example-1:
for i in range(1,8):
if(i==5):
break
print(i)
Output:
1
2
3
4

Example-2:
i=1

40
while(i<=8):
if(i==5):
break
print(i)
i=i+1
Output: 1
2
3
4

continue statement in python:


when this statement occur interpreter skip the rest of the following statement and continue with
the next iteration.

Example-1:
for i in range(1,8):
if(i==5):
continue

print(i)
Output: 1

2
3
4
6
7
In the above example all number is printed except 5.
pass statement:
The pass statement does not do anything. It can be used when a statement is required
syntactically but you do not want to execute any statement.
For Example:

41
Example-1: write a python program to print all number between 10 to 15 except 12, using for
loop.
Code:
for i in range(10,16,1):
if(i==12):
pass
else:
print(i)
Output:
10
11
13
14
15

else statement in loop:


In python Loop statements may have an else clause, else clause will be executed when the loop
terminates through exhaustion of the Sequence (in for loop) or when the condition becomes false
(in while loop), else clause will not be executed when the loop is terminated using the break
statement.
Example-1:
for i in range(5):
print(i)
else:
print("Loop terminated Normally")
Output: 0
1
2
3

42
4
Loop terminated Normally
Example-2:
for i in range(5):
if(i==3):
break
print(i)
else:
print("loop terminated with break statement")
Output: 0
1
2
3
4
In this example we can see that the statement inside else clause will not be executed because
here loop is terminated with break statement.

43
Python Data Types
List in python
List is a datatype that allows you to store various type of data in it.
list in python can be created by just placing the elements inside a square bracket i.e. [], and
elements are separated with comma.
 List is mutable object.

Example of List is as
follows: Example-1:
List1=[1,2.5,'NIELIT']
print(List1)
print(type(List1)
Output: [1,2.5,'NIELIT']
<class 'list'>

 list may contain duplicate


value. Example-1:
List1=[1,2,3,4,2]
print(List1)
Output: [1,2,3,4,2]

 A list also have another list as an element (i.e. Nested list).


Example-1:
List1=[1,[10,11,12],3,4]
print(List1)
Output: [1,[10,11,12],3,4]

How to access element of a list.

44
Example-1:

List1=[2,4,6,8,10]
print(List1[0]) #output:2
print(list[-5]) #output:2
print(list[3]) #output:8
print(list[-2]) #output:2

Output: 2
2
8
2
How to slice a list in python:
With the help of slicing we can get the part of the list.
Slicing has the syntax is as follows-
[start : stop : steps]

Example-1:

list=[2,6,3,17,7,9,4,15,11,5]
print(list[1:5]) # print the value from index 1 to 4
print(list[0:4]) # print the value from index 0 to 3
print(list[-10:-6]) # print the value from index -10 to -7
print(list[2:])# print the value from index 2 to end of list
print(list[:4])# print the value from index 0 to 3
print(list[:])# print the value from index 0 to end of the
45
l
i
s
t
.

46
Output: [6, 3, 17, 7]
[2, 6, 3, 17]
[2, 6, 3, 17]
[3, 17, 7, 9, 4, 15, 11, 5]
[2, 6, 3, 17]
[2, 6, 3, 17, 7, 9, 4, 15, 11, 5]

How to re-assign a list value:


we can Replace a value of a list with new
element. Example-1:
list=[2,6,3,17,7,9,4,15,11,5]
list[0]=10
print(list)
Output: [10, 6, 3, 17, 7, 9, 4, 15, 11, 5]

Some important Function Used in the list Operation.


append(): This method used to add an element at the end of the
list. Example-1:
list=[2,4,6,8,10]
[Link](15)
print(list)
Output: [2, 4, 6, 8, 10, 15]

insert(): This method is used to insert the element at specified index.


syntax:
list_name.insert(index, value)
Example-1:
list=[2,6,3,17,7,9,4,15,11,5]
[Link](0,20)
print(list)
Output: [20, 2, 6, 3, 17, 7, 9, 4, 15, 11, 5]

47
count(): This method will tell us how many times a particular element appear in the list.
syntax:
list_name.count(value)
Example-1:
list=[2,6,3,6,7,9,4,6,11,5]
print([Link](6))
Output: 3

extend (): This method is used to append multiple element at a time, at the end of the
list. Example-1:
list=[1,2,3,4,5]
[Link]([6,7,8,9])
print(list)
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

remove(): This method removes the first matching element from the
list. Example-1:
list=[1,2,3,4,5,3,6]
[Link](3)
print(list)
Output: [1, 2, 4, 5, 3, 6]

reverse(): This method is used to reverse a list.


Example-1:
list=[1,2,3,4,5,3,6]

48
[Link]()
print(list)
Output: [6, 3, 5, 4, 3, 2, 1]

sort(): This method is used to sort the list. By default it sort the list in ascending
order. Example-1:
list=[11,2,13,5,4,23,6]
[Link]()
print(list)
Output: [2, 4, 5, 6, 11, 13, 23]

Example-2: Sort a list in Descending order.


list=[11,2,13,5,4,23,6]
[Link](reverse=True)
print(list)
Output: [23, 13, 11, 6, 5, 4, 2]

pop():This method can be remove the element from the specified position. If position is not
given, then This method is used to remove the last element from the list by default.
Example-1:
list=[11,2,13,5,4,23,6]
[Link]()
print(list)
Output: [11,2,13,5,4,23]

Example-2:
list=[11,2,13,5,4,23,6]

49
[Link](0)
print(list)
Output: [2,13,5,4,23]

index(): This method is used to find the index of given value which appear first in the
list. Example-1:
list=[11,2,13,5,4,23,6,13]
print([Link](13))
Output: 2

copy(): This method is used to copy the list, such that if we change in original list it does not
affect the copy of the list.
Example-1:
list1=[11,2,13,5,4,23,6,13]
list2=[Link]()
print(list2)
Output: [11,2,13,5,4,23,6,13]

Example-2: if you copy a list using assignment operator then if we change anything in original
list then copy of the list is also affected.
list1=[11,2,13,5,4,23,6,13]
list2=list1
[Link](100)
print(list1)
print(list2)
Output: [11, 2, 13, 5, 4, 23, 6, 13, 100]
[11, 2, 13, 5, 4, 23, 6, 13, 100]

clear(): This method is used to remove all the element from the list.

50
Example-1:

list1=[11,2,13,5,4,23,6,13]
[Link]()
print(list1)
Output: []

How to delete the list value without using remove() Method.:


We can also delete the particular list element using del
keyword. Example-1:
list=[2,6,3,17,7,9,4,15,11,5]
del list[0]
print(list)
Output: [6, 3, 17, 7, 9, 4, 15, 11, 5]
in the above example element with index 0 has been deleted from the list.
Keyword del can be used to delete list completely.
Example-1:
list=[2,6,3,17,7,9,4,15,11,5]
del list
print(list)
Output: <class 'list'>

How to access Nested List:


Example-1: if you want to print the element 12.
list=[1,[10,11,12],3,[5,6,7],10.5]
print(list[1][2])
Output: 12

51
Example-2: How to add element 13 just after the 12.
list=[1,[10,11,12],3,[5,6,7],10.5]
list[1].append(13)
print(list)
Output: [1, [10, 11, 12, 13], 3, [5, 6, 7], 10.5]

Example-3: How to add element 4 just before the element 5.


list=[1,[10,11,12],3,[5,6,7],10.5]
list[3].insert(0,4)
print(list)
Output: [1,[10,11,12],3,[4,5,6,7],10.5]

How to add the element into existing list at run time :


Example-1:
list=[]
for i in range(5):
newele=int(input(“Enter Element” ))
[Link](newele)
print(“Current list=”,list)
Output: Enter
Element 2
Enter Element 4
Enter Element 6
Enter Element 8
Enter Element 10

52
Current list= [2, 4, 6, 8, 10]

How to initialize a list with huge element.


syntax:
list=[expression for variable in sequence]
Example-1:
list=[i for i in range(2,21,2)]
print(list)
Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Example-2:

list=[i**2 for i in range(1,11,1)]


print(list)
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

list is a mutable object. therefore, list can be modified after creation.


Example-1:
list=[1,2,3]
print(id(list))
[Link](4)
print(id(list))
Output: 57860168
57860168
In the above example id of the list not changed even after modifying the list.

immutable object: which cannot be modified after creation. For ex:int,


float,tuple..etc. Example-1:

53
n=5
print(id(n))
n=n+5
print(id(n))
Output: 1641347056
1641347136
In the above example id of the list changed after modifying the value of n.

IMPRTANT PROGRAM BASED ON THE LIST:

Question-1: write a python program to find the sum of all element present in the list.
Answer:
list=[2,4,6,8,10]
sum=0
for i in list:
sum=sum+i
print(sum)
Output: 30

Question-2: Write a python program to find the big number among n integer number, value of n
is taken from the user.
Answer:
list=[2,6,3,17,7,9,4,15,11,5]
big=list[0]
for i in list:
if(i>big):
big=i
print("big number =",big)
Output: 17
54
Alternate Method:

list=[2,6,3,17,7,9,4,15,11,5]
big=list[0]
for i in range(10):
if(list[i]>big):
big=list[i]
print("big number =",big)
Output: 17

Question-3: Write a python program to delete the all occurrence of a particular element from the
list except first one.
Answer:
list=[1,2,3,4,3,5,3,6,3,7,3]
imp=[Link](3)
inc=0
for i in list:
if i==3 and inc!=imp:
[Link](inc)
inc=inc+1
print(list)
Output: [1,2,3,4,5,6,7]

Alternate Method:

list=[1,2,3,4,5,3,6,3,7]
count=[Link](3)
imp=[Link](3)
for i in range(count):
[Link](3)
[Link](imp,3)
55
print(list)
Output: [1,2,3,4,5,6,7]
Tuple in Python:
A Tuple is an immutable sequence (we cannot modify in any way once it is created). A tuple is
created by placing all the elements inside parentheses () (optional), separated by commas.
Tuple is ordered collection means we print the all element of a tuple in the same order in which
order we have created.
 Tuple can store duplicate value.
Example-1:
t=(1,2,3,2,1)
print(t)
Output: (1,2,3,2,1)

 Tuple can store element of different data types value.


Example-1:
t=(1,2,3.5,"hello")
print(t)
Output: (1, 2, 3.5, 'hello')

 In Tuple we can store Mutable and immutable datatype.


Example-1:
t=(1,2,3,[5,6,7],1)
print(t)
Output: (1,2,3,[5,6,7],1)

How to create an Empty


Tuple: Example-1:
t1=()

56
Print(type(t1))
Output: <class ‘tuple’>

How to create tuple with one element:


Example:
t1=(2) # this way we cannot create tuple with one element.
print(type(t1))
Output: <class 'int'>
In the above example we are trying to create tuple with one element but it is showing that the t1
is a integer not tuple so way of creating tuple with one element is wrong here.
Following is the correct way to create tuple with one element.
Example:
t1=(2,) # this way we can create tuple with one element.
print(type(t1))
Output: <class 'tuple'>

How to access tuple element:

 Tuple support indexing and slicing.

We can access tuple element with the help of index value(i.e. either positive index or
negative index)
Example-1:
t1=(1,2,3,4)
print(t1[0])

57
print(t1[3])
print(t1[-1])
print(t1[-4])

Output: 1
4
4
1

slicing in tuple:

Example-1:

t1=(5,10,2,8,12,7)
print(t1[0:5])
print(t1[0:len(t1)])
print(t1[0:])
print(t1[:])
print(t1[-5:])
print(t1[-5:len(t1)])
print(t1[-5:-3])

58
print(t1[:-1])
Output: (5, 10, 2, 8, 12)
(5, 10, 2, 8, 12, 7)
(5, 10, 2, 8, 12, 7)
(5, 10, 2, 8, 12, 7)
(10, 2, 8, 12, 7)
(10, 2, 8, 12, 7)
(10, 2)
(5, 10, 2, 8, 12)

Deleting a tuple:
We cannot delete tuple element, but we can delete tuple completely.

Example-1:
t1=(1,2,3,4)
del t1[0]
Output: TypeError: 'tuple' object doesn't support item deletion
In the above example I am trying to delete Tuple Element using del keyword but item is not
deleted from the tuple, because tuple is an Immutable Object.
Note: since tuple is an Immutable so we cannot insert, delete and update element of a tuple.

Example-2: How to delete tuple completely using del keyword.


t1=(1,2,3,4)
del t1
print(t1)
Output: NameError: name 't1' is not defined

Iterating through a tuple:

59
Example-1:

t1=(1,2,3,4)
for i in t1:
print(i)
Output: 1
2
3
4
Membership test in tuple:
Example-1:
t1=(1,2,3,4)
k=1 in t1
print(k)
Output: True
Example-2:
t1=(1,2,3,4)
k=10 in t1
print(k)
Output: false

Tuple unpacking:
Example-1:
t1=[1,2,3,4]
a,b,c,d=t1
print(a)
print(b)
print(c)

60
print(d)
Output: 1

2
3
4
Some Important Method used in Tuple Manipulation:
len(): This is used to find the length of tuple.
Example-1:
t1=(1,2,3,4,5)
k=len(t1)
print(k)
Output: 5

max(): This is used to find the element with maximum value.


Example-1:
t1=(1,2,3,4,5)
k=max(t1)
print(k)
Output: 5
Example-2:
t1=(1,2,3,4,5.8)
k=max(t1)
print(k)
Output: 5.8

61
Example-3:

t1=("apple","book",”ant”)
k=max(t1)
print(k)
Output: book
Example-4:

t1=(1,2,3,"a","b","c")
k=max(t1)
print(k)
Output: TypeError: '>' not supported between instances of 'str' and 'int'
From the above example we conclude that if tuple contains int/float and string then we cannot
find the max among element of tuple using max() method.
sum():This is used to find the sum of all element.
Example-1:
t1=(1,2,3,4,5)
k=sum(t1)
print(k)
Output: 15
count():This is used to find the number of occurrence of an
element. Example-1:
t1=(1,2,3,4,5,3,7,3)
k=[Link](3)
print(k)
Output: 3
index(): This Method is used to find the index value of an element.
Example-1:
t1=(1,2,3,4,5)
k=[Link](3)
print(k)
62
Output: 2

How to make a list from


tuple. Example-1:
t1=(1,2,3,4,5)
l1=list(t1)
print(l1)
Output: [1,2,3,4,5]

Repetition in
tuple: Example-1:
t1=(1,2,3,4,5)
print(t1*3)
Output: (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
Dictionary in python
Dictionary is a datatype in python, it is in the form of key value pair.
 key can't be repeated.
 value can be duplicated.
 if we mention same key again then old key will be overwritten.
 key is case sensitive.
 dictionary in python is a mutable.

Example-1:

d={"city":"patna","roll":12,"distt":"gaya"}
print(d)
print(type(d))
Output: {'city': 'patna', 'roll': 12, 'distt': 'gaya'}
<class 'dict'>

63
How to declare empty dictionary:
Example:
d={}
print(d)
print(type(d))
Output: {}

<class 'dict'>

How to access Dictionary


value: Example-1:
d={1:"patna","city":"delhi",3:"bihta"}
print(d[1])
print(d["city"])
print(d['city'])
Output: patna
delhi
delhi

How to update value in dictionary.


Example:
d={1:"patna","city":"delhi",3:"bihta"}
d[1]="gaya"
print(d)
Output: {1: 'gaya', 'city': 'delhi', 3: 'bihta'}

How to iterate through loop:


Example-1:

64
d={1:"patna","city":"delhi",3:"bihta"}
for i in d:
print(i)

Output: 1

city
3
Example-2:

d={1:"patna","city":"darbhanga",3:"bihta"}
for i in d:
print(d[i])
Output: patna
darbhanga
bihta

Example-3:

d={
1:"patna",
"city":"delhi",
3:"bihta"
}
for i in d:

print(d[i])
Output: patna
darbhanga
bihta
How to add element in dictionary:
Example:
65
d={1:"patna",2:"delhi",3:"bihta"}
print(d)
d[4]="goa"
print(d)
Output: {1:"patna",2:"delhi",3:"bihta",4: "goa"}

How to remove element from dictionary:


pop(): This method is used to remove an element from the dictionary based on key.
Example-1:
d={1:"patna",2:"delhi",3:"bihta"}
[Link](2)
print(d)
Output: {1:"patna",3:"bihta"}
Delete dictionary element using del keyword
Example:
d={1:"patna",2:"delhi",3:"bihta"}
del d[1]
print(d)
Output: {2:"delhi",3:"bihta"}

We can delete dictionary completely using del keyword.


Example:
d={1:"patna",2:"delhi",3:"bihta"}
del d
print(d)
Output: NameError: name 'd' is not defined
In this example, we are printing the dictionary after deletion of complete dictionary that’s why
we are getting an Error message.

66
popitem(): This method is used to delete a element randomly.
Example:
d={1:"patna",2:"delhi",3:"bihta"}
[Link]()
print(d)
Output: {1:"patna",2:"delhi"}

clear(): This method is used to delete all element from the dictionary.
Example:
d={1:"patna",2:"delhi",3:"bihta"}
[Link]()
print(d)
Output: {}

get(): This method is also used to get the value of a dictionary with the help of key.
Example:
d={1:2,3:4,5:6}
print(d[1])
print([Link](1))
Output: 2
2
len(): This method is used to find the length of
dictionary. Example:
d={1:2,3:4,5:6}
print(len(d))
Output: 3
values(): This method is used to get the all value of a dictionary in python.
Example:

67
d={1:2,3:4,5:6,7:8}
for i in [Link]():
print(i)
Output: 2
4
6
8

keys(): This method is used to get the all key of a dictionary.


Example:
d={1:2,3:4,5:6,7:8}
for i in [Link]():
print(i)
Output: 1
3
5
7

items(): This method is used to get the key, value pair of a dictionary.
Example:
d={1:2,3:4,5:6,7:8}
for a,b in [Link]():
print("key=",a,"value=",b)
Output: key= 1 value= 2
key= 3 value= 4
key= 5 value= 6
key= 7 value= 8

68
copy(): This Method is used to copy a dictionary.
Example:
d={1:2,3:4,5:6,7:8}
k=[Link]()
print(k)
Output: {1: 2, 3: 4, 5: 6, 7: 8}

update(): This method is used to add elements (one or more elements) to the Dictionary, if
newly element key already in the dictionary then key is updated with the New Value and if
newly element key is not in the dictionary then key and value is added into the dictionary .
Example:
d1={1:2,3:4,5:6,7:8}
d2={8:9,10:11}
[Link](d2)
print(d1)
Output: {1:2,3:4,5:6,7:8,8:9,10:11}

Membership Test in Dictionary Values:


Example-1:
d={1:2,3:4,5:6,7:8}
k=10 in [Link]()
print(k)
Output: False

Example-2:

d={1:2,3:4,5:6,7:8}
k=4 in [Link]()
print(k)

69
Output: True

Membership Test in Dictionary Keys:


Example-1:
d={1:2,3:4,5:6,7:8}
k=3 in [Link]()
print(k)
Output: True

Example-2:

d={1:2,"roll":4,5:6,7:8}
k="roll" in [Link]()
print(k)
Output: True

Question: write a python program to count the frequency of elements in a list using a dictionary.
Code:
list1=[1,2,3,5,7,1,2,1,9,4,2,1,5,7,2]
result_dict = {}
for list_element in list1:
result_dict[list_element] =[Link](list_element)

for key, value in result_dict.items():


print (key,"=>",value)
Output: 1 => 4
2 => 4

70
3 => 1
5 => 2
7 => 2
9 => 1
4 => 1

71
Python Function

Function

A function is a block of organized, reusable code that is used to perform a single, related action.
When you define a function, you specify the name and the sequence of statements. Later, you
can “call” the function by name. Functions provide better modularity for your application and a
high degree of code reusing. 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.
Let’s one example of a function call
>>> type(32)
The name of the function is type. The expression in parentheses is called the argument of the
function. The argument is a value or variable that we are passing into the function as input to the
function. The result, for the type function, is the type of the argument. It is common to say that a
function “takes” an argument and “returns” a result. The result is called the return value
The keyword def introduces a function definition. It must be followed by the function name and
the parentheses. Any input parameters or arguments should be placed within these parentheses.
The statements that form the body of the function start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal is the
function’s documentation string, or docstring. The code block within every function starts with
a colon ( : ) and is indented. The execution of a function introduces a new symbol table used for
the local variables of the function. More precisely, all variable assignments in a function store
the value in the local symbol table; whereas variable references first look in the local symbol
table, then in the local symbol tables of enclosing functions, then in the global symbol table, and
finally in the table of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a global statement), although they may be referenced. The
actual parameters (arguments) to a function call are introduced in the local symbol table of the
called function when it is called; thus, arguments are passed using call by value (where the
value is always an object reference, not the value of the object).
Why functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are
several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which makes
your program easier to read, understand, and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make
a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and
then assemble them into a working whole.
72
• Well-designed functions are often useful for many programs. Once you write and debug
one, you can reuse it.
Function Structure
def functioname (parameters):
"function_docstring"
function_suite
return [expression]
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 printme function –
Function definition is here
def print( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function print
("call user defined function")
print ("Again second call to the same function")
When the above code is executed, it produces the following result –
call user defined function
! Again second call to the same function
The return statement returns with a value from a function. return without an expression argument
returns None. Falling off the end of a function also returns None.
Pass by reference vs value
All parameters arguments in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function.
For example –
def change( mylist ):

73
"This changes a passed list into this function"
[Link]([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call change function
mylist = [10,20,30];
change( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result –
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.
def change( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
Now you can call change function
mylist = [10,20,30];
change( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function change. Changing mylist within the function does
not affect mylist. The function accomplishes nothing and finally this would produce the
following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Default Argument Values

74
The most useful form is to specify a default value for one or more arguments. This creates a
function that can be called with fewer arguments than it is defined to allow. A default argument
is an argument that assumes a default value if a value is not provided in the function call for that
argument. For example:
def default (name, location = ‘patna’ ):
"This prints a passed info into this function"
print "Name: ", name
print "location ", location
return;
# Now you can call default
function default
(‘NIELIT’ ,’Delhi’)
default( ‘NIELIT’)
When the above code is executed, it produces the following result −
Name: NIELIT location Delhi
Name: NIELIT location Patna
Variable argument
There are times when we don’t know how many arguments need to be passed to the function.
Like in case when we define a function for summing variables.
def add(a,b):
return a+b
add(10,15)
As we increase the number of variables to be passed to the function ( numbers to be added) we
have to increase the number of attributes in function definition. So in cased where numbers of
variables to passed may vary we can make use of variable length function.
In python variable arguments are defined using a keyword *args.
Let’s see an example of variable argument function
def add(*args):
return sum(args)
print(add((10,20,30,40,50))
output- 150
For printing arguments passed
75
def myfunc(*args):
for num in args:
print(num)
myfunc(10,20,30,40,50)
output-
10
20
30
40
50

**kwargs
The special syntax **kwargs in function definitions in python is used to pass a keyworded,
variable-length argument list. We use the name kwargs with the double star. The reason is
because the double star allows us to pass through keyword arguments (and any number of
them).
def myfun(**kwargs):
if 'city' in kwargs:
{
print('my institute is located in {}'.format(kwargs['city']))
}
else:
print("I don’t study anywhere")
myfun(institute='NIELIT', city='patna')
Output
My institute is located in patna
Inbuilt functions in Python
input()
76
This function first takes the input from the user and then evaluates the expression, which means
Python automatically identifies whether user entered a string or a number or list. If the input
provided is not correct then either syntax error or exception is raised by python.
val = input("Enter your value: ")
print(val)

Output
Enter your value: 10
>>>10
When input() function executes program flow will be stopped until the user has given an input.
The text or message display on the output screen to ask a user to enter input value is optional i.e.
the prompt, will be printed on the screen is optional. Whatever you enter as input, input function
convert it into a string. if you enter an integer value still input() function convert it into a string.
You need to explicitly convert it into an integer in your code using typecasting.
Code:

num = input ("Enter


number:") print(num)
name1 = input ("Enter name: ")
print(name1)
print ("type of number",
type(num)) print ("type of name",
type(name1)) Output
Enter number: 10
>>>10
Enter name: NIELIT
>>>NIELIT
type of number < class ‘str’>
type of name < class ‘str’>
String Function in python
Count
count() function in an inbuilt function in python programming language that returns the number
of occurrences of a substring in the given string.
The count() function has one compulsory and two optional parameters.
Mandatory parameter:
1) substring – string whose count is to be found.
Optional Parameters:
1) start (Optional) – starting index within the string where search starts.
2) end (Optional) – ending index within the string where search ends.

77
Return Value:
count() method returns an integer that denotes number of times a substring occurs in a given string.

a= “nielitpatna” print([Link](‘t’))

Output

>>> 2

find
The find() method returns the lowest index of the substring if it is found in given string. If it is not
found, then it returns -1.
[Link](sub,start,end)

sub : It’s the substring which needs to be searched in the given string. start :
Starting position where sub is needs to be checked within the string. end :
Ending position where suffix is needs to be checked within the string.
a= “nielitpatna”

print([Link](‘t’))

Output

>>> 5
replace

replace() is an inbuilt function in Python programming language that returns a copy of the string
where all occurrences of a substring is replaced with another substring.

Syntax :

[Link](old, new, count)


old – old substring you want to replace.
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with the new substring.
(Optional)
Return Value :
It returns a copy of the string where all occurrences of a substring is replaced with another
substring.

78
a=”nielitpatna”
[Link](“nielit”,”NIELIT”)
Output
>>>NIELITpatna
strip

strip() is an inbuilt function in Python programming language that returns a copy of the string
with both leading and trailing characters removed (based on the string argument passed).
Syntax:
[Link]([chars])
Parameter:
There is only one optional parameter in it:
chars - a string specifying
the set of characters to be removed.

If the optional chars parameter is not given, all leading


and trailing whitespaces are removed from the string.
Return Value:
Returns a copy of the string with both leading and trailing characters removed.
a=" nielit patna "
[Link]()
output
'nielit patna' (white spaces removed)

a="nielitpatnanielit"
[Link]("nielit")

Output

'patna'

partition

The partition() method splits the string at the first occurrence of the separator and returns a tuple
containing the part the before separator, separator and the part after the separator. Here
separator is a string which is given as the argument.
Syntax:
[Link](separator)

a=”nielitpatna”

[Link]('t')

79
Output

('nieli', 't', 'patna')

join

The join() method is a string method and returns a string in which the elements of sequence
have been joined by str separator.
Syntax:
string_name.join(iterable)

string_name: It is the name of string in which joined elements of iterable will be stored.

a=["nielit","patna","gov","in"]
b="."
b=[Link](a)

Output

>>> b
'[Link]'
Numeric inbuilt functions
max()
This function is used to compute the maximum of the values passed in its argument
Syntax:
max(a,b,c,..)

Parameters:
a,b,c,..: similar type of data.

Return Value:
Returns the maximum of all the arguments.
Exceptions:
Returns TypeError when conflicting types are compared.

max(10,20,30,40,50)

Output

50

min()
This function is used to compute the minimum of the values passed in its argument
Syntax:

80
min(a,b,c,..)
Parameters:
a,b,c,.. : similar type of data.
Return Value:
Returns the minimum of all the arguments.
Exceptions:
Returns TypeError when conflicting types are compared.
min(10,8,16,3,5)
Output :
3
pow
Python offers to compute the power of a number and hence can make task of calculating
power of a number easier.
pow(x,y) : computes x**y
pow(3,4)
output
81
round
Python provides an inbuilt function round() which rounds off to the given number of digits and
returns the floating point number, if no number of digits is provided for round off , it rounds
off the number to the nearest integer.
Syntax:
round(number, number of digits)
number - number to be rounded
number of digits (Optional) - number of digits up to which the given number is to be rounded.
If the second parameter is missing, then round() function returns:
if only an integer is given , as 15 , then it will round off to 15.

if a decimal number is given , then it will round off to the ceil integer after that if decimal value
has >=5 , and it will round off to the floor integer if decimal is <5.

print(round(15))
print(round(51.6))
print(round(51.5))
print(round(51.4))
Output:
15

81
52
52
51
When the second parameter is present, then it returns:
The last decimal digit till which it is rounded is increased by 1 when (ndigit+1)th digit is >=5 ,
else it stays the same.
# when the (ndigit+1)th digit is =5
print(round(2.665, 2))

# when the (ndigit+1)th digit is >=5


print(round(2.676, 2))

# when the (ndigit+1)th digit is <5


print(round(2.673, 2))
Output:
2.67
2.68
2.67
Recursive Function

Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant
approach to programming.

Following is an example of a recursive function to find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number.

def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-
1)) num = 6
print("The factorial of", num, "is", factorial(num))

Output

82
720
In the above example, factorial() is a recursive function as it calls itself. When we call this
function with a positive integer, it will recursively call itself by decreasing the number. Each
function multiplies the number with the factorial of the number below it until it is equal to
one. recursion ends when the number reduces to 1. This is called the base condition. Every
recursive function must have a base condition that stops the recursion or else the function
calls

83
Python File Handling

Introduction

Till now, we were taking the input from the console and writing it back to the console to interact
with the user. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the console,
and since the memory is volatile, it is impossible to recover the programmatically generated
data again and again.

However, if we need to do so, we may store it onto the local file system which is nonvolatile
and can be accessed every time. Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard disk). A file is
collections of lines of code, each line of code includes a sequence of characters. Each line of a
file is terminated with a special character, called End of Line characters like comma {,} or
newline character.

Python supports file handling and allows users to read and write along with other operations.
Python file handling operation are quite easy to implement. The key function while working with
files is open (). There are different ways of opening a file like read, write, append and create.
Arguments passed to open function are filename and mode. open() function returns a file object.
There are 4 modes in which can be opened:
‘r’- read-open a file for reading, it is default mode and if no arguments is passed by default file
will be read, it returns an error if no file is there
‘w’- write- open a file for writing, creates the file if it doesn’t exist
‘a’-append-opens a file for appending, creates the file if it doesn’t exist
‘x’- create-create the file , returns an error if file already exists
Python treats file differently as text or binary and this can be
specified ‘t’- text mode
‘b’- binary mode
Suppose there is a file “[Link]”, to open in read mode the file required syntax will be
a= open(“[Link]”,’r’)
To read a file using the python script, the python provides us the read() method. The read()
method reads a string from the file. It can read the data in the text as well as binary format.

The syntax of the read() method is given below.

[Link](<count>)
84
Here, the count is the number of bytes to be read from the file starting from the beginning of the
file. If the count is not specified, then it may read the content of the file until the end.

Now to read already opened file “[Link]” syntax will be


Print([Link]())
By default, read method real full content of the file, we can pass an argument to the read method
which specifies how many characters we want to read.
Print([Link](5))- to read 5 characters
Python facilitates us to read the file line by line by using a function readline(). The readline()
method reads the lines of the file from the beginning, i.e., if we use the readline() method two
times, then we can get the first two lines of the file.
Print([Link]())
Print([Link]())
One can also iterate through the lines
for i in a:
print(i)

close() method

Once all the operations are done on the file, we must close it through our python script using the
close() method. Any unwritten information gets destroyed once the close() method is called on
a file object.

We can perform any operation on the file externally in the file system is the file is opened in
python, hence it is good practice to close the file once all the operations are done.

Syntax for close() is given below

[Link]()
Write method

To write some text to a file, we need to open the file using the open method with one of the
following access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

a= open(“[Link]”,’w’)

85
[Link](“this is python course
material”) [Link](“it helps us to learn
python”) [Link]()
Write method will overwrite an existing content, if one wants to add to the existing content
append method should be used.
a= open(“[Link]”,’a’)
[Link](“append ore content”)
print([Link]())
tell method
The tell() method returns the current file position in a file stream.
syntax
[Link]()
Example
a=open(“[Link]”,’r’)
print([Link]())
print([Link]())
seek() method
Change the current file position
Syntax
[Link](offset )
Offset- A number representing the position to set the current file stream position
a=open(“[Link]”,’r’)
[Link](4)print([Link]())

Python os module

The os module provides us the functions that are involved in file processing operations like
renaming, deleting, etc.

Renaming the file

The os module provides us the rename() method which is used to rename the specified file to a
new name. The syntax to use the rename() method is given below.

86
rename(?current-name?, ?new-name?)

import os;
[Link]("[Link]","[Link]")
Removing the file

The os module provides us the remove() method which is used to remove the specified file. The
syntax to use the remove() method is given below.

import os;
[Link]("[Link]")
Deleting directory

The rmdir() method is used to delete the specified directory.

The syntax to use the rmdir() method is given below.

import os;
[Link]("new")

87
Python Module

Namespaces and Scope in Python

A namespace is a system to have a unique name for each and every object in Python. An object
might be a variable or a method. Python itself maintains a namespace in the form of a Python
dictionary. Let’s go through an example, a directory-file system structure in computers. Needless
to say, that one can have multiple directories having a file with the same name inside of every
directory. But one can get directed to the file, one wishes, just by specifying the absolute path to
the file.
Real-time example, the role of a namespace is like a surname. One might not find a single
“Alice” in the class there might be multiple “ankit” but when you particularly ask for “ankit
kumar” or “ankit mishra” (with a surname), there will be only one (time being don’t think of
both first name and surname are same for multiple students).
On the similar lines, Python interpreter understands what exact method or variable one is trying
to point to in the code, depending upon the namespace. So, the division of the word itself gives
little more information. Its Name (which means name, an unique identifier) + Space(which talks
something related to scope). Here, a name might be of any Python method or variable and space
depends upon the location from where is trying to access a variable or a method.
Types of namespaces :
When Python interpreter runs solely without and user-defined modules, methods, classes, etc.
Some functions like print(), id() are always present, these are built in namespaces. When a user
creates a module, a global namespace gets created, later creation of local functions creates the
local namespace. The built-in namespace encompasses global namespace and global namespace
encompasses local namespace.

88
Lifetime of a namespace :
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the
lifetime of that namespace comes to an end. Hence, it is not possible to access inner namespace’s
objects from an outer namespace.
Example:

# var1 is in the global namespace


var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local


# namespace
var3 = 7
As shown in the following figure, same object name can be present in multiple namespaces
as isolation between the same name is maintained by their namespace.

89
Scope of Objects in Python:

A scope defines the hierarchical order in which the namespaces have to be searched in
order to obtain the mappings of name-to-object(variables). It is a context in which variables
exist and from which they are referenced. It defines the accessibility and the lifetime of a
variable. Let us take a simple example as shown below:
a=10 (global variable)
def printer():
a=20 (scope is limited inside function printer)
return a
print(a)
>>> 10
Print(printer(a))
>>>20
Above program give different outputs because the same variable name a resides in different
namespaces, one inside the function printer and the other in the upper level.
How does python which variable user is referring to, in such cases python uses a rule called
LEGB rule.
The scopes are listed below in terms of hierarchy (highest to lowest):
 Local(L): Defined inside function/class

90
 Enclosed(E): Defined inside enclosing functions(Nested function concept)
 Global(G): Defined at the uppermost level
 Built-in(B): Reserved names in Python builtin modules
Let’s understand through an example
#Global
name="nielit"
def hello():
#enclosed
name= "patna"
def present():
print("hello"+name)
present()
hello()

Output
>>>hellopatna
Here as per LEGB rule present function searches for local variable name, as there is no
variable inside the function present so it searches for enclosed variable name. Present
function is enclosed in hello function and inside hello, variable name is defined and it’s
value is “patna” so when hello function is called this name is taken and we got the output
“hellopatna”.
If there is no variable defined in the enclosed function it will take global variable.
name="nielit"
def hello():
def present():
print("hello"+name)
present()
hello()

Output
“hellonielit”
Now if a local variable is defined
#Global
name="nielit" def
hello():
#enclosed
name= "patna"
def present():
#local Name=”python”
print("hello"+name)
present()
hello()

Output
“hellopython

91
Python modules
Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules. Individual modules can then be
cobbled together like building blocks to create a larger application.

There are several advantages to modularizing code in a large application:

 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
module, you’ll have a smaller problem domain to wrap your head around. This
makes development easier and less error-prone.
 Maintainability: Modules are typically designed so that they enforce logical boundaries
between different problem domains. If modules are written in a way that minimizes
interdependency, there is decreased likelihood that modifications to a single module will
have an impact on other parts of the program. (You may even be able to make changes
to a module without having any knowledge of the application outside that module.) This
makes it more viable for a team of many programmers to work collaboratively on a large
application.
 Reusability: Functionality defined in a single module can be easily reused (through an
appropriately defined interface) by other parts of the application. This eliminates the
need to duplicate code.
 Scoping: Modules typically define a separate namespace, which helps avoid collisions
between identifiers in different areas of a program. Functions, modules and packages
are all constructs in Python that promote code modularization.

Module

A module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code. modules written in Python are exceedingly
straightforward to build. All you need to do is create a file that contains legitimate Python code
and then give the file a name with a .py extension.

Suppose we write a python code and save it as [Link]. The code includes a function which
adds two numbers. Now this python code will act as a module.

def add(a,b):

return a+b

Now using import statement, we can use the module we just created.

Now write a user python code. In the code Import the module named addition, and call the add
function:

92
[Link]

Import addition

[Link](5,10)

Output:

15

The module can contain functions, as already described, but also variables of all types

[Link]

fruit= {‘name’: ‘mango’,’price’:40,’colour’:’green’}

Import module

a= [Link][‘colour’]

Output

Green

When interpreter executes import statement it searches [Link] in search path. A search path
is a list of directories that the interpreter searches before importing a module. Following is the
list of directories

 The directory from which the input script runs


 The list of directories contained in the PYTHONPATH environment variable, if it is set
 An installation-dependent list of directories configured at the time Python is installed

The resulting search path is accessible in the Python variable [Link], which is obtained from a
module named sys:

>>> import sys


>>> [Link]
['', 'C:\\Users\\nielit\\Documents\\Python\\doc', 'C:\\Python36\\Lib\\idlelib',
'C:\\Python36\\[Link]', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\
Python36', 'C:\\Python36\\lib\\site-packages']

Thus, to ensure your module is found, you need to do one of the following:

93
 Put [Link] in the directory where the input script is located or the current directory
 Modify the PYTHONPATH environment variable to contain the
directory where [Link] is located before starting the interpreter
 Put [Link] in one of the installation-dependent directories, which you may or may
not have write-access to, depending on the OS

The import Statement


Import statement is used for calling the module in user program.

import <module_name>

once the module is called, caller can use dot operator to access function or variables defined in
module. Simply function or variable will have no meaning in caller program.
Like in above example simply fruit has no meaning in caller program, whenever we have to
access any element defined in fruit we have to use [Link].
Several modules may be imported in a single statement seprated by commas
Import module 1[, module 2 [, ……]
from import statement
In most of the cases module contains multiple functions and variables. It can be used to import
specific function or variable from module
from module import name(fun)
It is possible to import more than one function at a time
From module import fun1, fun2
It is also possible to import all names from a module into the current namespace by using the
following import statement
from module import *
dir() function
it is a built-in function to list all the function names (or variable names) in a module. It returns a
list of defined names in a namespace
[Link]

fruit= {‘name’: ‘mango’,’price’:40,’colour’:’green’}

student={‘name’: ankit,’ roll no 1’, ‘marks’: 76}

[Link]

94
import mod
a= dir(mod)
print(a)
Output
[' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ',
' spec ', 'fruit', 'student']
call to dir() lists several names that are automatically defined and already in the namespace
when the interpreter starts. As new names are defined (fruit, student) they appear on subsequent
invocations of dir().
Python in built modules
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub-packages and sub-sub packages, and so on.
Math
For straightforward mathematical calculations in Python, you can use the built-in
mathematical operators, such as addition (+), subtraction (-), division (/), and multiplication (*).
But more advanced operations, such as exponential, logarithmic, trigonometric, or power
functions, are not built in. Python provides a module specifically designed for higher-level
mathematical operations: the math module.
You can import the Python math module using
>>> import math
The module includes several famous mathematical constants.

>>> [Link]

3.141592653589793

>>> [Link](12.76)

12

>>> [Link](121)

11.0

>>> [Link](3,4)

81.0

95
>>> [Link](10) (base e)

2.302585092994046

>>> [Link](10,10) (base 10)

1.0
Random
Python offers random module that can generate random numbers.
Random module contains useful functions
You can import the Python random module using
>>> import random
Random function in random module generates random number between 0 and 1

>>> [Link]()

0.5735828707967853
randint generates random integer between two numbers

>>> [Link](1,100)

61

96
97

You might also like