Applied Analytics using
Python
(Part-2)
range() function
• The range() function is a built-in function that
generates a sequence of numbers.
• It is commonly used in loops, particularly for loops,
to iterate over a sequence of numbers or to specify
the number of iterations.
• The range() function has several variations and can
be used with different arguments to create different
sequences of numbers.
|
range() function
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
• All arguments must be integers. You can not use
float number or any other type in a start, stop and
step argument of a range(). If any value is not an
integer, Python raises a TypeError exception.
• The step value must not be zero. If a step is zero
Python raises a ValueError exception.
|
for loop
• A for loop is a control flow structure allowing you to
iterate over a sequence of items or numbers.
• It's commonly used for tasks that involve repeating a
block of code a specific number of times or for
processing elements in a sequence (like a list, tuple,
or string).
|
for loop Example:
for number in range(1, 10):
Syntax: print(number)
for item in sequence:
# Code to execute for each item in the sequence
|
The else statement for loop
• In Python, a for loop is used to iterate over a
sequence (such as a list, tuple, string, or range) and
execute a code block for each item in the sequence.
• The else clause in a for loop is an optional part that
can be used to specify a block of code to run when
the loop completes all its iterations.
|
The else statement for loop Example:
for i in range(6):
print(i)
Syntax:
else:
for variable in sequence:
print("Loop is finished")
# Code to execute for each item in the sequence
else:
# Code to execute when the loop completes all
iterations
|
Nested loop
A nested loop is a loop inside another loop. It allows
you to perform iterations within iterations, creating a
multi-level loop structure. This can be particularly
useful when you need to work with combinations of
elements, iterate through two-dimensional data
structures (like matrices or grids), or perform
repetitive tasks involving multiple levels of
complexity.
|
Nested Loop Example:
for i in range(0, 5): # Outer loop for rows
Syntax: for j in range(i+1): # Inner loop for
for outer_item in outer_sequence: columns
for inner_item in inner_sequence: print('*',end='')
# Code to execute for each combination of print() # Add a line break after each
outer_item and inner_item row
|
Loop Control Statements
Loop control statements allow you to modify the
behavior of loops.
These statements control how and when a loop
executes its iterations.
Python supports the following control statements:
• Break
• Continue
• Pass
|
Break Statement Example:
for i in range(1, 11):
• The break statement is used within loops (e.g., for if i == 5:
and while loops).
break
• When a break statement is encountered inside a
loop, it immediately terminates the loop and exits it, print(i)
regardless of whether the loop's condition is still true.
• This is useful when you want to exit a loop
prematurely based on some condition.
|
Continue Statement Example:
for i in range(1, 11):
• The continue statement is also used within loops. if i % 2 == 0:
• When a continue statement is encountered, it skips continue
the current iteration of the loop. It proceeds to the print(i)
next iteration, ignoring any code that comes after it
within the current iteration.
• This is useful when you want to skip certain iterations
of a loop based on a condition.
|
Pass Statement Example:
for i in range(10):
• In Python, the pass statement is a placeholder
if i % 2 == 0:
statement that does nothing when executed.
pass
• It is used as a syntactical placeholder where
Python’s syntax expects some code, but you don't else:
want to execute any code at that point. print(i)
• It is a way to create a code structure without
specifying any instructions.
|
Introduction to Strings
Example:
• Strings are a sequence of ordered individual
characters in contiguous memory locations. Name = “Hello”
Or
• Single or double quotation marks surround string
Name = ‘Hello’
literals in Python. ‘hello' is the same as "hello“.
Or
• Python, unlike other languages, does not have Name = ‘’’Hello
a char type, so a single character is rendered hello
hi !! ’’’
simply by a string of length 1.
|
Introduction to Strings
• Strings in Python are considered an immutable
sequence of Unicode Characters. It cannot be
changed during the execution of the program.
• In Python, Strings are stored as individual
characters in a continuous memory location.
|
Indexing
Strings are sequences of characters, and you can access individual characters by their position (index)
within the string. Python uses zero-based indexing, which means the first character is at index 0.
Forward
Indexing
0 to N-1
Backward Indexing
-1 to -N
Slicing
• Used to retrieve a substring from the main string.
• Based on indexing
• Syntax: str_object[start_pos : end_pos ]
,str_object[start_pos : end_pos : step]
• Default start_pos = 0 ; end_pos = length of string ;
step = 1
• Never results in error.
• Returns an empty string if there is an error in
indexing.
|
String Operations Example:
Concatenation: Joining two or more strings using the + str1 = 'Hello'
operator. str2 = 'World'
result = str1 + ' ' + str2
print(result)
print(str1,str2)
|
String Operations Example:
Repetition: Repeat a string multiple times using the * Str1 = ‘Hello’
operator. result = str1 * 3
print(result)
|
String Methods
Method Description Example Result
var_str = "Education Learning" EDUCATION
upper() Converts the string to uppercase.
print(var_str.upper()) LEARNING
var_str = "Education Learning"
lower() Converts the string to lowercase. education learning
print(var_str.lower())
Capitalizes the first character of the var_str = "Education Learning"
capitalize() string and converts the rest to Education learning
lowercase. print(var_str.capitalize())
Capitalizes the first character of each var_str = "Education learning"
title() Education Learning
word in the string. print(var_str.title())
Returns the length (number of
len len("Education") 9
characters) of a string.
String Methods
Method Description Example Result
var_str = " Education
Removes leading and trailing learning "
strip() Education learning
whitespace.
print(var_str.strip())
var_str = " Education
learning " Education learning
lstrip() Removes leading whitespace.
print(var_str.lstrip())
var_str = " Education
rstrip() Removes trailing whitespace. learning " Education learning
print(var_str.rstrip())
Check if the string starts with var_str = "Education learning"
startswith(prefix) True
the specified prefix. print(var_str.startswith("Edu"))
Checks if the string ends with var_str = "Education learning"
endswith(prefix) False
the specified suffix. print(var_str.endswith("Edu"))
String Methods
Methods Description Example Result
Replaces all occurrences of old var_str = "Ramandeep"
replace(old,new) Samandeep
with new in the string. print(var_str.replace("R",“S"))
Returns the index of the first
var_str = "Happy
find(substring) occurrence of substring. Returns 6
learning"print(var_str.find("learn"))
-1 if not found.
Returns the number of non-
var_str = "Happy
count(substring) overlapping occurrences of 2
learning"print(var_str.count("n"))
substring in the string.
var_str =
Splits the string into a list of [‘Education',
split() "Education,learning"print(var_str.split(
substrings based on separator. 'learning']
","))
String Methods
Method Description Example Result
Returns True if all characters var_str = "Education"
isalpha() True
in the string are alphabetic. print(var_str.isalpha())
Returns True if all characters var_str = "Education"
isdigit() False
in the string are digits. print(var_str.isdigit())
Returns True if all characters var_str = "Education2024"
isalnum() in the string are alphanumeric True
(letters or digits). print(var_str.isalnum())
Returns True if all characters var_str = "Education"
isupper() False
in the string are uppercase. print(var_str.isupper())
Returns True if all characters var_str = "Education"
islower() False
in the string are lowercase. print(var_str.islower())
We are
Shaping Vibrant Bharat
A member of Grant Thornton International Ltd, Grant Thornton Bharat is at the forefront of helping reshape the values in
the profession. We are helping shape various industry ecosystems through our work across Assurance, Tax, Risk,
Transactions, Technology and Consulting, and are going beyond to shape more #VibrantBharat.
Our offices in India
Ahmedabad Bengaluru Chandigarh Chennai Dehradun Scan QR code to see our office addresses
Goa Gurugram Hyderabad Kochi Kolkata Mumbai [Link]
New Delhi Noida Pune
Connect
@Grant-Thornton-Bharat-LLP @GrantThorntonBharat @Grantthornton_bharat @GrantThorntonIN @GrantThorntonBharatLLP GTBharat@[Link]
with us
© 2024 Grant Thornton Bharat LLP. All rights reserved.
“Grant Thornton Bharat” means Grant Thornton Advisory Private Limited, a member firm of Grant Thornton International Limited (UK) in India, and those legal entities which are its related parties as defined by the Companies Act, 2013,
including Grant Thornton Bharat LLP.
Grant Thornton Bharat LLP, formerly Grant Thornton India LLP, is registered with limited liability with identity number AAA-7677 and has its registered office at L-41 Connaught Circus, New Delhi, 110001.
References to Grant Thornton are to Grant Thornton International Ltd. (Grant Thornton International) or its member firms. Grant Thornton International and the member firms are not a worldwide partnership. Services are delivered
independently by the member firms.