Python Workshop-Day2
Python Workshop-Day2
Python Workshop-Day2
Statement and
String
Manipulation
22/06/2018
Workshop on “Introduction to
Python”
Department Of
Computer Science
Engineering
SKFGI, Mankundu
Control statements:
In general, statements are executed sequentially: The first statement in a
function 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.
Programming languages provide various control structures that allow for
more complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement −
3 nested loops
You can use one or more loop inside any another while, for or
do..while loop.
1.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 expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
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.
Program-1:
count = 0
while count < 9:
print ('The count is:', count)
count = count + 1
print ("Exit from loop")
output:-
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Exit from loop
Program-2
print("enter the number")
x=(int)(input())
f=1
while x > 0:
f=f * x
x= x - 1
print(f)
output:-
enter the number
6
factorial is 720
Program-3
print("enter the number")
x=(int)(input())
rev=0
while x > 0:
r=x % 10
rev=rev*10+r
x= x // 10
print("reverse is",rev)
output:-
enter the number
123
reverse is 321
Program-4
print("enter the number")
x=(int)(input())
f=x
rev=0
while x > 0:
r=x % 10
rev=rev*10+r
x= x // 10
print("reverse is",rev)
if (f == rev):
print(f ," is palindrome")
else:
print(f ," is not palindrome")
output:-
enter the number
121
reverse is 121
121 is palindrome
output:-
enter the number
123
reverse is 321
123 is not palindrome
Program-5
#Fibonacii Series upto n terms
print("enter the value of n")
n=(int)(input())
a=0
b=1
if(n==1):
print(a)
if(n==2):
print(a)
print(b)
if(n>2):
i=1
print(a)
print(b)
while i<=n-2:
c=a+b
a=b
b=c
print(c)
i=i+1
output:-
enter the value of n
10
0
1
1
2
3
5
8
13
21
34
2.For loop:-
For loop is used for iterating over a sequence (that is either a list, a tuple
or a string). To loop through a set of code a specified number of times, we
can use the range() function which returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by default), and ends
at a specified number.
Program-1
for x in range(6):
print(x)
output:-
0
1
2
3
4
5
Program-2
for x in range(2,6):
print(x)
output:-
2
3
4
5
Program-3
for x in range(2,16,3):
print(x)
output:-
2
5
8
11
14
Program-4
print("enter the range")
x=(int)(input())
for i in range(1,x,2):
print(i)
output:-
enter the range
10
1
3
5
7
9
Program-5
print("enter the range")
x=(int)(input())
f=1
for i in range(1,x+1):
f=f*i
print(f)
output:-
enter the range
5
120
Program-6
print("enter the number")
x=(int)(input())
rev=0
for i in range(x,0,-1):
r=x%10
rev=rev*10+r
x=x//10
if x==0:
break
print(rev)
/*alternative*/
reverse = ''
num = input()
for i in range(len(num), 0, -1):
reverse += num[i-1]
print(int(reverse))
output:-
enter the number
123
321
Nested loop:-
Program-1
*
**
***
****
print("enter the number")
n=(int)(input())
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print("")
Program-2
print("enter the number")
n=(int)(input())
for i in range(n,1,-1):
for j in range(1,i,1):
print("*",end=" ")
print("")
output:-
enter the number
5
****
***
**
*
3.Break statement:-It terminates the current loop and resumes execution
at the next statement, just like the traditional break statement in C. The
most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops. If you are using nested loops, the break statement
stops the execution of the innermost loop and start executing the next line
of code after the block.
Program-1
for x in "Python":
if( x == 'h'):
break
print("Current Letter :", x)
output:-
Current Letter : P
Current Letter : y
Current Letter : t
Program-2
a = 10
while a > 0:
print ('value of a is:', a)
a = a -1
if (a == 5):
break
print ("Happy ending!")
output:-
value of a is: 10
value of a is: 9
value of a is: 8
value of a is: 7
value of a is: 6
Happy ending!
Program-1
for i in range(0,10):
if i==5:
continue
print(i)
print("end")
output:-
0
1
2
3
4
6
7
8
9
end
Program-2
for a in 'Python':
if (a == 'h'):
continue
print ('Current Letter :', a)
output:-
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
5.Pass statement:- The pass statement in Python is used when a
statement is required syntactically but you do not want any command or
code to execute. However, nothing happens when pass is executed.
Suppose we have a loop or a function that is not implemented yet, but we
want to implement it in the future. They cannot have an empty body. The
interpreter would complain. So we use the pass statement to construct a
body that does nothing.
Program-1
for a in 'Python':
if (a == 'h'):
pass
print ('This is pass block')
print ('Current Letter :', a)
String:-
Note: String are immutable which means that once created they can not
changed. Whenever we try to modify an existing string variable , a new
string created .
s1 ="listen"
print(s1,id(s1))
s1+= "silent"
print(s1,id(s1))
Output:
listen 35714656
listensilent 36958064
6.Accessing Python Strings
o In Python, Strings are stored as individual characters in a contiguous
memory location.
o The benefit of using String is that it can be accessed from both the
directions (forward and backward).
o Both forward as well as backward indexing are provided using Strings
in Python.
o Forward indexing starts with 0,1,2,3,....
o Backward indexing starts with -1,-2,-3,-4,....
1. str[0]='P'=str[-6] , str[1]='Y' = str[-
5] , str[2] = 'T' = str[-
Example 4] , str[3] = 'H' = str[-3]
2. str[4] = 'O' = str[-2] , str[5] = 'N' = str[-1].
Program-1
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
output:-
var1[0]: H
var2[1:5]: ytho
Program-2 program to retrieve String in reverse as well as normal form.
name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print name[i],"\t",name[n]
i+=1
Output:
R t
a a
j j
a a
t R
>>>
7. Python Strings Operators
To perform operation on string, Python provides basically 3 types of
Operators that are given below.
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
Expression Output
Eg:
'abc' + 3
>>>
output:
Replication operator uses two parameters for operation, One is the integer
value and the other one is the String argument.
The Replication operator is used to repeat a string number of times. The
string will be repeated the number of times which is given by the integer
value.
>>> print(5*"Vimal" )
Output:
'VimalVimalVimalVimalVimal'
Expression Output
"soono"*2 'soonosoono'
3*'1' '111'
'$'*5 '$$$$$'
NOTE: We can use Replication operator in any way i.e., int * string or
string * int. Both the parameters passed cannot be of same type.
>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True
'sayon'>'sazon'
False
Explanation:
The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is
65,B is 66,C is 67 and so on. The comparison between strings are done on
the basis on ASCII value.
Python String slice can be defined as a substring which is the part of the
string. Therefore further substring can be obtained from a string.
<string_name>[startIndex:endIndex],
<string_name>[:endIndex],
<string_name>[startIndex:]
Python String Slice Example 1
>>> str="Nikhil"
>>> str[0:6]
'Nikhil'
>>> str[0:3]
'Nik'
>>> str[2:5]
'khi'
>>> str[:6]
'Nikhil'
>>> str[3:]
'hil'
Note: startIndex in String slice is inclusive whereas endIndex is
exclusive.
String slice can also be used with Concatenation operator to get whole
string.
Program-1
print(str[2:15])
print(str[2:15:1])
print(str[2:105:2])
print(str[2:15:3])
output:-
lcome to the
lcome to the
loet h ol fpto
lmtt
Program-2 reverse of a string using slice operation
print(str[::-1])
output:-
nohtyp fo dlrow eht ot emoclew
Program-1
string1="Welcome to SSSIT"
substring1="IT"
substring2="to"
print (string1.endswith(substring1) )
print (string1.endswith(substring2,2,16))
Output:
>>>
True
False
9.15 isupper():-It returns False if characters of a string are in Upper case,
otherwise False.
Program-1
string1="Hello Python"
print (string1.isupper())
string2="WELCOME TO"
print (string2.isupper())
Output:
>>>
False
True
9.16. isspace(): It returns True if the characters of a string are whitespace, otherwise false.
Program-1
string1=" "
print (string1.isspace())
string2="WELCOME TO WORLD OF PYT"
print (string2.isspace())
Output:
>>>
True
False
>>>
9.17 len(string):-
It returns the length of a string.
Program-1
string1=" "
print (len(string1))
string2="WELCOME TO SSSIT"
print (len(string2))
Output:
>>>
4
16
>>>
9.18 lower():-
It converts all the characters of a string to Lower case.
Program-1
string1="Hello Python"
print (string1.lower() )
string2="WELCOME TO SSSIT"
print (string2.lower())
Output:
>>>
hello python
welcome to sssit
>>>
9.19: startswith(string,start index, end index):-
This method returns a Boolean value if the string starts with given str
between begin and end.
Program-1
string1="Hello Python"
print (string1.startswith('Hello'))
string2="welcome to SSSIT"
print (string2.startswith('come',3,7))
Output:
>>>
True
True
>>>
9.20 lstrip():-
It removes all leading whitespace of a string and can also be used to remove
particular character from leading.
Program-1
string1=" Hello Python"
print (string1.lstrip())
string2="@@@@@@@@welcome to SSSIT"
print (string2.lstrip('@'))
Output:
>>>
Hello Python
welcome to world to SSSIT
>>>
9.21rstrip() :-
It removes all trailing whitespace of a string and can also be used to remove
particular character from trailing.
Program-1
string1=" Hello Python "
print (string1.rstrip() )
string2="@welcome to SSSIT!!!"
print (string2.rstrip('!') )
Output:
>>>
Hello Python
@welcome to SSSIT
>>>
9.22strip():-It removes all trailing and leading whitespace of a string and
can also be used to remove particular character from trailing.
Program-1
string2="!!!welcome to SSSIT!!!"
print (string2.strip('!') )
Output: welcome to SSSIT
Program-1
str=”the world is beautiful”
print(str.title())
output: The World Is Beautiful
Program-1
str="abc,def,ghi,jkl"
print(str.split(','))
Sample Program:-
output: ['abc', 'def', 'ghi', 'jkl']
9.25 join(list):- it is just the opposite of spilt. The function joins a list of
string using the delimiter with which the function is invoked
Program-1
l=['abc', 'def', 'ghi', 'jkl']
print(','.join(l))
output: abc,def,ghi,jkl
9.26 enumerate(str):- returns an enumerate object that list the index and
value of all characters in the string as pair
Program-1
str="hello"
print(list(enumerate(str)))
output: [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
9.27 ljust(width, fillchar):- returns a string left-justified to a local of
width column. Column without characters are padded with the character
specified in the fill char argument.
Program-1
str="hello"
print(str.ljust(10,"*"))
output: hello*****
9.28 rjust(width, fillchar):- returns a string right-justified to a local of
width column. Column without characters are padded with the character
specified in the fill char argument.
Program-1
str="hello"
print(str.rjust(10,"*"))
output: *****hello
9.29 Center (width, fillchar):- returns a string with the original string
centered to a total width columns and filled with fillchar in column that not
have character
Program-1
str="hello"
print(str.center(10,"*"))
output: **hello***
s1 ="listen"
s2 ="silent"
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
output:-
The strings are anagrams.
6. To count the number of vowels and digits in a string:-
string=input("Enter string:")
vowels=0
count1=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
if(i.isdigit()):
count1=count1+1
print("Number of vowels are:")
print(vowels)
print("The number of digits is:")
print(count1)
output:-
Enter string:abcd1234
Number of vowels are:
1
The number of digits is:
4
7. WAP that encrypts a message by adding a key value to every
character (Caesar cipher)[take key=3]
str="Hello"
index=0
s=""
while index<len(str):
l=str[index]
s+=chr(ord(l)+3)
index+=1
print(s)
output:-
Khoor
8. WAP to check A PAN number format is valid or not
s=input('enter the PAN Card number')
s1=s[0:5]
s2=s[5:9]
s3=s[9]
if s1.isalpha()==True and s2.isdigit()== True and s3.isalpha()==True:
print("correct format of pan number")
else:
print("not a valid pan number")
output:-
enter the PAN Card number 120aumpg5d
not a valid pan number
Specifying Type
We can include more parameters within the curly braces of our syntax. We’ll
use the format code syntax {field_name:conversion},
where field_name specifies the index number of the argument to
the str.format() method that we went through in the reordering section,
and conversion refers to the conversion code of the data type that you’re
using with the formatter.
The conversion type refers to the the single-character type code that Python
uses. The codes that we’ll be using here are s for string, d to display decimal
integers (10-base), and f which we’ll use to display floats with decimal
places. You can read more about the Format-Specification Mini-
Language through Python 3’s official documentation.
Using Variables
So far, we have passed integers, floats, and strings into
the str.format() method, but we can also pass variables through the
method. This works just like any other variable.
17. nBalloons = 8
print("Sammy has {} balloons today!".format(nBalloons))
output: Sammy has 8 balloons today!
19.
a=5
b=6
print("So you are %d of %d" % (a, b))
output: So you are 5 of 6
Symbol Purpose Symbol Purpose
%c Char %o Octal
%d or %i Signed Decimal Integer %x or Hexadecimal integer
%X
%s string %e Exponential notation
%f Floating point number %g Short number in floating
point/ exponential number