Python Notes (Unit 2)
Python Notes (Unit 2)
Control Flow Statements: if, if-else, if-elif-else, while loop, range() Function, for loop, continue
and break statements.
Strings: Creating and Storing Strings, Basic String Operations, String Slicing and Joining, String
Methods, Formatting Strings
2. if-else statement: When the condition is true, then code associated with if statement will
execute, otherwise code associated with else statement will execute.
Example:
a = 10
b = 20
if a>b:
print(“a is greater”)
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
LOOPS in PYTHON
2 For loop This type of loop executes a code block multiple times and abbreviates
the code that manages the loop variable.
1 Break statement This command terminates the loop's execution and transfers the
program's control to the statement next to the loop.
2 Continue This command skips the current iteration of the loop. The
statement statements following the continue statement are not executed once
the Python interpreter reaches the continue statement.
Example
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
INTRODUCTION
When a sequence of characters is grouped together, a meaningful string is created. Thus, a
string is a sequence of characters treated as a single unit
The following example illustrates the use of the basic function on strings.
>>> a = “PYTHON”
>>> len(a) #Return length i.e. number of characters in string a
6
>>> min(a) #Return smallest character present in a string
‘H’
>>> max(a) #Return largest character present in a string
‘Y’
Example
>>> S1=”Python”
>>>S1[0] #Access the first element of the string.
‘P’
>>>S1[5] #Access the last element of the String.
‘n’
Note: Consider a string of length ‘n’, i.e. the valid indices for such string are from 0 to n-1. If you
try to access the index greater than n-1, Python will raise a ‘string index out of range’ error.
Example
>>> S=”PYTHON”
>>> S[-1]#Access the last character of a String ‘S’
‘N’
>>> S[-2]
‘O’
>>> S[-3]
‘H’
>>> S[-4]
‘T’
>>> S[-5]
‘Y’
>>> S[-6]#Access the First character of a String ‘S’
‘P’
PROGRAM
S=”India”
index=0
while index <len(S):
print(S[index],end=””)
index=index+1
Output
India
IMMUTABLE STRINGS
Character sequences fall into two categories, i.e. mutable and immutable. Mutable means
changeable and immutable means unchangeable. Hence, strings are immutable sequences of
characters.
Example
Str1=”I Love Python”
Str1[0]=”U”
print(Str1)
ERROR: TypeError: ‘str’ object does not support item assignment.
Example
>>> S=”IIT-BOMBAY”
>>> S[4:10] #Returns a Subset of a String
‘BOMBAY’
Name_of_Variable_of_a_String[Start_Index:End_Index:Step_Size]
Example
>>>S=”IIT-BOMBAY”
>>> S[0:len(S):2]
>>>’ITBMA’
2. The * Operator:
The multiplication (*) operator is used to concatenate the same string multiple times. It is also
called repetition operator.
Example:
>>> S1=”Hello”
>>> S2=3*S1 #Print the String “Hello” three times
>>> S2 ‘HelloHelloHello’
Note: S2=3*S1 and S2=S1*3 gives same output 3.
Python 3 has added a new string method called format() method. Instead of % we can use {0},
{1} and so on. The syntax for format() method is:
template.foramt(P0,P1,…………,k0=V0,K1=V1…}
whereas the arguments to the .format() method are of two types. It consists of zero or more
positional arguments Pi followed by zero or more keyword arguments of the form, Ki =Vi.
Testing String
A string may contain digits, alphabets or a combination of both of these. Thus, various methods
are available to test if the entered string is a digit or alphabet or is alphanumeric.
bool isalnum()
Returns True if characters in the string are alphanumeric and there is at least one character.
Example:
>>>S=”Python Programming”
>>>S.isalnum()
False
>>> S=”Python”
>>>S.isalnum()
True
bool isalpha()
Returns True if the characters in the string are alphabetic and there is at least one character.
Example:
>>> S=”Programming”
>>>S.isalpha()
True
>>> S=”1Programming”
>>>S.isalpha()
False
bool isdigit()
Returns True if the characters in the string contain only digits.
Example:
>>> Str1=”1234”
>>> Str1.isdigit()
True
>>> Str2=”123Go”
>>> Str2.isdigit()
False
bool islower()
Returns True if all the characters in the string are in lowercase.
Example:
>>> S=”hello”
>>>S.islower()
True
bool isupper()
Returns True if all the characters in the string are in uppercase.
Example:
>>> S=”HELLO”
>>>S.isupper ()
True
bool isspace()
Returns true if the string contains only white space characters.
Example:
>>> S=” “ >>>S.isspace()
True
>>> Str1=”Hello Welcome to Programming World”
>>> Str1.isspace ()
False
Searching Substring in a String
Formatting String
str center(int width)
Returns a copy of the string centered in a fi eld of the given width.
Example
>>> S1=”APPLE MACOS” #Place the string S1 in the center of a string with 11 characters
>>> S1.center(15)
‘APPLE MACOS’