Unit-Ii-Python Theory Notes
Unit-Ii-Python Theory Notes
:1
PYTHON PROGRAMMING
UNIT-II
Control Flow Statements – If statement – If else statement – If elif else statement – nested if statement - while
loop – for loop – continue and break statements – catching exceptions using try and except statement – syntax
errors – exceptions – exception handling – Strings – str() function - Basic string operations – String
comparison – Built in functions using strings – Accessing characters in string – String slicing – String joining
– split() method – string traversing.
CONTROL FLOW STATEMENTS
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Decision-making statements in programming languages decide the direction of the flow of program
execution. In Python, if-else elif statement is used for decision making.
CONDITIONAL STATEMENTS
The decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
if statement
if statement is the most simple decision-making statement. It is used to decide whether a certain statement
or block of statements will be executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if
the value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:
if condition:
statement1
statement2
Here if the condition is true, if block will consider only statement1 to be inside its block.
Flowchart of Python if statement
As the condition present in the if statement is false. So, the block below the if statement is executed.
if-else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
While Loop
While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And
when the condition becomes false, the line immediately after the loop in the program is executed.
Syntax:
while expression:
statement(s)
While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of
times the loop is executed isn’t specified explicitly in advance. Statements represent 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. When a while loop
is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the
expr is checked again, if it is still true then the body is executed again and this continues until the expression
becomes false.
Example to calculate the sum of first ten numbers
num = 10
sum = 0
Output
i=1
while i <= num:
sum = sum + i
Sum of first 10 number is: 55
i=i+1
print("Sum of first 10 number is:", sum)
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this
purpose, we use three types of transfer statements.
1. break statement
2. continue statement
3. pass statements
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:8
Break Statement
The break statement is used inside the loop to exit out of the loop. It is useful when we want to terminate
the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution
time. Whenever the controller encountered a break statement, it comes out of that loop immediately.
Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body of the loop for
other numbers.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an
error. This error does not stop the execution of the program, however, it changes the normal flow of the
program.
Example: Output:
marks = 10000
# perform division with 0
a = marks / 0
print(a)
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
a = [1, 2, 3] Output
try:
print ("Second element = %d" %(a[1])) Second element = 2
print ("Fourth element = %d" %(a[3]))
except: An error occurred
print ("An error occurred")
In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list which
is not there and this throws an exception. This exception is then caught by the except statement.
except NameError:
print("NameError Occurred and Handled")
If you comment on the line fun(3), the output will be NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError occurs.
Try with Else Clause
In python, you can also use the else clause on the try-except block which must be present after all the except
clauses. The code enters the else block only if the try clause does not raise an exception.
Example: Try with else clause
def AbyB(a , b):
try: Output:
c = ((a+b) / (a-b)) -5.0
except ZeroDivisionError:
a/b result in 0
print ("a/b result in 0")
else:
print (c)
Finally Keyword
Python provides a keyword finally, which is always executed after the try and except blocks. The final block
always executes after normal termination of try block or after try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
try:
k = 5//0 # raises divide by zero exception. Output:
print(k) Can't divide by zero
except ZeroDivisionError:
print("Can't divide by zero") This is always executed
finally:
print('This is always executed')
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class
that derives from Exception).
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:11
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise
The output of the above code will simply line printed as “An exception” but a Runtime error will also
occur in the last due to the raise statement in the last line. So, the output on your command line will look
like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
STRINGS IN PYTHON
A string is a data structure in Python that represents a sequence of characters. It is an immutable data type,
meaning that once you have created a string, you cannot change it. Strings are used widely in many different
applications, such as storing and manipulating text data, representing names, addresses, and other types of
data that can be represented as text.
str( ) function
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
The computer does not understand the characters; internally, it stores manipulated character as the
combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called
the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides
triple-quotes to represent the string, but it is generally used for multiline string or docstrings.
Example:
Output:
str = "HELLO" H
E
print(str[0])
L
print(str[1]) L
print(str[2]) O
print(str[3]) IndexError: string index out of range
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
As shown in Python, the slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given string. Consider the
following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO'
is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
# Given String
Output:
str = "JAVATPOINT"
# Start Oth index to end JAVATPOINT
print(str[0:])
AVAT
# Starts 1th index to 4th index
print(str[1:5]) VA
# Starts 2nd index to 3rd index
JAV
print(str[2:4])
# Starts 0th to 2nd index TPO
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1.
The second rightmost index indicates -2, and so on.
T
str = 'JAVATPOINT'
I
print(str[-1]) NT
print(str[-3]) OIN
ATPOI
print(str[-2:])
TNIOPTAVAJ
print(str[-4:-1]) IndexError: string index out of range
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support
item assignment i.e., A string can only be replaced with new string since its content cannot be partially
replaced. Strings are immutable in Python.
Example
str = "HELLO" Output:
str[0] = "h" Traceback (most recent call last):
print(str) File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
However, in example 1, the string str can be assigned completely to a new content as specified in the
following example.
str = "HELLO"
print(str) Output:
str = "hello"
HELLO
print(str)
hello
As we know that strings are immutable. We cannot delete or remove the characters from the string. But
we can delete the entire string using the del keyword.
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
str = "Hello"
EXAMPLE:
String1 = "GeeksForGeeks" Output:
print("Initial String: ") Initial String:
print(String1) GeeksForGeeks
First character of String is:
# Printing First character G
print("\nFirst character of String is: ") Last cha racter of String is:
print(String1[0]) s
We can also reverse a string by using built-in join and reversed function.
Example
gfg = "pythonprogramming"
gfg = "".join(reversed(gfg))
print(gfg)
Output:
gnimmargorpnohtyp
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).
Example
String1 = "GeeksForGeeks"
print("Initial String: ") Output:
print(String1) Initial String:
GeeksForGeeks
# Printing 3rd to 12th character Slicing characters from 3-12:
print("\nSlicing characters from 3-12: ") ksForGeek
print(String1[3:12]) Slicing characters between 3rd and
2nd last character:
# Printing characters between ksForGee
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
String Comparison
To compare Strings in Python.
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the zeroth index
till the end of the string. It then returns a boolean value according to the operator used.
Example:
“Geek” == “Geek” will return True as the Unicode of all the
characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of
g is \u0067
“Geek” < “geek” will return True and
“Geek” > “geek” will return False
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")
Output:
True
True
False
False
The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3 were
the same therefore they the result is True in all the cases. After the object id of str1 is changed, the
result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1,
the answer will be false as their object IDs are different.
capitalize() Converts the first character of the string to a capital (uppercase) letter
expandtabs() Specifies the amount of space to be substituted with the “\t” symbol in the string
isalnum() Checks whether all the characters in a given string is alphanumeric or not
isnumeric() Returns “True” if all characters in the string are numeric characters
isprintable() Returns “True” if all characters in the string are printable or the string is empty
isspace() Returns “True” if all characters in the string are whitespace characters
rindex() Returns the highest index of the substring inside the string
rsplit() Split the string from the right by the specified separator
strip() Returns the string with both leading and trailing characters
zfill() Returns a copy of the string with ‘0’ characters padded to the left side of the string
string_name = "geeksforgeeks"
Output:
# Iterate over the string geeksforgeeks
for element in string_name:
print(element, end=' ') G
print("\n") E
E
# Code #2 K
string_name = "GEEKS" S
# Iterate over index
for element in range(0, len(string_name)):
print(string_name[element])
string = "hello"
# Create an iterator that returns the characters from index 1 to the end of the string
char_iter = itertools.islice(string, 0, None) Output
h
# Iterate over the selected characters e
for char in char_iter: l
print(char) l
o