Python Programming
UNIT-2
Unit – II Control Statement, Strings and Text Files
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.
Looping statements or Repetition Statements or Control Structures
While and for are called as looping statements( or Iterative or repetitive statements)
While loop and for loop are called as repetition structures
Syntax of while Statement
while condition:
statement11
statement12
statement1n
Above statements will be executed repeatedly until condition becomes false.
Example for ‘While’ statement
# python program to print 1 to 10 numbersusing 'while' statement
i=1
whilei<=10:
print(i)
i+=1
While and for are called as looping statements ( or Iterative or repetitive statements)
Syntax of for Statement
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
for variable in sequence:
statement11
statement12
statement1n
Sequence is range or string or list or tuple or set or dictionary
In each iteration, element or value in sequence will be assigned to variable.
Above statements will be executed repeatedly until completion of all elements in the sequence.
Example for ‘for’ statement
# python program to print 1 to 5 numbers using ‘for' statement
fori in range(1,6):
print(i)
Output:
# range(1,6) returns 1 to (6-1) 1,2,3,4,5
Example for ‘for’ statement
# python program to print characters in a string
s=“abcd”
for ch in s:
print(ch)
Output:
c
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
d
Nested loops
If one loop statement (while or for ) is included in any other loop statement (while
or for ) then that structure is called as nested loop.
Example:
For I in range(1,5):
For j in range(I):
Print(‘*’)
Print(‘\n’)
In the above program one for loop is included in another for loop.
Output is:
*
**
***
****
range() function
This function returns sequence of numbers
Syntax of range() function
range(lower, upper, increment/decrement)
range(upper) returns numbers from 0 to upper-1 with a default increment value 1.
range(5) returns 0,1,2,3,4
range(lower, upper) returns numbers from lower to upper-1
With a default increment value 1.
range(2,8) returns numbers 2,3,4,5,6,7
range(1,11,2) returns numbers from 1 to 10 With increment value 2.
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
Range(1,11,2)->1,3,5,7,9
range(10,1,-1) returns numbers from 10 to 2 With decrement value 1.
Range(10,1,-1)->10,9,8,7,6,5,4,3,2
10,9,8….3,2,1
Break and continue
Break is used to exit from the loop (while or for).
Continue is used to skip remaining statements in the current loop and control moves to next iteration.
Example:
while (cond1):
stmt1
stmt2
if (cond2):
break
stmt3
stmt4
If cond2 is true control comes out from the while loop.
Example:
while (cond1):
stmt1
stmt2
if (cond2):
continue
stmt3
stmt4
If cond2 is true, stmt3 and stmt4 will not be executed, control moves to next iteration.
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
Formatting Text for Output
% operator is used to format text for output.
Syntax:
formatestring%(data)
name=“abcd”
print(“My name is %s”%name)
marks=99
Print(“My name is %s Marks:%d”%(name,marks)
%width-of-field format-specifier
%20s – string will be displayed with a length 20
%10d – integer will be displayed with a length 10
%-10s – string will be displayed with a length 10 with left alignment.
( - symbol for left alignment, default-right alignment)
Strings
String is sequence of characters included in single quotes or double quotes.
S1=‘aditya’
S2=“aditya”
Multiline strings are include in three single quotes or double quotes.
Mtext=‘’’this is
Multiline
Text’’’
Accesing Characters and Substrings in a string
Characters in a string can be accessed using indexing (using subscript operator [ ] )
S=“abcd”
Index value of ‘a’ is 0, ‘b’ is 1 and so on.
S[0] returns ‘a’ s[1] returns ‘b’
Indexing is also negative. Last character index is -1.
S[-1] returns ‘d’ s[-2] returns ‘c’
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
substrings in a string can be accessed using slicing operation (using ‘ : ‘ operator)
s[a:b] returns from s[a] to s[b-1]
S=“Aditya College of Engineering”
We can extract substring “College” from string S using S[7:14].
S[7:14] returns “College”
S[a:] returns from S[a] to last character.
S[:a] returns from S[0] to s[a-1].
String Methods or functions
Let S is a string ( S=“python programming” )
S.lower() returns a string in lower case
S.upper() returns a string in uppercase
s.isdigit() returns true if all characters in the string are digits
s.isspace() returns true if all characters in the string are white spaces
s.isalpha() returns true if all characters in the string are alphabets
len(s) returns length of the string
s.count(“sub”) Returns the number of times a specified value occurs in a string
s.title() converts first character of each word to Uppercase.
s.capitalize() converts first character in the string to Uppercase.
s.center() returns a centered string
s.find() Searches the string for a specified value and returns
the position of where it was found. If not found it
returns -1
s.index() Searches the string for a specified value and
returns the position of where it was found.
If not found it returns error.
s.strip() It removes leading or trailing blank spaces.
s.replace(a,b) It replaces all occurrences of substring ‘a’ with substring ‘b’ in the string s.
s.replace(a,b,n) It replaces ‘n’ occurrences of substring ‘a’ with substring ‘b’ in the string s.
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
s.split(separator) It splits the string into words separated by ‘separator’ string. It returns list of elements.
Separator.join(list) This function joins the list of elements into string.
We can add one string to another string using ‘+’ operator.
S1=“abc” s2=“def” s=s1+s2
Now string s contains “abcdef”
Strings and Number Systems
Decimal Number System
Base is 10 and digits are 0,1,2,3,4,5,6,7,8,9
Example: 1298, 30465
Binary Number System
Base is 2 and digits are 0,1
Example: 1010111, 11110101
Octal Number System
Base is 8 and digits are 0,1,2,3,4,5,6,7
Example: 1234, 7056, 3672
Hexadecimal Number System
Base is 16 and digits are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
Example: 1234, 7056, 3672,1298, 2AF, ABCDEF, 89FE
Conversion from Decimal Number to Binary Number
29310 = 1001001012
2 293
146 --- 1
73----- 0
36----- 1
18------ 0
9------ 0
4 -------1
2-------0
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
1--------0
0-------1
After dividing 293 with 2 remainder is 1. Store it in bin. bin=‘1’. After that divide 146 with 2 remainder is
0. Add it to bin. bin=str(0)+bin=‘0’+’1’=‘01’
Do the same process until number becomes 0.
Conversion from Binary Number to Decimal Number
1001001012 = 29310
Read Binary number as string bin=‘100100101’
Length of bin is 9
So exponent is 9-1=8
dec=1*28+0*27+0*26+1*25+0*24+0*23+1*22+0*21+1*20= 293
Take a character at index 0. ch=‘1’
Convert ch to int a=int(ch)=int(‘1’)=1
dec=a*2**exponent
exponent=exponent-1
Again take second character a=0
dec=dec+a*2**exponent
Do the above process until exponent becomes 0
Data Encryption
Data Encryption is used to protect information transmitted on networks.
Some application protocols include secure versions such as HTTPS,FTPS that use data encryption. Assume
messages are being transmitted from sender to receiver. 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 plain text form. At both sides there must be one or more keys that allow them to encrypt and
decrypt messages.
A simple Data Encryption method is Caesar cipher. This encryption method replaces each character in the
plain text with the character that occurs a given distance away in the sequence. For example , if the
distance value of a caesar cipher equals three characters the string “action” would be encrypted as
“dfwlrq”. To decrypt this cipher text back to its plain text, take previous characters with 3 characters
distance.
a b c d e f g h . . . .u v w x y z
97 98 99 100 101 102 103 104 ……. 117 118 119 120 121 122
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
In the above list you can see alphabets with corresponding ASCII values.
Encryption
Plain Text a c t i o n
ASCII value 97 99 116 105 111 110
Distance +3 +3 +3 +3 +3 +3
ASCII value 100 102 119 108 114 113
Cipher Text d f w l r q
a b c d e f g h .... u v w x y z
97 98 99 100 101 102 103 104 ……. 117 118 119 120 121 122
In the above list you can see alphabets with corresponding ASCII values.
Encryption
Plain Text a c t i o n
ASCII value 97 99 116 105 111 110
Distance +3 +3 +3 +3 +3 +3
ASCII value 100 102 119 108 114 113
Cipher Text d f w l r q
Decryption
Cipher Text d f w l r q
ASCII value 100 102 119 108 114 113
Distance -3 -3 -3 -3 -3 -3
ASCII value 97 99 116 105 111 110
Plain Text a c t i o n
Text Files
File Operations
A text file is a software object that stores data on a permanent medium such as a disk, CD, or flash
memory. File name extension of Text file is txt
Generally text files can be created with Notepad application
Fileobject=open(filename, filemode)
Open() function opens a connection to the file on disk and returns a file object.
Filename is a string that specifies name of the file.
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem
File mode is a string that specifies in which mode file is to be opened.
File Modes are
“r”------ read
“w”-----write
“rw”----read and write
“a”------append (write content at the end of existing file)
Fileobject.close() --closes a file.
Fileobject.write(String) ------ writes a string to the file.
Fileobject.writelines(List) ------ writes a List of strings to the file.
Fileobject.read() --- It returns content in the file as a string.Returns empty string (“”) if the end of
file is reached.
Fileobject.readline() --- It returns a line of text in the file as a string. Returns empty string (“”) if the
end of file is reached.
Fileobject.readlines() --- It returns a list of lines.
L=f.readlines()
Where L is [ line1, line2, lin3, ……………………]
Where line1 is first line in the file
Line2 is second line in the file and so on…..
‘for loop’ is used to accesses line by line from the file.
Program to write Data to the file ‘file1.txt’
f=open(“file1.txt”, “w”)
f.write(“Aditya college of Engg.\nDepartment of CSE\nPython Programming\n”)
L=[ “Aditya\n”,”Sai Aditya\n”,”Sri Aditya\n” ]
f.writelines(L)
f.close()
Then a file with name file1.txt is created as follows
Aditya college of Engg.
Department of CSE
Python Programming
Aditya
Sai Aditya
Sri Aditya
Program to read Data from the file ‘file1.txt’
f=open(“file1.txt”, “r”)
s=f.read() # or you can use L=f.readLines()
print(s)
f.close()
Output: Content in the file will be displayed on the window
Vasamsetti Chandra Sekhararao, Associate Professor(CSE), Aditya College of Engineering, Surampalem