Python - UNIT-2
Python - UNIT-2
Unit -2
Topics to be covered
Control Statements: Definite iteration for Loop, Formatting Text for output,
Selection if and if else Statement, Conditional Iteration the While Loop
Strings and Text Files: Accessing Character and Substring in Strings, Data
Encryption, Strings and Number Systems, String Methods Text Files.
----------------------------------------------------------------------------------------
Control Statements
Introduction: The control statements are the program statements that allow
the computer to select a part of the code or repeat an action for specified
number of times. These statements are categorized into categories: Selection
statements, Iterative/Loop statements and Jump statements. First, we will
learn for iterative statement, then we will learn selection statements if and
else, later we will learn conditional iteration statement while.
Exp1.py Output
for i in range(3): It's Alive! It's Alive! It's Alive!
print("It's Alive!",end=" ")
This for loop repeatedly calls one function that print () function. The constant
3 for the range() function specifies the number of times to repeat action. If we
www.Jntufastupdates.com 1
Python Programming (R19)
www.Jntufastupdates.com 2
Python Programming (R19)
Exp2.py Output
number=int(input('Enter number:')) Enter number:2
exponent=int(input('Enter Exponent Enter Exponent value:3
value:')) 248
product=1
for i in range(exponent):
product=product*number
print(product,end=" ")
Count-Controlled Loops
Loops that count through a range of numbers are also called count-controlled
loops. The value of the count on each pass is used in computations. When
Python executes the type of for loop just discussed above, it actually counts
from 0 to the value of the integer expression minus 1 placed inside range ()
function. On each pass through the loop, the loop variable is bound to the
current value of the count.
Fact.py Output
num=int(input('Enter the number:')) Enter the number:4
product=1 4! is 24
for i in range(num):
"""i is loop variable,
its value used inside body
for computing product"""
product=product*(i+1)
print(f'{num}! is {product}')
Augmented Assignment
Expressions such as x = x + 1 or x = x + 2 occur so frequently in loops. The
assignment symbol can be combined with the arithmetic and concatenation
operators to provide augmented assignment operations. The general form is
as follow:
<variable> <operator>=<expression>
Which is equal to
<variable> =<variable> <operator><expression>
www.Jntufastupdates.com 3
Python Programming (R19)
The data sequence can be list, or tuple, string or set. The loop variable is
bound to the next value in the sequence. The sequence of numbers generated
using the range function can be converted into list or tuple. This tuple or list
can be later used in the place of the sequence.
Add.py Output
l=list(range(1,11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(l) Sum of Elements of list is 55
s=0
for x in l: #here x is loop variable and
l is list
s=s+x
print('Sum of Elements of list is',s)
All of our loops until now have counted up from a lower bound to an upper
bound. Once in a while, a problem calls for counting in the opposite direction,
from the upper bound down to the lower bound. When the step argument is
a negative number, the range function generates a sequence of numbers
from the first argument down to the second argument plus 1.
Countdown.py Output
l=list(range(10,0,-1)) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(l) Sum of Elements of list is 55
s=0
for x in l: #here x is loop variable and
l is list
s=s+x
print('Sum of Elements of list is',s)
Many data-processing applications in our day to day life require output needs
to be display in a tabular format. In this format, numbers and other
information are aligned in columns that can be either left-justified or right-
justified. A column of data is left-justified if its values are vertically aligned
beginning with their leftmost characters. A column of data is right-justified if
its values are vertically aligned beginning with their rightmost characters.
The total number of data characters and additional spaces for a given
datum in a formatted string is called its field width. The print function
automatically begins printing an output datum in the first available column.
www.Jntufastupdates.com 4
Python Programming (R19)
<format_string>%<datum>
This version contains a format string, the format operator %, and a single
data value to be formatted. The format string is represented as: %<field
width>s. The format string begins with % operator, and positive number for
right-justification, and ‘s’ is used for string.
The format information for a data value of type float has the form:
%<fieldwidth>.<precision>f
Examples:
>>> "%8s" % "PYT" # field width is 8, right justification, datum is string PYT.
' PYT'
>>> "%-8s" % "PYT" # field width is -8, left justification, datum is string PYT.
'PYT '
>>> "%8d" % 1234 # field width is 8, right justification, datum is int 1234.
' 1234'
>>> "%-8d" % 1234 # field width is -8, left justification, datum is int 1234.
'1234 '
>>> "%6.2f" % 1234.678 # field width is 6, 2 decimal points, right justification,
datum is int 1234.678
'1234.68'
Read the number of years, starting balance, Interest, and Ending balance
from the keyboard.
www.Jntufastupdates.com 5
Python Programming (R19)
www.Jntufastupdates.com 6
Python Programming (R19)
perform the computation if the inputs are valid. For example, suppose a
program takes area of a circle as input and need to compute its radius. The
input must always a positive number. But, by mistake, the user could still
enter a zero or a negative number. Because the program has no choice but to
use this value to compute the radius, it might produce a meaningless output
or error message.
If area<=0 then convey user to enter valid area as input
Otherwise compute the radius as sqrt(area/PI)
Here is the Python syntax for the if-else statement:
if <condition>:
<sequence of statements-1>
else:
<sequence of statements-2>
Write a program to find the radius from the area of the circle.
import math
area=float(input('Enter area:'))
if area<=0:
print("Wrong Input!")
else:
radius=math.sqrt(area/math.pi)
print('The radius is:',radius)
www.Jntufastupdates.com 7
Python Programming (R19)
If <Boolean_Expression>:
Sequence of statement to execute
Next ststement after if selection statement
Flow diagram of if
Multi-Way if Statements
The process of testing several conditions and responding accordingly can be
described in code by a multi-way selection statement. This multi-way
decision statement is preferred whenever we need to select one choice among
multiple alternatives. The keyword ‘elif’ is short for ‘else if’. The else statement
will be written at the end and will be executed when no if or elif blocks are
executed. The syntax of will be as follow:
if Boolean_expression1:
Statements
elif Boolean_expression2:
Statements
elif Boolean_exxpression3:
Statements
else:
Statements
www.Jntufastupdates.com 8
Python Programming (R19)
Flow diagram
else:
print('Marks must be within the range 0 to 100')
www.Jntufastupdates.com 9
Python Programming (R19)
while <condition>:
<sequence of statements>
Here while is the keyword, condition will be always a Boolean expression, and
the loop end with colon (:). The first line is called loop body. The sequence of
statement that we write inside the body is called loop body.
The flow diagram will be as follow:
Write a python program to find the sum of all the numbers entered
from the user.
Tot.py Output
data=input('Enter any number:') Enter any number:2
tot=0 Enter any number:3
while data!="": Enter any number:4
data=int(data) Enter any number:5
tot=tot+data Enter any number:
data=input('Enter any number:') The sum of numbers is: 14
print('The sum of numbers is:',tot)
www.Jntufastupdates.com 10
Python Programming (R19)
incremented in the loop body. The count variable must also be examined in
the explicit continuation condition. The following are the some example for
count-controlled loops.
Write a python program to find sum of all the digits of a given number?
Total.py Output
num=int(input('Enter number :')) Enter number :234
rem=0 The sum of all digits is: 9
tot=0
while num>0:
rem=num%10
tot=tot+rem
num=num//10
print('The sum of all digits is:',tot)
Palindrome.py Output
num=int(input('Enter number :')) Enter number :121
rem=0 The reversed number is: 121
x=num 121 is palindrome
rev=0
while num>0: Enter number :123
rem=num%10 The reversed number is: 321
rev=rev*10+rem 123 is not palindrome
num=num//10
print('The reversed number is:',rev)
if x==rev:
print(x,'is palindrome')
else:
print(x,'is not palindrome')
Armstrong.py Output
d=input('Enter number :') Enter number :153
num=int(d) The sum of cubes is: 153
tot=0 153 is Armstrong
x=num
rev=0 Enter number :435
www.Jntufastupdates.com 11
Python Programming (R19)
i=1
while i < 6:
print(i)
i += 1
else:
print ("i is no longer less than 6")
www.Jntufastupdates.com 12
Python Programming (R19)
character from the string using the for loop. In this section we will learn how to fetch the desired
portions of the string called substrings.
The Structure of Strings
A string is a sequence of zero or more characters. It is treated as a data structure. A data
structure is a compound unit that consists of several smaller pieces of data. When working with
strings, the programmer sometimes must be aware of a string’s length and the positions of the
individual characters within the string. A string’s length is the number of characters it contains.
The length can be obtained using the len() function by passing the string as an argument to it.
The positions of a string’s characters are numbered from 0, on the left, to the length of the
string minus 1, on the right.
In the above string ‘Python’, the number of characters is 6, the position of the starting character
is o, and last character is length of the string minus 1 (i.e 6-1).
The Subscript Operator
Though the for loop helps to fetch individual characters from the given string. Sometimes it
may be need to extract the character at specified position. This can be done using the subscript
operator. The form of a subscript operator is the following:
<a string> [<an integer expression>]
The first part of the subscript operator is the string that you want to inspect, the integer
expression in square brackets is the position of the character that we want to inspect in that
string. This integer expression is also called ‘Index’. Example:
S= “Python”
S[0] -> gives ‘P’
S[1] -> gives ‘y’
S[5] -> gives ‘n’
Slicing for Substrings
The portions of the strings or parts of the strings are called “Substrings”. we can use Python’s
subscript operator to obtain a substring through a process called slicing. To extract a substring,
the programmer places a colon (:) in the subscript. An integer value can appear on either side
of the colon. The form of the slicing will be as follow: <a string> [start_position :
End_position], here the substring is obtained from the start_position but not including the
End_position.
www.Jntufastupdates.com 13
Python Programming (R19)
Example:
S[0:3] -> gives a substring ‘Pyt’
S[2:5] -> gives the substring ‘tho’
l=['prg1.py','sort.txt','substring.py','add.c','mul.cpp','eventest.py']
l2=[]
sub=input('Enter the substring:')
for x in l:
if sub in x:
l2.append(x)
print(x)
#display final list2
print(l2,end=" ")
Data Encryption
The information travelling through the network is vulnerable(exposed) to the spies and
potential thieves. By using the right sniffing software, a person can get the information passing
between any two computers. Many applications use Data Encryption to protect the information
transmitted on the network.
General scenario of security attacks
Security attack: Any action that compromises the security of information owned by an
organization is called security attack.
Security attacks are classified into two: Passive and Active
Passive Attacks - Passive attacks are in the nature of eavesdropping (secretly listening private
conversation) on transmissions. There are two types as follow:
Release of message contents –unauthorized person listens to the message from sender
to the receiver
Traffic analysis - unauthorized person observes the patterns of messages.
www.Jntufastupdates.com 14
Python Programming (R19)
Active Attacks
Active attacks involve some modification of data stream or the creation of a false stream. These
are sub divided into four categories :
www.Jntufastupdates.com 15
Python Programming (R19)
www.Jntufastupdates.com 16
Python Programming (R19)
The digits used in each system are counted from 0 to n - 1, where n is the system’s base.
• Binary system base is 2, hence it includes digits from 0 to 2-1 [0,1]
• Octal system base is 8, hence it includes digits from 0 to 8-1 [0,1,2,3,4,5,6,7]
• Decimal system base is 10, hence it includes digits from 0 to 10-1 [0,1,2,3,4,5,6,7,8,9]
• Hexadecimal system base is 16, hence it includes digits from 0 to 16-
1[0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F]
The Positional System for Representing Numbers
The value of each digit in a number is determined by the digit’s position in the
number.
In other words, each digit has a positional value.
The positional value of a digit is determined by raising the base of the system to
the power specified by the position (base position).
For an n-digit number, the positions (and exponents) are numbered from n - 1
down to 0, starting with the leftmost digit and moving to the right.
the positional values of the three-digit number 41510 are 100 (102), 10 (101), and 1
(100) { where n is 3, hence positions are 3-1 to 0}
To determine the quantity represented by a number in any system from base 2
through base 10, you multiply each digit (as a decimal number) by its positional
value and add the results.
The following example shows how this is done for a three-digit number in base
10:
www.Jntufastupdates.com 17
Python Programming (R19)
www.Jntufastupdates.com 18
Python Programming (R19)
Enter number:10
5 0 0
2 1 10
1 0 010
0 1 1010
The binary representation is: 1010
decimal=int(input('Enter number:'))
bstring="" Octal and Hexadecimal
if decimal ==0: Numbers
We have function
print(0)
like oct() and hex() to
else: convert the numbers into
decimal to octal, and
while decimal >0: decimal to hexadecimal
rem=decimal%2 numbers.
Each digit in the hexadecimal number is equivalent to four digits in the binary
number.
www.Jntufastupdates.com 19
Python Programming (R19)
Thus, to convert from hexadecimal to binary, you replace each hexadecimal digit with
the corresponding 4-bit binary number.
To convert from binary to hexadecimal, you factor the bits into groups of four and
look up the corresponding hex digits.
String Methods
Text processing involves many different operations on strings. Python
includes a set of string operations called methods. A method behaves like
a function, but has a slightly different syntax. Unlike a function, a Method
is always called with a given data value called an object, which is placed
before the method name in the call. The syntax of a method call is the
following:
<object>.method_name(arg1,arg2,….argn)
Example:
txt=“apple is good for health than mango, one apple a day keeps a doctor
away”.
print(txt.count(‘apple’))
Methods can also expect arguments and return values. A method knows
about the internal state of the object with which it is called. The methods
are as useful as functions, but we need to use the dot notation which we
have already discussed with module concept. Every data type includes a
set of methods to use with objects of that type.
We will see some useful methods of string object.
www.Jntufastupdates.com 20
Python Programming (R19)
www.Jntufastupdates.com 21
Python Programming (R19)
s.replace(old, new) Returns a copy of s >>> s='i like ice cream. it is very
with all occurrences tasty'
of substring old >>> s.replace('i','I')
replaced by new. 'I lIke Ice cream. It Is very tasty'
www.Jntufastupdates.com 22
Python Programming (R19)
character of each
word is capitalized
www.Jntufastupdates.com 23
Python Programming (R19)
words, numbers, or lines of text. When the data are treated as numbers (either
integers or floating-points), they must be separated by whitespace
characters—spaces, tabs, and newlines. For example, a text file containing
six floating-point numbers might look like:
34.6 22.33 66.75 77.12 21.44 99.01
All data output to or input from a text file must be strings. Thus, numbers
must be converted to strings before output, and these strings must be
converted back to numbers after input.
Writing Text to a File
Data can be output to a text file using a file object.
Python’s open function, which expects a file pathname and a mode string
as arguments, opens a connection to the file on disk and returns a file
object.
The mode string is 'r' for input files and 'w' for output files.
Thus, the following code opens a file object on a file named myfile.txt for
output:
f=open(“myfile.txt”,'w')
If the file does not exist, it is created with the given pathname.
If the file already exists, Python opens it. When data are written to the file
and the file is closed, any the data that is already existing in the file will be
erased.
String data are written (or output) to a file using the method write method
with the file object. The write method expects a single string argument.
If you want the output text to end with a newline, you must include the
escape character \n in the string.
f.close()
f=open('firstfile.txt','w')
f.write('Python is the number 1 language among the existing languages.\
\n It is an object oriented programming language.\
\n It is high-level and easy language\n')
f.close()
Output
www.Jntufastupdates.com 24
Python Programming (R19)
import random
f=open('nums.txt','w')
for n in range(20):
number=random.randint(1,100)
f.write(str(number)+"\n")
f.close()
www.Jntufastupdates.com 25
Python Programming (R19)
You open a file for input in a manner similar to opening a file for output.
The only thing that changes is the mode string, which, in the case of
opening a file for input, is 'r’.
However, if the pathname is not accessible from the current working
directory, Python raises an error.
Here is the code for opening myfile.txt for input:
F=open(‘myfile.txt’, ‘r’)
There are several ways to read data from an input file.
o We can use read() function which reads the entire content of a
file as single string.
o We can use for() loop which considers the file object as a lines of
text.
o We can use the readline() method of file object which is used to
read specific line from the file (say first line).
www.Jntufastupdates.com 26
Python Programming (R19)
f=open('nums.txt','r')
sum=0
for line in f:
n=line.strip()
sum=sum+int(n)
print('The sum of all the numbers is:',sum)
www.Jntufastupdates.com 27
Python Programming (R19)
os.path functions
os.path functions Description
exists(path) Returns True if path exists and False otherwise.
isdir(path) Returns True if path names a directory and False
otherwise.
isfile(path) Returns True if path names a file and False
otherwise.
getsize(path) Returns the size of the object names by path in
bytes.
Example:
• os.path.exists(‘nums.txt’) True
• Os.path.isdir(os.getcwd()) True
• os.path.isfile('nums.txt’) True
www.Jntufastupdates.com 28
Python Programming (R19)
www.Jntufastupdates.com 29