Unit - I
Unit - I
Unit - I
Ex: a=10
print(“Type of a:”,type(a))
b=“Hello”
print(“Type of b:”, type(b))
c=[ ]
print(“Type of c:”,type(c))
LISTS:
Lists in python are similar to arrays in C. However the list can contain data
of different types. The items stored in the list are separated with a comma (,)
and enclosed within square brackets [].We can use slice [:] operators to access
the data of the list.
l = [1, "hi", "python", 2]
print (l[2:])
print (l[0:2])
Tuple:
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The elements in the tuple are separated with a
comma (,) and enclosed in parentheses ().Whereas the list elements can be modified,
it is not possible to modify the tuple elements
t = (10,5.3,"hi", "python", 2)
print (t[1:]);
print (t[0:1]);
t[3]=77 #Error
String :
A string is represented by group of characters represented in quotation marks. In
python, strings are enclosed in single or double quotes. Multi-line strings can be
denoted using triple quotes, ''' or """. slicing operator [ :] can be used to retrieve
parts of string
s=‘hello’
str2=“welcome “
str3 =“ “ “ python ” ” ”
print(s[-4])
print(s[2:])
Dictionary:
Dictionary is an unordered collection of key-value pairs. It is generally used when
we have a huge amount of data. Dictionaries are optimized for retrieving data. We
must know the key to retrieve the value. In Python, dictionaries are defined within
braces {} with each item being a pair in the form key: value. Key and value can be
of any type.
d = {1:'value','key':2}
print(d[1])
print(d[‘key’]
Range:
The range data type represents a sequence of numbers. The numbers in the range are
not modifiable. Generally range is used for repeating a for loop for specific number
of times. To create a range of numbers, we can simply write
r=range(10) r=range(2,9)
r=range(1,10,2)
Set:
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered. it means the elements may
not appear in the same order as they are entered into the sets
a = {5,2,3,1,4}
print(a)
Type conversion:
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. It is done by using different type
conversion functions like int(), float(), complex and str() etc.
int():This function converts any data type to integer except complex type
>>>int(23.45) #23
>>>int(“44”) #44
>>>int(True) #1
float():This function is used to convert any data type to a floating point number
except complex type
>>>float(5) #5.0
>>>float(“10.5”) #10.5
>>>float(“10”) #10.0
>>>float(True) #1
Print(‘not x is ‘,not x)
40 and 50 50
0 and 50 0
40 or 50 40
0 or 50 0
Assignment operators
Assignment operators are used in Python to assign values to
variables. a = 5 is a simple assignment operator that assigns the value 5
on the right to the variable a on the left.
Multiple Assignments: Same value can be assigned to more than
one variable
Bitwise operators
Bitwise operators converts the operands data in the form of binary
format performs operations on the binary values and gives the result in
the form of decimal format.
Operator Meaning
& bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift
Ex: x=10 Output
Y=4 0
Print(x&y) 4
Print(x|y) -11
Print(x~y) 14
Print(x^y) 2
Print(x>>y) 40
Print(x<<y)
Special operators
Python language offers some special type of operators like the identity
operator or the membership operator.
Membership operators
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a
sequence(string, list, tuple, set and dictionary).
Operators Description
in Returns to true if it finds a variable in given sequence else false
Ex x=“hello ”
print( ‘h’ in x) #True
print(‘hel’ in x)
not in Returns to true if it does not find a variable in given sequence else false
Ex a=[1,2,3,4]
print(5 not in a)
print(5 in a)
Identity Operators
is and is not are the identity operators in Python.
They are used to check if two values(or variables) are located on the
same part of the memory. [used to compare memory locations of 2 objects]
Two variables that are equal does not imply that they are identical.
Operator Meaning
is Returns to true if variable on either side of operator
are referring to same object else false
Ex : a=10
b=10
x= a is b # True
argv sum.py 10 22
Block:
1. if:
Condition returns true then it executes the if block otherwise if block
execution is skipped.
output 1: output 2:
enter a positive number5 enter a positive number5
Given number is 1 digit number Given number is >=2 digit number
end end
3.elif:
elif block should be preceded by either if block or another elif
block.
elif block preceding block returns false then only control will go to
the elif block.
After reaching the control block to the elif block, if condition
returns true then only it will execute elif block.
Syntax:
if(con1):
stmt
elif(con2):
stmt
elif(con3)
stmt
else
stmt
Ex: print (“begin”)
x = input(“enter a positive number”)
i = int(x)
if i<10:
print (“given number is 1 digit number”)
elif i<100:
print (“given number is 2 digit number”)
elif i<1000:
print (“given number is 3 digit number”)
else :
print(“given number is >=4 digit number”)
print (“end”)
Output1: Output2:
begin begin
enter a positive number5 enter a positive number15
given number is 1 digit number given number is 2 digit number
end end
Nested If else:
if(cond1): if(cond1):
if(cond2): if(cond2):
stmt stmt
else: else:
stmt stmt
else: else:
if(cond3): stmt
stmt
else:
stmt
if(cond1):
if(cond1): stmt
if(cond2): else:
stmt if(cond2):
else: stmt
stmt else:
stmt
Looping( for, while nested loops)
While
In python, while loop is used to execute a block of statements
repeatedly until a given a condition is satisfied.
when the condition becomes false, the line immediately after the
loop in program is executed.
Syntax:
while (condition):
stmts
Ex: i =1
sum =0
while i<=100:
sum = sum+i
i = i+1
print (“sum”)
while loop with else
A while loop can have an optional else block as well. The else part is
executed if the condition in the while loop evaluates to False. The while
loop can be terminated with a break statement. In such case, the else part
is ignored. Hence, a while loop's else part runs if no break occurs and the
condition is false.
for i in range(10,20,2):
print(i)
s=“snist”
for i in s:
print(i)
for loop with else:
A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts. Break
statement can be used to stop a for loop. In such case, the else part is
ignored. Hence, a for loop's else part runs if no break occurs.
Ex:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Nested Loops: loop inside another loop.
syntax:
for var in sequence:
for var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
Control Statements(break , continue ,pass)
break
To interrupt the loop, to start a new iteration (one “round” of
executing the block), or to simply end the loop we use break.
Ex:
output
print("begin")
begin
i=1
p
for i in "python":
y
if i=='h':
t
break
end
else:
print(i)
print("end")
Ex:
print (“begin”)
i =1
while True:
print (“welcome”)
i =i+1
if i==5:
break Output
begin
else: welcome
print (“if else”) welcome
print (“end”) welcome
welcome
end
continue
It causes the current iteration to end, and to “jump” to the
beginning of the next.
It basically means “skip the rest of the loop body, but don’t end
the loop.”
Ex: output
print("begin") begin
i=1 p
for i in "python": y
if i=='h': t
continue o
else: n
print(i) end
print("end")
Pass
In Python programming, pass is a null statement. The difference
between a comment and pass statement in Python is that, while the
interpreter ignores a comment entirely, pass is not ignored.
Ex
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
File: File is a named location on Hard disk to store related information.
File is a chunk of logically related data or information which can be used
by computer programs.
File is used to permanently store data in a non-volatile memory(e. g. hard
disk)
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the file
are freed.
Types of Files
Text file : stores the data in the form of characters
Binary file: stores data in the form of bytes. These files can be used to store
text, images ,audio and video
In python, a file operation takes place in the following order
1.open a file
2.process file(read or write)
3.close file
Opening a file:
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
we use open() function along with two arguments, that accepts file name and the
mode
Syntax: fileObject=open(file_name,access_mode)
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
a+ Opens file in reading and appending mode. If file already exists, then append the
data at the end of existing file, else create a new file.
rb Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
Closing a file:
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not
rely on it to close the file.
file object. close( )