Python Material
Python Material
There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) which is installed when
you install the python software from http://python.org/downloads/
Working with Python
Source code you type is translated to byte code, which is then run by
the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
Source Byte code Runtime
hello world
python MyFile.py
Features of Python:
Ex:Lists,Dictionary,Sets
2. Immutable Data Types: Data types in python
where the value assigned to a variable cannot be
changed.
Ex:int,float,complex,Boolean,Strings,Tuples
1.int:
int, or integer, is a whole number, positive or negative, without decimals,
of unlimited length.
2.float:
float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
3.Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
4.Complex:
Complex number is represented by complex class. It is specified as
(real part) + (imaginary part)j.
Examples:
# Python program to demonstrate numeric
value a = 5
print("Type of a: ",
type(a)) b = 5.0
print("\nType of b: ",
type(b)) c = 2 + 4j
print("\nType of c: ", type(c))
Example:
Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)
Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)
Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)
Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)
4. Define a set? Illustrate any 5 functions/methods on set with
examples?
Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)
1.add():
The add() method adds an element to the set.
Syntax:
set.add(element)
Example:
>>> x={"mrcet","college","cse","dept"}
>>>x.add("autonomous")
>>> x
{'mrcet', 'dept', 'autonomous', 'cse', 'college'}
2.remove ():
The remove() method removes the specified element from the set.
Syntax:
set.remove(element)
Example:
>>> x={1, 2, 3, 'a', 'b'}
>>>x.remove(3)
>>> x
{1, 2, 'a', 'b'}
3. length():
The len() method is used to find the number of items or values present in a
set.
Syntax:
len(set)
Example:
>>> z={'mrcet', 'dept', 'autonomous', 'cse', 'college'}
>>>len(z)
5
4.clear:
The clear() method removes all items from the set.
Syntax:
set.clear()
Example:
>>> x={1,2,3,4,5,6,7}
>>>x.clear()
>>> x
set()
5.pop():
The pop() method removes a random item from the set. This method
returns the removed item.
Syntax:
set.pop()
Example:
>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>>x.pop()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}
Example:
1.isalnum():
The isalnum() method returns True if all the characters are alphanumeric,
meaning alphabet letter (a-z) and numbers (0-9), otherwise returns False.
Syntax:
string.isalnum()
Example:
>>> string="123alpha"
>>>string.isalnum()
True
2.isalpha():
The isalpha() method returns True if all the characters are alphabet letters
(a-z), otherwise returns False.
Syntax:
string.isalpha()
Example:
>>> string="nikhil"
>>>string.isalpha()
True
3.isdigit():
The isdigit() method returns True if all the characters are digits, otherwise
returns False.
Syntax:
string.isdigit()
Example:
>>> string="123456789"
>>>string.isdigit()
True
4.islower():
The islower() method returns True if all the characters are in lower case,
otherwise returns False.
Syntax:
string.islower()
Example:
>>> string="nikhil"
>>>string.islower()
True
5.isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-
9), otherwise returns False.
Syntax:
string.isnumeric()
Example:
>>> string="123456789"
>>>string.isnumeric()
True
6.isspace():
The isspace() method returns True if all the characters in a string are
whitespaces, otherwise returns False.
Syntax:
string.isspace()
Example:
>>> string=" "
>>>string.isspace()
True
7.istitle()
The istitle() method returns True if all words in a text start with a upper
case letter, and the rest of the word are lower case letters, otherwise
returns False.
Syntax:
string.istitle()
Example:
>>> string="Nikhil Is Learning"
>>>string.istitle()
True
8.isupper()
The isupper() method returns True if all the characters are in upper case,
otherwise returns False.
Syntax:
String.isupper()
Example:
>>> string="HELLO"
>>>string.isupper()
True
9.replace()
The replace() method replaces a specified old string with another new
string.
Syntax:
string.replace()
Example:
>>> string="Nikhil Is Learning"
>>>string.replace('Nikhil','Neha')
'Neha Is Learning'
10.split()
The split() method splits a string into a list according to delimiter string.
Syntax:
string.split()
Example:
>>> string="Nikhil Is Learning"
>>>string.split()
['Nikhil', 'Is', 'Learning']
11.count()
The count() method returns the number of times a specified value appears
in the string.
Syntax:
string.count()
Example:
>>> string='Nikhil Is Learning'
>>>string.count('i')
3
12.find()
The find() method searches the string for a specified value and returns the
position of where it was found.
Syntax:
string.find(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.find('k')
2
13.swapcase()
The swapcase() method is used for converting lowercase letters in a string
to uppercase letters and vice versa.
Syntax:
string.swapcase()
Example:
>>> string="HELLO"
>>>string.swapcase()
'hello'
14.startswith()
The startswith() method returns True if the string starts with the specified
value, otherwise returns False.
Syntax:
string.startswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.startswith('N')
True
15.endswith()
The endswith() method returns True if the string ends with the specified
value, otherwise returns False.
Syntax:
string.endswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.endswith('g')
True
Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)
1.append:
The append() method adds an item to the end of the list.
Syntax:
list.append(item)
Example:
>>> x=[1,5,8,4]
>>>x.append(10)
>>> x
[1, 5, 8, 4, 10]
2.extend:
The extend() method adds the specified list elements to the end of the
current list.
Syntax:
list.extend(newlist)
Example:
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
3.insert:
The insert() method inserts the specified value at the specified position.
Syntax:
list.insert(position,item)
Example:
>>> x=[1,2,4,6,7]
>>>x.insert(2,10)
>>> x
[1, 2, 10, 4, 6, 7]
4.pop:
The pop() method removes the item at the given index from the list and
returns the removed item.
Syntax:
list.pop(index)
Example:
>>> x=[1, 2, 10, 4, 6]
>>>x.pop(2)
10
>>> x
[1, 2, 4, 6]
5.remove:
The remove() method removes the specified item from a given list.
Syntax:
list.remove(element)
Example:
>>> x=[1,33,2,10,4,6]
>>>x.remove(33)
>>> x
[1, 2, 10, 4, 6]
6.reverse:
The reverse() method reverses the elements of the list.
Syntax:
list.reverse()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
7.sort:
The sort() method sorts the elements of a given list in ascending order.
Syntax:
list.sort()
Example:
>>> x=[10,1,5,3,8,7]
>>>x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
8.clear:
The clear() method removes all items from the list.
Syntax:
list.clear()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.clear()
>>> x
[]
9. length():
The len() method is used to find the number of items or values present in a
list.
Syntax:
len(list)
Example:
>>> x=[1,2,3,4,5]
>>> len(x)
5
7. Define a tuple? Illustrate any 3 functions/methods on tuple with
examples?
Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)
1.count():
The count() method returns the number of times a specified value appears
in the tuple.
Syntax:
tuple.count(value)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>x.count(2)
4
2.index():
The index() method searches the tuple for a specified value and returns the
position of where it was found.
Syntax:
tuple.index(value)
Example:
>>> x=(1,2,3,4,5,6)
>>>x.index(2)
1
3. length():
The len() method is used to find the number of items or values present in a
tuple.
Syntax:
len(tuple)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> len(x)
12
8. Define a dictionary? Illustrate any 5 functions on lists with
examples?
Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)
1.update():
The update() method inserts the specified items to the dictionary.
Syntax:
dictionary.update({“keyname”:”value”})
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.update({"cse":"dileep"})
>>> dict
{'brand': 'mrcet', 'model': 'college', 'year': 2004, 'cse': 'dileep'}
2.pop():
The pop() method removes the specified item from the dictionary.
Syntax:
dictionary.pop(keyname)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.pop("model"))
college
>>> dict
{'brand': 'mrcet', 'year': 2005}
3.items():
Returns all the items present in the dictionary. Each item will be inside
a tuple as a key-value pair.
Syntax:
dictionary.items()
Example:
dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
4.keys():
Returns the list of all keys present in the dictionary.
Syntax:
dictionary.keys()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.keys()
dict_keys(['brand', 'model', 'year'])
5.values():
Returns the list of all values present in the dictionary
Syntax:
dictionary.values()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.values()
dict_values(['mrcet', 'college', 2004])
6.Length():
The len() method is used to find the number of items present in a
dictionary.
Syntax:
len(dictionary)
Example:
>>>x={1: 1, 2: 4, 3: 9, 4: 16}
>>> len(x)
>>> 4
7.clear():
The clear() method removes all the elements from a dictionary.
Syntax:
dictionary.clear()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.clear()
>>> dict
{}
8.get():
The get() method returns the value of the item with the specified key.
Syntax:
dictionary.get(“keyname”)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.get("model")
'college'
Operators in Python:
Python has seven types of operators that we can use to perform different
operation and produce a result.
1.Arithmetic operator
2.Relational operators
3.Assignment operators
4.Logical operators
5.Membership operators
6.Identity operators
7.Bitwise operators
1.Arithmetic operators:
Arithmetic operators are used to perform different mathematical
operations between the operands.
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
// Floor division)
℅ (Modulus)
** (Exponentiation)
3.Assignment operators:
In Python, Assignment operators are used to assigning value to the
variable. Assign operator is denoted by = symbol. For example, name =
"Raju" here, we have assigned the string literal „Raju‟ to a variable name.
= (Assign)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
**= (Exponentiation and assign)
//= (Floor-divide and assign)
4.Logical operators:
Logical operators are useful when checking a condition is true or not.
Python has three logical operators. All logical operator returns a boolean
value True or False depending on the condition in which it is used.
5.Membership operators:
Membership operators are used to check for membership of objects in
sequence, such as string, list, tuple. It checks whether the given value or
variable is present in a given sequence. If present, it will return True
otherwise False.
6.Identity operators:
Identity operators are used to check whether the value of two variables are
same or not. If same, it will return True otherwise False.
7.Bitwise Operators:
In Python, bitwise operators are used to performing bitwise operations on
integers. To perform bitwise, we first need to convert integer value to
binary (0 and 1) value.
The bitwise operator operates on values bit by bit, so it‟s called bitwise. It
always returns the result in decimal format.
1.if statement:
if statement flowchart:
In conditional statements, The if statement is the simplest form.
It takes a condition and evaluates to either True or False.
If the condition is True, then the True block of code will be executed, and
if the condition is False, then the block of code is skipped, and the
controller moves to the next line.
Example
a=int(input('Enter any no'))
if(a>25):
print('Given no is greater than 25')
Example
n=int(input('Enter any no'))
if(n%2==0):
print('given no is even')
else:
print('given no is odd')
1.while loop
2.for loop
1.while loop:
It is used when a group of statements are executed repeatedly until the
specified condition is true.
It is also called entry controlled loop.
The minimum number of execution takes place in while loop is 0.
Syntax:
while(condition):
statement 1
statement 2
statement n
Example
i=1
print("The nos from 1 to 10 are ")
while(i<=10):
print(i)
i=i+1
2.for loop:
In Python, the for loop is used to iterate over a sequence such as a list,
string, tuple, other iterable objects such as range.
With the help of for loop, we can iterate over each item present in the
sequence and executes the same set of operations for each item. Using a
for loop in Python we can automate and repeat tasks in an efficient
manner.
Syntax:
for var in range/sequence:
statement 1
statement 2
statement n
Example
for i in range(1,11,1):
print(i)
12. Explain different types of unconditional statements in python
with example programs?
Example:
for i in range(1,6,1):
if(i==4):
break
printf(i)
Example:
for i in range(1,6,1):
if(i==4):
continue
printf(i)
3.pass statement:
The pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass
is not ignored.
The pass statement is generally used as a placeholder i.e. when the user
does not know what code to write. So user simply places pass at that
line.
pass is just a placeholder for functionality to be added later. Sometimes,
pass is used when the user doesn‟t want any code to execute.
Syntax:
pass
Example:
a=10
b=20
if(a>b):
pass
Keywords in Python:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or
any other identifier.
They are used to define the syntax and structure of the Python
language.
All the keywords except True, False and None are in lower
case and they must be written as it is.
Python Comments
Example
#This is a comment
print('Hello')
Multi-line comments
Example
"""This is also a
Perfect example of
multi-line comments"""
variable = input(prompt)
Example:
Example
>>>a = 5
Python Variables/Identifiers
The rules for writing a variable name is same as the rules for
writing identifiers in Python. We don't need to declare a
variable before using it. In Python, we simply assign a value
to a variable and it will exist.
Example
a=5
b = 3.2
c = "Hello“
variables simultaneously.
For example :
a = b = c = 10
Here, an integer object is created with the value 10, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables.
For example :
a,b,c = 1,2,"mrcet”
Here, two integer objects with values 1 and 2 are assigned to variables
a and b respectively, and one string object with the value "mrcet" is
assigned to the variable c.
17. How are type conversions done in python? Illustrate with
suitable examples?
1.int():
Examples:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
2.float():
We can use float() function to convert other type values to float type.
Examples:
3.str():
We can use this method to convert other type values to str type.
Examples:
Programs
1. Program for Prime numbers
n=int(input("Enter any number:"))
for i in range(1,n+1,1):
if (i>1):
for j in range(2,i,1):
if(i%j==0):
break
else:
print(i)
18. Program for print name of the day of a weak using elif statement
n=int(input("Enter n value:"))
if(n==1):
print("sunday")
elif(n==2):
print("monday")
elif(n==3):
print("tuesday")
elif(n==4):
print("wedensday")
elif(n==5):
print("thursday")
elif(n==6):
print("friday")
elif(n==7):
print("saturday")
else:
print("Enter in the number in range of(1,7):")
19. Program for sum of n natural numbers
n=int(input("Enter any number"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print("Sum of n natural numbers is ",sum)