Python 2
Python 2
In python, anything that you enclose between single or double quotation marks is considered a string. A
string is essentially a sequence or array of textual data. Strings are used when working with Unicode
characters.
Example
name = "Harry"
Output
Hello, Harry
NOTE: IT DOES NOT MATTER WHETHER YOU ENCLOSE YOUR STRINGS IN SINGLE OR DOUBLE QUOTES, THE OUTPUT REMAINS
THE SAME.
Sometimes, the user might need to put quotation marks in between the strings. Example, consider the
sentence: He said, “I want to eat an apple”.
How will you print this statement in python?: He said, "I want to eat an apple". We will definitely use single
quotes for our convenience
Multiline Strings
If our string has multiple lines, we can create them like this:
print(a)
print(name[0])
print(name[1])
print(character)
Above code prints all the characters in the string name one by one!
Example :
name = "Harry"
friend = "Rohan"
anotherFriend = 'Lovish'
apple = '''He said,
Hi Harry
hey I am good
"I want to eat an apple'''
Example:
fruit = "Mango"
len1 = len(fruit)
Output:
Mango is a 5 letter word.
String as an array
A string is essentially a sequence of characters also called an array. Thus we can access the
elements of this array.
Example:
pie = "ApplePie"
print(pie[:5])
Output:
Apple
Output:
Apple
Pie
pleP
ApplePie
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
D
13 - String methods
Python provides a set of built-in methods that we can use to alter and modify
the strings.
upper() :
The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print(str1.upper())
Output:
ABCDEFGHIJ
lower()
The lower() method converts a string to lower case.
Example:
str1 = "AbcDEfghIJ"
print(str1.lower())
Output:
abcdefghij
strip() :
The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print(str2.strip)
Output:
Silver Spoon
rstrip() :
the rstrip() removes any trailing characters. Example:
print(str3.rstrip("!"))
Output:
Hello
replace() :
The replace() method replaces all occurences of a string with another string.
Example:
print(str2.replace("Sp", "M"))
Output:
Silver Moon
split() :
The split() method splits the given string at the specified instance and returns
the separated strings as list items.
Example:
str2 = "Silver Spoon"
Output:
['Silver', 'Spoon']
capitalize() :
The capitalize() method turns only the first character of the string to
uppercase and the rest other characters of the string are turned to lowercase.
The string has no effect if the first character is already uppercase.
Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
capStr2 = str2.capitalize()
print(capStr2)
Output:
Hello
Hello world
center() :
The center() method aligns the string to the center as per the parameters
given by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50))
Output:
Welcome to the Console!!!
We can also provide padding character. It will fill the rest of the fill
characters provided by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))
Output:
............Welcome to the Console!!!.............
count() :
The count() method returns the number of times the given value has occurred
within the given string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
Output:
4
endswith() :
The endswith() method checks if the string ends with a given value. If yes then
return True, else return False.
Example :
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
Output:
True
We can even also check for a value in-between the string by providing start
and end index positions.
Example:
str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))
Output:
True
find() :
The find() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then return -1.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))
Output:
10
As we can see, this method is somewhat similar to the index() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then raise an exception.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
Output:
ValueError: substring not found
isalnum() :
The isalnum() method returns True only if the entire string only consists of A-
Z, a-z, 0-9. If any other characters or punctuations are present, then it returns
False.
Example 1:
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of A-
Z, a-z. If any other characters or punctuations or numbers(0-9) are present,
then it returns False.
Example :
str1 = "Welcome"
print(str1.isalpha())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are lower
case, else it returns False.
Example:
str1 = "hello world"
print(str1.islower())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given string
are printable, if not, then return False.
Example :
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains white
spaces, else returns False.
Example:
str1 = " " #using Spacebar
print(str1.isspace())
print(str2.isspace())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example:
str1 = "World Health Organization"
print(str1.istitle())
Output:
True
Example:
str2 = "To kill a Mocking bird"
print(str2.istitle())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are upper
case, else it returns False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
Output:
True
startswith() :
The endswith() method checks if the string starts with a given value. If yes
then return True, else return False.
Example :
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper case
are converted to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print(str1.swapcase())
Output:
pYTHON IS A iNTERPRETED lANGUAGE
title() :
The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())
Output:
He'S Name Is Dan. Dan Is An Honest Man.
14 – if Else conditions
if-else Statements
Sometimes the programmer needs to check the evaluation of certain expression(s), whether the
expression(s) evaluate to True or False. If the expression evaluates to False, then the program
execution follows a different path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into following types:
if
if-else
if-else-elif
nested if-else-elif.
Example:
applePrice = 210
budget = 200
else:
print("Alexa, do not add Apples to the cart.")
Output:
Alexa, do not add Apples to the cart.
elif Statements
Sometimes, the programmer may want to evaluate more than one condition, this can
be done using an elif statement.
Execute the block of code inside the first elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
Execute the block of code inside the second elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
.
.
.
Execute the block of code inside the nth elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
Execute the block of code inside else statement if none of the expression evaluates
to True. After execution return to the code out of the if block.
Example:
num = 0
print("Number is negative.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
print("Number is negative.")
else:
else:
print("Number is zero")
Output:
A match statement will compare a given variable’s value to different shapes, also referred to as
the pattern. The main idea is to keep on comparing the variable with all the present patterns
until it fits into one.
The case clause consists of a pattern to be matched to the variable, a condition to be evaluated
if the pattern matches, and a set of statements to be executed if the pattern matches.
Syntax:
match variable_name:
Example:
x=4
# if x is 0
case 0:
print("x is zero")
case 4 if x % 2 == 0:
case _:
print(x)
Output:
x % 2 == 0 and case is 4
16 - Introduction to Loops
Sometimes a programmer wants to execute a group of statements a certain number of times.
This can be done using loops. Based on this loops are further classified into following main
types;
for loop
while loop
for i in name:
Output:
A, b, h, i, s, h, e, k,
for x in colors:
print(x)
Output:
Red
Green
Blue
Yellow
range():
What if we do not want to iterate over a sequence? What if we want to use for loop for a
specific number of times?
Example:
for k in range(5):
print(k)
Output:
0
1
2
3
4
Here, we can see that the loop starts from 0 by default and increments at each iteration.
Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8
Quick Quiz
Explore about third parameter of range (ie range(x, y, z)
Example:
count = 5
print(count)
count = count - 1
Output:
5
Here, the count variable is set to 5 which decrements after each iteration. Depending upon
the while loop condition, we need to either increment or decrement the counter variable
(the variable count, in our case) or the loop will continue forever.
print(x)
x=x-1
else:
print('counter is 0')
Output:
5
counter is 0
Example
while True:
print(number)
break
Output
Enter a positive number: 1
-1
Explanation
This loop uses True as its formal condition. This trick turns the loop into an infinite
loop. Before the conditional statement, the loop runs all the required processing and
updates the breaking condition. If this condition evaluates to true, then the break
statement breaks out of the loop, and the program execution continues its normal
path.
18 - break statement
The break statement enables a program to skip over a part of the code. A break statement
terminates the very loop it lies within.
example
for i in range(1,101,1):
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
.
.
50 Mississippi
19 - Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to
occur.
example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
output
2
0
20 - Python Functions
A function is a block of code that performs a specific task whenever it is called. In bigger
programs, where we have large amounts of code, it is advisable to create or use existing
functions that make the program flow organized and neat.
Built-in functions
User-defined functions
Built-in functions:
These functions are defined and pre-coded in python. Some examples of built-in functions are
as follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.
User-defined functions:
We can create functions to perform specific tasks as per our needs. Such functions are called
user-defined functions.
Syntax:
def function_name(parameters):
pass
Create a function using the def keyword, followed by a function name, followed by a
paranthesis (()) and a colon(:).
Any statements and other code within the function should be indented.
Calling a function:
We call a function by giving the function name, followed by parameters (if any) in the
parenthesis.
Example:
name("Sam", "Wilson")
Output: