Python Unit 2
Python Unit 2
UNIT II: Repetition Structures: Introduction, while loop, for loop, Nested Loops, 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, string pattern matching. Understanding read functions, read(),
readline() and readlines(). Understanding write functions, write() and writelines(), Manipulating file pointer
using seek, Programming using file operations
Introduction:
In general, statements are executed sequentially, i.e The first statement is executed first, followed by the
second, and so on. There may be a situation when you need to execute a block of code several number of
times. In such situations we can use loop statements.
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement.
A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using loops
because of the possibility that this condition never resolves to a FALSE value. This results in a loop that
never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so
that client programs can communicate with it as and when required.
Python programming language provides the following types of loops to handle looping requirements.
While Loop:
A while loop statement in Python programming language repeatedly executes a target statement as long as a
given condition is true.
The syntax of a while loop in Python programming language is-
while condition:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition
may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct
are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
Flow Diagram:
Here, a key point of the while loop is that when the condition is tested and the result is false for the first time
itself, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
count = 0 while (count < 9):
print ('The count is:', count)
count = count + 1
For Loop: The for statement in Python has the ability to iterate over the items of any sequence, such as a
list or a string.
Syntax
statements(s)
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 statements block is executed. Each item in the list is
assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram:
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a list object of the
sequence, it is typecasted to list(). Now this list can be iterated using the for statement.
>>> for var in list(range(5)): print (var) This
will produce the following output
0
1
2
3
4
Example:
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence print
('Current fruit :', fruit)
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself. Following is a
simple example-
fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
•If the else statement is used with a while loop, the else statement is executed when the condition
becomes false.
The following example illustrates the combination of an else statement with a while statement that prints a
number as long as it is less than 5, otherwise the else statement gets executed.
Nested Loops:
Python programming language allows the use of one loop inside another loop. The following section shows
a few examples to illustrate the concept.
Syntax:
The syntax for a nested while loop statement in Python programming language is as follows-
while expression:
while expression:
statement(s)
statement(s)
The syntax for a nested for loop statement in Python programming language is as follows
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a
for loop can be inside a while loop or vice versa.
Example 2:
var = 10
while var > 0:
print ('Current variable value :', var) var = var -1
any number: 5
Examples for continue statement: The continue statement can be used in both while and for loops.
Example 1:
for letter in 'Python': if
letter == 'h':
continue
print ('Current Letter :', letter)
Example 2:
var = 10 while
var > 0:
var = var -1 if var == 5:
continue print ('Current variable
value :', var)
pass Statement:
The pass statement is a null operation; nothing happens when it executes. The pass statement is also useful
in places where your code will eventually go. It is used when a statement is required syntactically. Example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block') print ('Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Data Encryption:
1. Data encryption to protect information transmitted on networks. Some application protocols have
been updated to include secure versions that use data encryption. Examples of such versions are FTPS
and HTTPS, which are secure versions of FTP and HTTP for file transfer and Web page transfer,
respectively.
2. Encryption techniques are as old as the practice of sending and receiving messages. The sender
encrypts a message by translating it to a secret code, called a cipher text.
3. At the other end, the receiver decrypts the cipher text back to its original plaintext form.
4. Both parties to this transaction must have at their disposal one or more keys that allow them to
encrypt and decrypt messages.
5. A very simple encryption method that has been in use for thousands of years is called a Caesar cipher.
6. The next two Python scripts implement Caesar cipher methods for any strings that contain lowercase
letters and for any distance values between 0 and 26.
7. Here we are using the ord function returns the ordinal position of a character value in the ASCII
sequence, whereas chr is the inverse function.
Fig : Encryption and Decryption Using Symmetric Key
Example-1:
“””
File:encrypt.py
Encrypts an input string of lowercase letters and prints the result. The other input is the distance
value.
“””
Program:
plain_text=input('Enter Plain Text:') Output:
Example-2:
“””
File: decrypt.py
Decrypts an input string of lowercase letters and prints the result. The other input is the distance
value.
“”” Output:
Program:
enter cipher text: jgnnq#*%
ciphertext=input("enter cipher text: ") key=int(input("enter key enter key value: 2 hello!(#
value: ")) plain=" "
for i in ciphertext:
ordvalue=ord(i)
plainvalue=ordvalue-key
plain+=chr(plainvalue)
print(plain)
String Methods
• Python has a set of built-in methods that you can use on strings.
• Note: All string methods returns new values. They do not change the original string.
6 endswith() Returns true if the string ends with the specified value
8 find() Searches the string for a specified value and returns the
position of where it was found
9 index() Searches the string for a specified value and returns the
position of where it was found
15 islower() Returns True if all characters in the string are lower case
16 isnumeric() Returns True if all characters in the string are numeric
20 isupper() Returns True if all characters in the string are upper case
31 rfind() Searches the string for a specified value and returns the
last position of where it was found
32 rindex() Searches the string for a specified value and returns the
last position of where it was found
1. capitalize ():
• Converts the first character to upper case
Syntax: string.capitalize()
Example: 1
>>> str="python is a trending programming language"
>>> str.capitalize()
Output:'Python is a trending programming language'
Example: 2
>>> txt='522616 is a pincode'
>>> txt.capitalize()
Output: '522616 is a pincode'
2. casefold ():
• Converts string into lower case
• This method is similar to the lower() method, but the casefold() method is stronger, more aggressive,
meaning that it will convert more characters into lower case, and will find more matches when comparing
two strings and both are converted using the casefold() method.
Syntax: string.casefold()
Example: 1
>>> str='PYTHON IS A TRENDING PROGRAMMING LANGUAGE'
>>> str.casefold()
Output: 'python is a trending programming language'
3. center ():
• The center() method will center align the string, using a specified character (space is default) as the fill
character.
Syntax: string.center(length, character) Here,
length = Required. The length of the returned string.
Character = Optional. The character to fill the missing space on each side. Default is " " (space)
Example-1: Print the word "Engineering", taking up the space of 128 characters, with "
Engineering " in the middle:
str1="Engineering"
>>> str1.center(128)
Output: ' Engineering '
>>> str1.center(28)
Output: ' Engineering '
4. count (): The count() method returns the number of times a specified value appears in the string.
5. encode ():
• The encode() method encodes the string, using the specified encoding.
• If no encoding is specified, UTF-8 will be used.
Output: True
7. expandtabs():
The expandtabs() method sets the tab size to the specified number of whitespaces.
Syntax: string.expandtabs(tabsize)
Here, tabsize Optional. A number specifying the tabsize. Default tabsize is 8
Example-2:
txt = "H\te\tl\tl\to"
print(txt)
print(txt.expandtabs())
print(txt.expandtabs(2)) print(txt.expandtabs(4))
print(txt.expandtabs(10)) Output:
H e l l o
H e l l o
Hello
Hello
H e l l o
8. find():
• The find() method finds the first occurrence of the specified value.
• The find() method returns -1 if the value is not found.
Output: 7
Output: 8
Example-3: txt = "Hello, welcome to my
world."
print(txt.find("q"))
print(txt.index("q"))
9. index()
• The index() method finds the first occurrence of the specified value.
• The index() method raises an exception if the value is not found.
• The index() method is almost the same as the find() method, the only difference is that the find()
method returns -1 if the value is not found. (See example below)
Syntax: string.index(value, start, end)
Here, value Required. The value to search for start Optional. Where to start the search. Default is 0, end
Optional. Where to end the search. Default is to the end of the string Example-1: txt = "Hello,
welcome to my world." x = txt.index("welcome")
print(x)
Output: 7
Example-2: txt = "Hello, welcome to my
world."
10. isalnum():
• The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-
z) and numbers (0-9).
• Example of characters that are not alphanumeric: (space)!#%&? etc.
Syntax: string.isalnum()
Example-1:
txt = "Company12"
x = txt.isalnum()
print(x)
Output: True Example-2:
txt = "Company 12"
x = txt.isalnum()
print(x)
Output: False , because white space before 12.
11. isalpha():
• The isalpha() method returns True if all the characters are alphabet letters (a-z).
• Example of characters that are not alphabet letters: (space)!#%&? etc.
Syntax: string.isalpha()
Example-1:
txt =
"CompanyX" x =
txt.isalpha() print(x)
Output: True
Example-2:
txt =
"Company10" x =
txt.isalpha()
print(x)
Output: False
12. isdecimal():
• The isdecimal() method returns True if all the characters are decimals (0-9).
• This method is used on unicode objects.
Syntax: string.isdecimal()
Output: True
False
13. isdigit():
• The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit. Syntax: string.isdigit() Example-1:
txt = "50800"
x =
txt.isdigit()
print(x)
Output: True Example-2: a =
"\u0030" #unicode for 0 b = "\u00B2"
#unicode for ²
print(a.isdigit())
print(b.isdigit())
14. isidentifier():
• The isidentifier() method returns True if the string is a valid identifier, otherwise False.
• A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and
(0-9), or underscores (_).
• A valid identifier cannot start with a number, or contain any spaces. Syntax:
string.isidentifier() Example-1:
txt = "Demo"
x = txt.isidentifier()
print(x)
Output: True Example-2:
a = "MyFolder" c =
"2bring"
print(a.isidentifier()
)
15. islower():
• The islower() method returns True if all the characters are in lower case, otherwise
False.
• Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: string.islower()
Example-1: txt = "hello
world!" x =
txt.islower()
print(x)
Output: True Example-
2: a = "Hello world!" b = "hello
123" c = "mynameisPeter"
print(a.islower()) print(b.islower())
print(c.islower()) Output:
False True False
16. isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
Exponents, like ² and ¾ are also considered to be numeric values. Syntax: string.isnumeric()
Example-1: txt = "565543" x = txt.isnumeric()
print(x) Output: True
Example-2: a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
c = "10km2"
print(a.isnumeric())
print(b.isnumeric())
print(c.isnumeric())
Output: True
True
False
17. isprintable():
• The isprintable() method returns True if all the characters are printable, otherwise False.
• Example of none printable character can be carriage return and line feed.
Syntax: string.isprintable()
18. isspace():
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax: string.isspace()
Example-1: txt = " " x =
txt.isspace()
print(x)
Output: True Example-
2: txt = " s " x = txt.isspace()
print(x)
Output: False
19. istitle():
• The istitle() method returns True if all words in a text start with a upper
case letter, AND the rest of the word are lower case letters, otherwise
False.
• Symbols and numbers are ignored. Syntax: string.istitle()
Example-1:
txt = "Hello, And Welcome To My World!" x
= txt.istitle() print(x) Output: True Example-2:
a = "HELLO, AND WELCOME TO MY
WORLD" b = "Hello" c = "22 Names" d = "This Is
%'!?" print(a.istitle()) print(b.istitle())
print(c.istitle()) print(d.istitle())
Output: False True True True
20. isupper()
The isupper() method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: string.isupper()
Example-1:
txt = "THIS IS NOW!"
x = txt.isupper()
21. join():
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
Syntax: string.join(iterable)
Here, iterable is Required. Any iterable object where all the returned values are strings
22. ljust():
The ljust() method will left align the string, using a specified character (space is default) as the fill
character.
Syntax: string.ljust(length, character)
Here, length Required. The length of the returned string character Optional. A character to fill the missing
space (to the right of the string). Default is " " (space).
Example-1:
txt = "banana"
x = txt.ljust(20)
print(x, "is my favorite fruit.")
Output: banana is my favorite fruit.
Example-2: txt = "banana" x = txt.ljust(20, "O")
print(x) Example-3: Output:
txt = "banana" x = txt.ljust(20, "so") print(x)
Output: bananaOOOOOOOOOOOOOO
23. lower():
• The lower() method returns a string where all characters are lower case.
• Symbols and Numbers are ignored.
Syntax: string.lower()
Example-1: txt = "Hello
my
FRIENDS" x = txt.lower()
print(x)
Output: hello my friends
24. replace():
• The replace() method replaces a specified phrase with another specified phrase.
• Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Syntax: string.replace(oldvalue, newvalue, count)
Here, oldvalue Required. The string to search for newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is
all occurrences.
Example-1:
25. split():
• The split() method splits a string into a list.
• You can specify the separator, default separator is any whitespace.
• Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax: string.split(separator, maxsplit)
Here, separator Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences" Example-1:
txt = "welcome to the jungle"
x = txt.split() print(x)
27. strip():
• The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end)
characters (space is the default leading character to remove)
Syntax: string.strip(characters)
Here, characters Optional. A set of characters to remove as leading/trailing characters.
Example-1:
txt = " banana "
x = txt.strip()
print("of all fruits", x, "is my favorite")
28. swapcase():
• The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax: string.swapcase() Example-1: txt = "Hello My Name Is Purple" x = txt.swapcase()
print(x)
29. title() :
• The title() method returns a string where the first character in every word is upper case. Like a
header, or a title.
• If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Syntax: string.title()
Example-1:
txt = "Welcome to my world"
x = txt.title()
print(x)
Output: Welcome To My World
Example-2:
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x)
Output: Hello B2B2B2 And 3G3G3G
30. upper():
• The upper() method returns a string where all characters are in upper case.
• Symbols and Numbers are ignored. Syntax: string.upper() Example-1:
txt = "Hello my friends"
x = txt.upper()
print(x)
Output: HELLO MY FRIENDS
31. rfind():
• The rfind() method finds the last occurrence of the specified value.
• The rfind() method returns -1 if the value is not found.
• The rfind() method is almost the same as the rindex() method. See example below.
Syntax: string.rfind(value, start, end)
Here, value Required. The value to search for start Optional. Where to start the search. Default is 0
End is Optional. Where to end the search. Default is to the end of the string Example-1: txt = "Mi
casa, su casa." x = txt.rfind("casa")
print(x)
Output: 12
Example-2:
txt = "Hello, welcome to my world."
x = txt.rfind("e", 5, 10)
print(x)
Output: 8
Example-3: txt = "Hello, welcome to my
world."
32. rindex():
• The rindex() method finds the last occurrence of the specified value.
• The rindex() method raises an exception if the value is not found.
• The rindex() method is almost the same as the rfind() method. See example below.
Syntax: string.rindex(value, start, end)
Here, Value i s Required. The value to search for start
Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example-1: txt = "Mi casa, su
casa." x =
txt.rindex("casa")
print(x)
Output: 12
Example-2: txt = "Hello, welcome to my
world." x = txt.rindex("e", 5, 10)
print(x)
Output: 8
33. rjust():
The rjust() method will right align the string, using a specified character (space is default) as the fill
character.
Syntax: string.rjust(length, character)
Here,
length Required. The length of the returned string
character Optional. A character to fill the missing space (to the left of the string). Default is " "
(space).
Example-1: txt = "banana"
x = txt.rjust(20)
print(x, "is my favorite fruit.")
Output: banana is my favorite fruit.
34. rsplit():
• The rsplit() method splits a string into a list, starting from the right.
• If no "max" is specified, this method will return the same as the split() method.
• Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
35. rstrip():
The rstrip() method removes any trailing characters (characters at the end a string), space is the
default trailing character to remove.
Syntax: string.rstrip(characters)
Here, characters Optional. A set of characters to remove as trailing
characters. Example-1:
txt = " banana "
x = txt.rstrip()
print("of all fruits", x, "is my favorite")
Output: of all fruits banana is my favorite
36. splitlines()
The splitlines() method splits a string into a list. The splitting is done at line breaks.
Syntax: string.splitlines(keeplinebreaks) Example-1: txt = "Thank you for the music\
nWelcome to the jungle" x = txt.splitlines(True)
print(x)
Output: ['Thank you for the music\n', 'Welcome to the jungle']
37. translate():
• The translate() method returns a string where some specified characters are replaced with the
character described in a dictionary, or in a mapping table.
• Use the maketrans() method to create a mapping table.
• If a character is not specified in the dictionary/table, the character will not be replaced. If you use
a dictionary, you must use ascii codes instead of characters.
Syntax: string.translate(table)
Here, table Required. Either a dictionary, or a mapping table describing how to perform the replace
38. zfill():
Syntax: string.zfill(len)
Here,
len Required. A number specifying the position of the element you want to remove.
Example-1:
txt = "50"
x = txt.zfill(10)
print(x)
Output: 0000000050
Example-2: a = "hello"
b = "welcome to the
jungle" c = "10.000"
print(a.zfill(10)) print(b.zfill(10))
print(c.zfill(10))
Output: 00000hello
welcome to the jungle
000010.000
When you perform arithmetic operations, you use the decimal number system. This system, also called
the base ten number system, uses the ten characters 0,1, 2, 3, 4, 5, 6, 7, 8, and 9 as digits.
The binary number system is used to represent all information in a digital computer. The two digits in
this base two number system are 0 and 1.Because binary numbers can be long strings of 0s and 1s.
Computer scientists often use other number systems, such as octal (base eight) and hexadecimal (base
16) as shorthand for these numbers.
Example:
Output:
• This algorithm repeatedly divides the decimal number by 2. After each division, the remainder (either a 0
or a 1) is placed at the beginning of a string of bits.
• 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.
• Using a text editor such as Notepad or TextEdit, you can create, view, and save data in a text file. Your
Python programs can output data to a text file.
• The data in a text file can be viewed as characters, words, numbers, or lines of text, depending on the
text file’s format and on the purposes for which the data are used.
• Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
• Python treats file differently as text or binary and this is important.
• Each line of code includes a sequence of characters and they form text file.
• It ends the current line and tells the interpreter a new one has begun.
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.There are four different methods (modes)
for opening a file:
1. "r" - Read - Default value. Opens a file for reading, error if the file does not exist
2. "a" - Append - Opens a file for appending, creates the file if it does not exist
3. "w" - Write - Opens a file for writing, creates the file if it does not exist
4. "x" - Create - Creates the specified file, returns an error if the file exists
• In addition you can specify if the file should be handled as binary or text mode
1. "t" - Text - Default value. Text mode
2. "b" - Binary - Binary mode (e.g. images)
Python File Open:
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the
file.
Syntax: f = open("filename",”mode”)
Example: f = open("demofile.txt", "rt")
Here , "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error. To open a file for reading it is enough to
specify the name of the file:
Close Files: It is a good practice to always close the file when you are done with it. Example:
Close the file when you are finish with it: f = open("demofile.txt", "r") print(f.readline()) f.close()
Python File Write: To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file "w" -
Write - will overwrite any existing content
Python Delete File: To delete a file, you must import the OS module, and run its os.remove() function:
Example: Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Delete Folder: To delete an entire folder, use the os.rmdir()
method Example: Remove the folder "myfolder" import os
os.rmdir("myfolder")
fileno() Returns a number that represents the stream, from the operating system's perspective
readline() Method:
The readline() method returns one line from the file.You can also specified how many bytes from the line
to return, by using the size parameter. Syntax: file.readline(size) Here,
size Optional. The number of bytes from the line to return. Default -1, which means the
whole line.
Example: 1 f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Example: 2 Return only the five first bytes from the first line: f
= open("demofile.txt", "r") print(f.readline(5))
readlines() Method:
The readlines() method returns a list containing each line in the file as a list item.
Use the hint parameter to limit the number of lines returned. If the total number of bytes returned exceeds
the specified number, no more lines are returned.
Syntax: file.readlines(hint)
Here,
hint Optional. If the number of bytes returned exceed the hint number, no more lines will be returned.
Default value is -1, which means all lines will be returned.
Output:['Hello! Welcome to demofile.txt\n', 'This file is for testing purposes.\n', 'Good Luck!']
tell() Method:
The tell() method returns the current file position in a file stream.
Syntax: file.tell()
Output:
The sum is 55