23CS101T PSPP - Unit 3
23CS101T PSPP - Unit 3
3.1 CONDITIONALS:
Boolean values:
Boolean values are the two constant objects False and True. They are used to represent truth
values (although other values can also be considered false or true). In numeric contexts (for
example when used as the argument to an arithmetic operator), they behave like the integers
0 and 1, respectively.
A string in Python can be tested for truth value.
The return type will be in Boolean value (True or False)
To see what the return value (True or False) will be, simply print it out.
str="Hello World"
print( str.isalpha()) #False #check if all char in the string are alphabetic
Condiotional If Statement:
An if statement is a selection control statement based on the value of agiven Boolean expression.
The if structure may include 1 statements or n statements enclosed withinthe if block.
First the test expression is evaluated. If the test expression is true , the statements of if block are
executed, otherwise these statements will beskipped and the execution will jump to statement X.
Python supports if-elif-else statements to test additional conditions apartfrom the initial test
expression.
The if-elif-else construct works in the same way as a usual if-else statement. If-elif-else construct
is also known as nested-if construct.
3.3 ITERATIVE STATEMENTS:
Iterative statements are decision controlstatements that are used to
repeat the execution of a list of statements.
Python language supports two types of iterative statements as follows:
• While loop
• For loop
While loop:
The while loop provides a mechanism to repeat one or more statements while a particular condition is
true.
For loop:
For loop provides a mechanism to repeat a task until a particular condition isTrue. It is usually known as
a determinate or definite loop because the programmer knows exactly how many times the loop will
repeat.
The for...in statement is a looping statement used in Python to iterate over asequence of objects.
Syntax:
for iterating_var in sequence:
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 Chart :
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
OUTPUT
The sum is: 183
The Range() function:
The range() function is a built-in function in Python that is used to iterate over a sequence of
numbers.
The syntax of range() : range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending with one
less than the number end.
The step argument is optional
By default, every number in the range is incremented by 1 but we can specify a different
increment using step.
It can be both negative and positive, but not zero.
• If range() function is given a single argument, it produces an object with valuesfrom 0 to argument-1.
For example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to thesecond. For example,
range(0,10).
• If range() has three arguments then the third argument specifies the interval ofthe sequence produced.
In this case, the third argument must be an integer. For example, range(1,20,3).
Examples:
NESTED LOOPS:
The break statement is used to terminate the execution of the nearestenclosing loop in which it
appears.
When compiler encounters a break statement, the control passes to thestatement that follows the
loop in which the break statement appears.
SYNTAX:break
EXAMPLE:
SYNTAX:continue
The Pass Statement:
Pass statement is used when a statement is required syntactically but nocommand or code has to
be executed.
It specifies a null operation or simply No Operation (NOP) statement.
It remains the same when the pass statements are executed.
SYNTAX:pass
EXAMPLE:
If the else statement is used with a for loop, the else statement is executedwhen the loop has
completed iterating.
When the else statement is executed with the while loop, the else
statement is executed when the condition becomes false.
3.5 FUNCTIONS:
A function is a block of organized and reusable program code that performs a single , specific
and well defined task.
Python enables its programmers into functions , each of which can bewritten more or less
independently of the others.
In the above figure (a), a func1() is called to perform a well-defined tasks.When the func1() is
called , the program control is passed to the first statement in the function.
All the statements in the functions are executed and then the programcontrol is passed to the
statement following the one that called the function.
BUILT-IN FUNCTIONS:
A function is a group of statements that performs a specific task. Theycan either be user-defined
or already built into python interpreter.
The python interpreter has a number of functions built into it that arealways available.
FUNCTION DESCRIPTION
abs() Returns the absolute value of a number
ascii() Returns a string containing a printable representation ofan object,but
escape the non-ASCII characters
Sum() Sums the items of an iterable from left to right and returnsthe total
USER-DEFINED FUNCTIONS
The common terminologies used under functions are listed as follows.
• A function, f that uses another function g, is known as the calling function
and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it issaid to return that result.
• The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters,else not.
FUNCTION DEFINITION:
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed withinparentheses.
• The first statement of a function can be an optional statement - the docstring
describe what the function does.
• The code block within the function is properly indented to form the blockcode.
• A function may have a return[expression] statement. That is, the returnstatement is optional.
• You can assign the function name to a variable. Doing this will allowyou to call same function using
the name of that variable.
The syntax of a function definition can be given as:
EXAMPLE:
FUNCTION CALL:
The function call statement invokes the function.
When a function is invoked the program control jumps to the calledfunction to execute the
statements that are a part of that function.
Once the called function is executed, the program control passes back tothe calling function.
The syntax of calling a function that does not accept parameters is simplythe name of the
function followed by parenthesis which is given as,
function_name()
Function call statement has the following syntax when it acceptsparameters.
PASSING PARAMETERS:
A function can be called by using the following type of formal arguments.
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
REQUIRED ARGUMENTS:
In the required arguments, the arguments are passed to a function incorrect positional order.
Also, the number of arguments in the function call should exactly match with the number of
arguments specified in the function definition
KEYWORD ARGUMENTS:
When we call a function with some values, the values are assigned to thearguments based on
their position.
Python also allow functions to be called using keyword arguments inwhich the order (or
position) of the arguments can be changed.
The values are not assigned to arguments according to their position butbased on their name (or
keyword).
Keyword arguments are beneficial in two cases.
def display(name,age,salary):
print("name :",name)
print("age :",age)
print("salary :",salary)
n="xyx"
a=30
s=123456
display(salary=s , name=n , age=a)
OUTPUT:
name : xyx
age : 30
salary : 123456
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
OUTPUT:
30
return[expression]
1)Using Tuple: A Tuple is a comma separated sequence of items. It is created with orwithout (). Tuples are
immutable.
def fun():
str = "geeksforgeeks"
(
x = 20
return (str, x)
y = fun()
print(y)
2. Using a list: A list is like an array of items created using square brackets. Theyare different from arrays
as they can contain items of different types. Lists are different from tuples as they are mutable.
def fun():
str = "geeksforgeeks"
x = 20
Example:
return [str, x];
['geeksforgeeks', 20]
list = fun()
print(list)
def fun():
d = dict();
d['str'] = "GeeksforGeeks"
d['x'] = 20 Example:
d = fun()
print(d)
3.8 VARIABLE SCOPE:
Step5:END-IF
Step1:Start the program
Step6:Stop
Step2:Procedure TowerOfHanoi (disk,source, destination,auxilary)
Step3:IF n==1,
Step3.1:Move disk from source to destination
Step4:ELSE
Step4.1:TowerOfHanoi (n-1,source,auxilary,dest)
Step4.2:Move disk from source to destination
Step4.3:TowerOfHanoi (n-1 auxilary, destination,source)
Step5:END-IF
Step6:Stop
`
PROGRAM:
`
3.10 STRINGS:
String is a sequence which is made up of one or more UNICODE characters.
The character can be a letter, digit, whitespace or any other symbol.
Python has a built-in string class named "str" that has many usefulfeatures.
A string can be created by enclosing one or more characters in single, double or triple
quote.
To declare and define a string by creating a variable of string type:
>>> name = "India"
>>> graduate = 'N’
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
>>>country = name nationality = str("Indian")
Accessing Characters in a String - Index
Individual characters in a string are accessed using the subscript ([ ])operator. The
expression in brackets is called an index.
The index specifies a member of an ordered set and in this case it specifies the character
to be accessed from the given set of characters inthe string.
The index of the first character is 0 and that of the last character is n-1where n is the
length of the string.
The index must be an integer (positive, zero or negative).
Negative indices are used when the characters of the string are accessedfrom right to left.
Starting from right hand side, the first character has the index as -1 andthe last character
has the index –n where n is the length of the string.
>>> str[-3]
>>> r
The index can also be an expression including variables and operators butthe expression
must evaluate to an integer.
A substring of a string is called a slice. The slice operation is used torefer to sub-parts of
sequences and strings within the objects.
Slicing operator [ ] is used to access subset of string from original string
Syntax :
`
string_var [START INDEX : END INDEX: STEP]
Ex. str[n : m : k] returns every kth character extracted fromthe string starting from
index n (inclusive) and ending at m (exclusive).
By default, the step size is one
Note :
1. The numbers of characters in the substring will always be equal tom-n
>>> str1= "Hello World!"
#index that is too big is truncated down to#the end of the string
>>> str1[3:20]
>>> 'lo World!'
2. If the first index is not mentioned, the slice starts from index 0.
>>> str1[:5]
>>> 'Hello'
3. If the second index is not mentioned, the slicing is done till thelength of the string.
>>> str1[6:]
>>>'World!'
4. Negative indexes can also be used for slicing.
>>> str1[-6:-1]
>>> 'World'
Traversing a String:
To access each character of a string or traverse a string, for loop and whileloop are used
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
>>> Hello World! #output of for loop
for loop starts from the first character of the string str1 andautomatically ends when the
last character is accessed.
iii. Membership : Python has two membership operators 'in' and 'notin'. The 'in'
operator takes two strings and returns True if the firststring appears as a substring
in the second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
>>> True
>>> 'My' in str1
>>> False
The 'not in' operator also takes two strings and returns True if thefirst string does
not appear as a substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
>>> True
>>> 'Hello' not in str1
>>> False
iv. Comparing strings: Two strings can be compared using relationaloperators which
return True or False
`
v. len():This function returns the length of the string.Ex:>>>t=”Welcome”
>>> len(t)
7
vi. max( ) : This function returns the maximum alphabetical characterfrom the string
vii. min( ) : This function returns the minimum alphabetical characterfrom the string
Ex: >>> max(t)
'o'
>>> min(t)
'e'
viii. ord( ) : This function returns the ASCII code of thecharacter
1. str.lower ( ) : Return a string with all the cased characters converted tolowercase.
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '
2. str.upper ( ): Return a string with all the cased characters converted touppercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '
3. str.istitle ( ) : Return True, if the string is title cased, otherwise False isreturned.
>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True
4. str.capitalize ( ) : Return a string with its first character capitalized andthe rest lowercase.
`
>>> str=" this Is stRing example ....... wow ! ! ! "
>>> str.capitalize ( )
' This is string example ...... wow ! ! !
5. str.title ( ) : Return a title cased version of the string, where words startwith an uppercase
character and the remaining characters are lowercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! !
7. str.isalnum( ) : Return true if all characters in the string arealphanumeric, false otherwise.
8. str. isalpha ( ) : Return true if all characters in the string arealphabetic, false otherwise.
9. str.isdigit( ) : Return True, if all characters in the string are digits,otherwise False is
returned.
>>> str="this2009"
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True
10. str . isspace ( ) : Return True, if there are only whitespace characters inthe string,
otherwise False is returned.
>>> str= " "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False
11. str.islower ( ) : Return True, if all cased characters in the string are inlowercase, false
`
otherwise.
>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True
12. str.isupper ( ) : Return True, if all cased characters in the string areuppercase, otherwise
False is returned.
14. str.find(sub[,start[,end]]) : Return the lowest index in the string where the sub-string sub
is found, such that sub is contained in the slice s [ start:end]. Optional arguments start and
end are interpreted as in slice notation.Return -1, if the sub is not found.
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15
15. str.index ( sub [ , start [ , end ] ] ) : Return the lowest index in the stringwhere the sub-
string sub is found, such that sub is contained in the slice s[ start: end] (like find ( ) but
raise ValueError when the sub-string is not found)
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 )
15
>>> str1.index ( str2 , 10 )
15
16. str.rfind(sub[,start[, end]] ) : Return the highest index in the string where the sub-string
sub is found, such that sub is contained within s [start: end]. Optional arguments start and
end are interpreted as in slicenotation. Return -1 on failure.
`
>>> str1=" this is really a string example. . . .wow !
! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
17. str. join ( iterable ) : Return a string which is the concatenation of the
strings in the iterable. The separator between elements is the string str providing this
method.
>>> str="-"
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq)
' a-b-c '
18. str.replace ( old , new [ , count ] ) : Return a string with all occurrences of substring old
replaced by new. If the optional argument count is given, only the first count occurrences
are replaced.
>>> str=" this is string example. . . . wow ! ! ! this
is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was
really string’
19. str.center ( width [ , fillchar ] ) : Return centered string of length width. Padding is done
using optional argument fillchar (default is a space).
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'
20. str.ljust ( width [ , fillchar ] ) : Return the string left-justified in a stringof length width.
Padding is done using the optional argument fillchar (default is a space). The original
string is returned if the width is less thanor equal to len(str).
>>> str="this is string example. . . .wow! ! ! "
>>> str . ljust (50, ' 0 ' )
'this is string example. . . .wow ! !
!000000000000000000 '
21. str.rjust ( width [ ,fillchar ] ) : Return the right-justified string of lengthwidth. Padding is
done using the optional argument fillchar (default is a space). The original string is
returned if the width is less than or equal to len(str).
>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! !
! '
22. str.strip ( [ chars ] ) : Return a string with the leading and trailing characters removed.
The chars argument is a string specifying the set of characters to be removed. If omitted or
None, the chars argument defaultsto removing whitespace.
`
>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '
23. str.split ( [ sep [ , maxsplit ] ] ) : Return a list of the words from the string using sep as
the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will
have at most maxsplit + 1 elements). If maxsplit is not specified or -1, then all possible
splits are made. If sep is not specified or None, any whitespace string is a separator.
24. str. splitlines ( [ keepends ] ) : Return a list of the lines in the string, breaking at line
boundaries. Line breaks are not included in the resultinglist unless keeping is given.
Programs
a=input("Enter a string:")b=a.lower()
c=b[::-1]
if b==c:
print(a,"is a palindrome")else:
print(a,"is not a palindrome")
Output:
Enter a string: RadarRadar is a palindrome
def linear(lst,sval):
for i in range(len(lst)):
if lst[i]==sval:
return(i)
return -1
`
def
is_anagram(s1
,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return
Trueelse:
return False
Output:
enter 1st string:Ajax
enter 2nd string:Jaxa
Is Anagram: True
Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the
characterfrom the string and return the new string.
Program:
def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))
Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz
Write a Python program to count Uppercase, Lowercase, special character and numeric
values in a given string.
Programs:
`
v='Shop open@3pm'
s=v.replace(" ","")
a=0
b=0
c=0
d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)
Output:
digit values: 1
`
uppercase letters: 1
lower case letters: 9
special charc: 1
str1="".join(str.split())vowel="aeiou"
vcount=0ccount=0
for i in str1:
if i.lower() in vowel:vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount) print("No. of consonents in string ",str
,ccount)
Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string 11