Python Programming Unit-II
Python Programming Unit-II
There are various data types in python. Some of the important types are
Numeric types:
Integers:
Integers are whole numbers which can be either positive or negative without any
decimal point of unlimited length. Integers must be written without commas.
The most common implementation of the int data type in many programming
languages consists of the integers from -2,147,483,648 (-2 31 ) to 2,147,483,647
(231 -1).
However, the magnitude of a Python integer is much larger and is limited only by
the memory of your computer.
computer’s memory limits not only the range but also the precision that can
be represented for real numbers. Values of the most common implementation of
Python’s float type range from approximately -10308 to 10308 and have 16 digits of
precision.
Page 1
Complex numbers:
Complex number is a number that can be expressed in a form a+bj where a is real
part and b is imaginary part and ‘j’ or ‘J’ as an imaginary unit.
3+4j 3.14j 10.j 10j .001j 1e100j 3.14e-10j
Booleans:
Python has explicit Boolean data type called bool with the values True and False
available as preassigned built-in names. Internally, the names True and False are
instances of bool, which in turn a subclass of built-in integer type int.
>>> type(True)
<class ‘bool’>
>>>x=True
>>> isinstance(x,int)
True
Strings:
Python can also manipulate strings, which can be enclosed in single quotes ('...') or
double quotes ("...") with the same result .
a = "Hey"
b = "Hey there!"
c = "742 Evergreen Terrace"
d = "1234"
e = "'How long is a piece of string?' he asked"
f = "'!$*#@ you!' she replied"
note:
Double-quoted strings are used for composing strings that contain single quotation
marks or apostrophes and use single-quote marks to enclose a string literal that
contains double quotes as part of the string
Ex:
>>> print("I'm using a single quote in this string!")
I'm using a single quote in this string!
Page 2
>>> print('Your assignment is to read "Hamlet" by tomorrow')
Your assignment is to read "Hamlet" by tomorrow
The individual characters of a string can be accessed using indexing and a range of
characters can be accessed using slicing. The index must be an integer and Index
starts from 0. Python also allows negative indexing for its sequences. The index of
-1 refers to the last item, -2 to the second last item and so on.
Trying to access a character out of index range will raise an IndexError. We can't
use float or other types, this will result into TypeError.
Ex:
Page 3
Strings are immutable. This means that elements of a string cannot be changed
once it has been assigned. We can simply reassign different strings to the same
name.
>>> my_string='python'
>>> my_string[5]='a' # results in TypeError: 'str' object does not support
item assignment
We cannot delete or remove characters from a string. But deleting the string
entirely is possible using the keyword del.
>>> my_string='python'
>>> print(my_string)
python
>>> del my_string[1] #results in TypeError: 'str' object doesn't support item
deletion
Operations on strings:
The following are some of the operations that can be performed over strings
Ex3:
>>> 'py' 'thon'
'python'
Page 4
>>>str = 'python programming'
[]
Returns the character at the given >>>print( str[0])
index p
String formatting:
Python uses C-style string formatting to create new, formatted strings. The string
formatting operator "%" is used to perform string formatting. The format specifiers
like %s ,%d etc, can be used
Ex1:
Ex2:
>>> name = "John"
>>> age = 23
>>> print("%s is %d years old." % (name, age))
John is 23 years old.
Ex3:
>>> print("my name is %s and my age is %d"%('pavan',21))
my name is pavan and my age is 21
Page 5
The list of complete set of symbols which can be used along with % are given
below.
Page 6
String formatting using format( ) :
string.format(str1, str2,...)
The string itself contains placeholders {}, in which the values of variables
are successively inserted.
Ex:
>>>name="Bill"
>>>age=25
>>>"My name is {} and I am {} years old.". format (name, age)
'My name is Bill and I am 25 years old.'
Ex:
>>>myStr = "My name is {} and I am {} years old."
>>>myStr.format(name, age)
'my name is Bill and I am 25 years old.'
String methods:
capitalize( ):
returns the capitalized version of the string i.e., make the first character have
upper case and the rest lower case
title( ):
Return a title cased version of the string, i.e., all words start with uppercase and
rest of the characters in words are in lowercase.
lower( ):
Return a copy of the string converted to lowercase.
Page 7
upper( ):
swapcase( ):
Return a copy of the string with uppercase characters converted to lowercase
and vice versa.
Return the lowest index in the string where substring sub is found, such that sub
is contained within the string in the range [start:end]. Optional arguments start and
end are interpreted as in slice notation. Return -1 on failure.
Return the highest index in the string where substring sub is found, such that
sub is contained within the string in the range [start:end]. Optional arguments start
and end are interpreted as in slice notation. Return -1 on failure
Return the lowest index in the string where substring sub is found, such that sub
is contained within the string in the range [start:end]. Optional arguments start and
end are interpreted as in slice notation. Raises ValueError when the substring is
not found.(same as find but return value on failure different)
Return the highest index in the string where substring sub is found, such that
sub is contained within the string in the range [start:end]. Optional arguments start
and end are interpreted as in slice notation
Page 8
replace(old, new[, count]):
Return a copy of S with all occurrences of substring old replaced by new. If the
optional argument count is given, only the first count occurrences are replaced.
Ex:
split(sep=None, maxsplit=-1) :
Return a list of the words in the string, using sep as the delimiter string. If maxsplit
is given, at most maxsplit splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed from the result.
Ex:
>>> var='This is a good example'
>>> var.split(sep=' ')
['This', 'is', 'a', 'good', 'example']
>>> var.split(' ')
['This', 'is', 'a', 'good', 'example']
>>> var.split(sep='@')
['This is a good example']
>>> var.split(sep=' ',maxsplit=2)
['This', 'is', 'a good example']
Page 9
join(iterable):
Ex:
>>> list1=['This', 'is', 'a', 'good', 'example']
>>> list1
['This', 'is', 'a', 'good', 'example']
>>> string=" "
>>> string.join(list1)
'This is a good example'
istitle( ):
Ex:
>>>string=”this is a good example”
>>>string.istitle( )
False
Operators:
Operators are special symbols in Python that carry out arithmetic or logical
computation.
Types of Operator:
Page 10
Arithmetic Operators:
These operators are used perform arithmetic operations like addition, substraction,
multiplication, division etc. the various arithmetic operators are
Operato
r Meaning Example
>>>x,y=20,10
+ Add two operands or unary plus >>>x+y
30
>>>x,y=20,10
Subtract right operand from the left or unary
- >>>x-y
minus
10
>>>x,y=20,10
>>>x*y
* Multiply two operands
200
>>> x,y=20,10
Divide left operand by the right one (always
/ >>> x/y
results into float)
2.0
>>> x,y=20,10
Modulus - remainder of the division of left
% >>> x%y
operand by the right
0
>>> x,y=20,10
Exponent - left operand raised to the power
** >>> x**y
of right
10240000000000
Page 11
Comparison (Relational) Operators:
Operato
r Meaning Example
>>> x,y=20,10
Greater that - True if left operand is greater >>> x>y
> than the right True
>>> x,y=20,10
Less that - True if left operand is less than >>> x<y
< the right False
>>> x,y=20,10
>>> x==y
== Equal to - True if both operands are equal False
>>> x,y=20,10
>>> x!=y
!= Not equal to - True if operands are not equal True
>>> x,y=20,10
Greater than or equal to - True if left operand >>> x>=y
>= is greater than or equal to the right True
>>> x,y=20,10
Less than or equal to - True if left operand is >>> x<=y
<= less than or equal to the right False
Page 12
Assignment operators:
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Page 13
Logical operators:
Operato
r Meaning Example
>>> x=True
>>> y=False
>>> x and y
and True if both the operands are true False
>>> x=True
>>> y=False
>>> x or y
or True if either of the operands is true True
>>> x=True
>>> y=False
>>> not y
not True if operand is false (complements the operand) True
Bitwise operators:
Page 14
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).In a dictionary we can only
test for presence of key, not the value.
Operator Description Example
not in Evaluates to true if it does not finds a >>> 'py' not in 'python'
variable in the specified sequence and
false otherwise. False
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. Two variables that
are equal does not imply that they are identical.
Operator Description Example
>>> id(x)
1631445808
>>> id(y)
1631445808
>>> x is y
True
Page 15
is not Evaluates to false if the variables on either >>> x=[1,2,3,4]
side of the operator point to the same
object and true otherwise. >>> y=[1,2,3,4]
>>> id(x)
38243464
>>> id(y)
38279328
>>> x is not y
True
The following table summarizes the operator precedence in Python, from lowest
precedence (least binding) to highest precedence (most binding). Operators in
the same box have the same precedence. Unless the syntax is explicitly given,
operators are binary. Operators in the same box group left to right (except for
exponentiation, which groups from right to left).
Operator Description
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
Comparisons, including
in, not in, is, is not, <, <=, >, >=, !=, =
membership tests and identity
=
tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
Page 16
Operator Description
<<, >> Shifts
+, - Addition and subtraction
Multiplication, matrix
*, @, /, //, % multiplication, division, floor
division, remainder
Positive, negative, bitwise
+x, -x, ~x
NOT
** Exponentiation
await x Await expression
x[index], x[index:index], x(arguments. Subscription, slicing, call,
..), x.attribute attribute reference
Binding or tuple display, list
(expressions...), [expressions...], {key:
display, dictionary display, set
value...},{expressions...}
display
Loops :
While loop:
while expression:
block1 of statements
else:
block2 of statements
statement-x
Here expression is any valid expression. Block of statements can contain one or
more statements with uniform indentation. the else clause in while loop is
optional.The while statement repeatedly execute block1 of statements as long as
the expression is true. If the expression is false then the block2 of statements in the
else clause (if present ) gets executed and loop terminates by transferring the
control to the next immediate statement of while loop i.e., statement –x.
Page 17
While loop can be terminated with a break statement. In such case, the else
part is also ignored. Hence a while loop’s else clause runs if no break occurs and
condition is false.
Ex1:
output:
python programming
python programming
python programming
else clause statement is executed
end of program
Ex2:
Page 18
output:
python programming
python programming
end of program
for loop:
The for loop is used to iterate over the elements of a sequence (such as a string,
tuple or list) or other iterable object.
Block of statements can contain one or more statements with uniform indentation.
the else clause in for loop is optional. If a sequence contains an expression list, it is
evaluated first. Then, the first item in the sequence is assigned to the iterating
variable iterating_var. Next, the block1 statements gets executed. Each item in the
list is assigned to iterating_var, and the block1 statements gets executed until the
entire sequence is exhausted.
After the entire sequence is exhausted, the block2 of statements in the else clause
(if present) gets executed and loop terminates by transferring the control to the next
immediate statement of for loop i.e., statement –x
for loop can be terminated with a break statement. In such case, the else part is also
ignored. Hence a for loop’s else clause runs if no break occurs and sequence is
exhausted.
Page 19
Ex1:
numbers = [11,33,55,39,55,75,36,21,23,41,13]
print("exit")
output:
Ex2:
write a program that prints out the decimal equivalents of 1/2, 1/3, 1/4, . . . ,1/10
sol:
#program that prints out the decimal equivalents of 1/2, 1/3, 1/4, . . . ,1/10
for i in range(2,11):
print("decimal equivalent of 1/",i, "is" ,1/i)
output:
Page 20
Ex3:
Sol:
str="cse"
print("the characters in the string are")
for i in str:
print(i)
list1=["civil","eee","mech","ece","cse"]
print("the items in the list are")
for i in list1:
print(i)
output:
Page 21
break statement:
The break statement breaks out of the innermost enclosing for or while loop. When
the loop is terminated by a break statement, the else clause of the loop (if present) is
not executed.
Ex1:
for i in range(1,11):
if (i==5):
break
print(i,end=" ")
print("\ndone")
output:
1234
done
continue statement:
The continue statement is used to end the current iteration in a for loop (or
a while loop) and continues with the next iteration of the loop
Page 22
Ex:
for i in range(1,11):
if (i==5):
continue
print(i,end=" ")
print("\ndone")
output:
1 2 3 4 6 7 8 9 10
done
pass statement:
The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.
Ex:
#program to illustrate pass statement
for i in range(1,11):
if (i==5):
pass
print(i,end=" ")
print("\ndone")
output:
1 2 3 4 5 6 7 8 9 10
done
Page 23