Python R20 - Unit-2
Python R20 - Unit-2
Control Statement: 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.
– for
– while
– those that perform the action until the program determines that it needs to stop
(indefinite iteration).
<statement-1>
<statement-n>
• The first line of code in a loop is sometimes called the loop header,which denotes the
number of iterations that the loop performs.
www.Jntufastupdates.com 1
• The loop body comprises the statements in the remaining lines of code, below the
header.These statements are executed in sequence on each pass through the loop.
– The statements in the loop body must be indented and aligned in the same
column.
print(i)
Count-Controlled Loops:
• Loops that count through a range of numbers are also called count-controlled loops.
• To count from an explicit lower bound, the programmer can supply a second integer
expression in the loop header. When two arguments are supplied to range, the count ranges
from the first argument to the second argument minus 1
• The only thing in this version to be careful about is the second argument of range, which
should specify an integer greater by 1 than the desired upper bound of the count.
<loop body>
>>>for i in range(5,10):
print(i)
www.Jntufastupdates.com 2
• The loop fails to perform the expected number of iterations. Because this number is
typically off by one, the error is called an off-by-one error
The values contained in any sequence can be visited by running a for loop , as follows:
– On each pass through the loop, the variable is bound to or assigned the next value in the
sequence, starting with the first one and ending with the last one.
>>> nl=[45,36,644]
>>> nt=(4,22,6,1)
print(i,end=",")
S,u,r,y,a, ,L,a,k,s,h,m,i,
print(i,end=",")
45,36,644,
print(i,end=",")
4,22,6,1,
• A variant of Python’s range function expects a third argument that allows you to nicely
skip some numbers.
• The third argument specifies a step value, or the interval between the numbers used in the
range, as shown in the examples that follow:
[1, 2, 3, 4, 5]
www.Jntufastupdates.com 3
[1, 3, 5]
[1, 4]
• Once in a while, a problem calls for counting in the opposite direction, from the upper
bound down to the lower bound.
• a loop displays the count from 10 down to 1 to show how this would be done:
10 9 8 7 6 5 4 3 2 1
• 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.
• Conditional iteration requires that a condition be tested within the loop to determine
whether the loop should continue. Such a condition is called the loop’s continuation
condition.
– If the continuation condition is true, the statements within the loop are executed
again.
• Syntax:
while <condition>:
<sequence of statements>
• The while loop is also called an entry-control loop, because its condition is tested at
the top of the loop.
• This implies that the statements within the loop can execute zero or more times.
www.Jntufastupdates.com 4
# Summation with a while loop
theSum = 0
count = 1
theSum += count
count += 1
print(theSum)
• The while loop is also called an entry-control loop, because its condition is tested at
the top of the loop.
– This implies that the statements within the loop can execute zero or more times.
• If the loop must run at least once, use a while True loop and delay the examination of
the termination condition until it becomes available in the body of the loop.
• Ensure that something occurs in the loop to allow the condition to be checked and a
break statement to be reached eventually.
while True:
break
www.Jntufastupdates.com 5
else:
OUTPUT
A trial run with just this segment shows the following interaction:
45
Random Numbers
• The function random.randint (from module random) returns a random number from
among the numbers between the two arguments and including those numbers.
2 4 6 4 3 2 3 6 2 2
• Many data-processing applications require output that has a tabular format, like that
used in spreadsheets or tables of numeric data.
• In this format, numbers and other information are aligned in columns that can be either
left-justified or right-justified.
www.Jntufastupdates.com 6
– 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 following example shows how to right-justify and left- justify the string "four"
within a field width of 6:
' four'
'four '
• When the field width is positive, the datum is right-justified; when the field width is
negative, you get left-justification.
• If the field width is less than or equal to the datum’s print length in characters, no
justification is added.
• The % operator works with this information to build and return a formatted string.
• To format a sequence of data values, you construct a format string that includes a format
code for each datum and place the data values in a tuple following the % operator.
print(exponent, 10 ** exponent)
www.Jntufastupdates.com 7
7 10000000
8 100000000
9 1000000000
10 10000000000
• The first column is left-justified in a field width of 3, and the second column is
right-justified in a field width of 12.
7 10000000
8 100000000
9 1000000000
10 10000000000
• The format information for a data value of type float has the form
%<field width>.<precision>f
• Example of the use of a format string, which says to use a field width of 6 and a
precision of 3 to format the float value 3.14:
' 3.140'
• Note that Python adds a digit of precision to the string and pads it with a space to the
left to achieve the field width of 6. This width includes the place occupied by the
decimal point.
4. Strings
• E-mail, text messaging, Web pages, and word processing all rely on and manipulate
data consisting of strings of characters.
www.Jntufastupdates.com 8
• The following session with the Python shell shows some example strings:
'Hello there!'
'Hello there!'
>>> ''
''
>>> ""
''
• A string is a data structure i.e., it is a compound unit that consists of several other
pieces of data.
• The string is an immutable data structure. This means that its internal data elements,
the characters, can be accessed, but cannot be replaced, inserted, or removed.
• A string’s length is the number of characters it contains. Python’s len function returns
this value when it is passed a string, as shown in the following session:
>>> len("")
• 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.
• The following figure illustrates the sequence of characters and their positions in the
string "Hi there!".
www.Jntufastupdates.com 9
The Subscript Operator:
• The subscript operator [] inspects one character at a given position without visiting
all the characters in a given string / sequence.
• The first part of this operation is the string you want to inspect.
• The integer in brackets is the index that indicates the position of a particular character
in that string.
'A'
'n'
'g'
'g'
'n'
• The next code segment uses a count-controlled loop to display the characters and their
positions:
print(index, data[index])
www.Jntufastupdates.com 10
0H
1i
3t
4h
5e
6r
7e
8!
• You 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
• When two integer positions are included in the slice, the range of characters in the
substring extends from the first position up to but not including the second position.
• When the integer is omitted on either side of the colon, all of the characters extending
to the end or the beginning are included in the substring
>>> name[:]
'Surya Lakshmi'
>>> name[0:5]
'Surya'
>>> name[0:]
'Surya Lakshmi'
>>> name[4:7]
'a L'
name[-4:-1]
www.Jntufastupdates.com 11
'shm'
• When used with strings, the left operand of in is a target substring, and the right operand
is the string to be searched.
• The operator in returns True if the target string is somewhere in the search string, or
False otherwise.
name="Surya Lakshmi"
False
True
True
• The system used to represent numbers are called number systems. Various number
systems are:
• To identify the system being used, you attach the base as a subscript to the number.
• For example, the following numbers represent the quantity 41510 in the binary, octal,
decimal, and hexadecimal systems:
www.Jntufastupdates.com 12
The Positional System for Representing Numbers
• All of the number systems we have examined use positional notation—that is, 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 ).
• 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:
• Each digit or bit in a binary number has a positional value that is a power of 2.
• Determine the integer quantity that a string of bits represents in the usual manner:
Multiply the value of each bit (0 or 1) by its positional value and add the results
decimal = 0
exponent = len(bitString) - 1
www.Jntufastupdates.com 13
decimal = decimal + int(digit) * 2 ** exponent
exponent = exponent - 1
OUTPUT :
• The quotient becomes the next dividend in the process. The string of bits is initially
empty, and the process continues while the decimal number is greater than 0.
if (decimal == 0):
print(0)
else:
bitString = ""
remainder = decimal % 2
decimal = decimal // 2
www.Jntufastupdates.com 14
Quotient Remainder Binary
17 0 0
8 1 10
4 0 010
2 0 0010
1 0 00010
0 1 100010
Octal Numbers
• Conversions of octal to decimal and decimal to octal use algorithms similar to those
discussed thus far (using powers of 8 and multiplying or dividing by 8, instead of 2).
• To convert binary to octal, you begin at the right and factor the bits into groups of three
bits each. You then convert each group of three bits to the octal digit they represent.
Hexadecimal Numbers:
• The hexadecimal or base-16 system (called “hex” for short), which uses 16 different
digits, provides a more concise notation than octal for larger numbers.
• Base 16 uses the digits 0 . . . 9 for the corresponding integer quantities and the letters
A . . . F for the integer quantities 10 . . . 15.
• Each digit in the hexadecimal number is equivalent to four digits in the binary number.
• Thus, to convert from hexadecimal to binary, you replace each hexadecimal digit with
the corresponding 4-bit binary number.
www.Jntufastupdates.com 15
• To convert from binary to hexadecimal, you factor the bits into groups of four and look
up the corresponding hex digits.
5 String Methods :
Examples :
>>> len(s)
Surya Lakshmi Kantham Vinti
CSE DEPT
ACET
www.Jntufastupdates.com 16
9
>>> s.center(11)
>>> s.count('e')
>>> s.endswith("there!")
True
>>> s.startswith("Hi")
True
>>> s.find("the")
>>> s.isalpha()
False
>>> 'abc'.isalpha()
True
>>> "326".isdigit()
True
>>> words
['Hi', 'there!']
'Hithere!'
'Hi there!'
>>> s.lower()
'hi there!'
>>> s.upper()
www.Jntufastupdates.com 17
'HI THERE!'
'Ho there!'
'Hi there!'
6) Data Encryption
• It is easy to observe data crossing a network, particularly now that more and more
communications involve wireless transmissions.
– For example, a person can sit in a car in the parking lot outside any major hotel
and pick up transmissions between almost any two computers if that person runs
the right sniffing software
• The sender encrypts a message by translating it to a secret code, called a cipher text.
• At the other end, the receiver decrypts the cipher text back to its original plaintext form.
• Both parties to this transaction must have at their disposal one or more keys that allow
them to encrypt and decrypt messages.
• This encryption strategy replaces each character in the plaintext with the character that
occurs a given distance away in the sequence.
• For positive distances, the method wraps around to the beginning of the sequence to
locate the replacement characters for those characters near its end.
• For example, if the distance value of a Caesar cipher equals three characters, the string
"invaders" would be encrypted as “lqydghuv“
• To decrypt this cipher text back to plaintext, you apply a method that uses the same
distance value but looks to the left of each character for its replacement.
• This decryption method wraps around to the end of the sequence to find a replacement
character for one near its beginning
www.Jntufastupdates.com 18
Python Script to encrypt plain text to cipher text using Caesar Cipher
code = ""
for ch in plainText:
ordvalue = ord(ch)
code += chr(cipherValue)
print(code)
OUTPUT :
sbwkrq
abc
www.Jntufastupdates.com 19
Python Script to encrypt cipher text to plain text using Caesar Cipher
plainText = ""
for ch in code:
ordvalue = ord(ch)
plainText += chr(cipherValue)
print(plainText)
OUTPUT :
python
xyz
• The main shortcoming of this encryption strategy is that the plaintext is encrypted one
character at a time, and each encrypted character depends on that single character and
a fixed distance value.
• In a sense, the structure of the original text is preserved in the cipher text, so it might
not be hard to discover a key by visual inspection.
• A block cipher uses plaintext characters to compute two or more encrypted characters.
www.Jntufastupdates.com 20
• The matrix provides the key in this method. The receiver uses the same matrix to
decrypt the cipher text.
• The fact that information used to determine each character comes from a block of data
makes it more difficult to determine the key
www.Jntufastupdates.com 21