UNIT-1 - Fundamentals of Python
UNIT-1 - Fundamentals of Python
WHAT IS PYTHON?
Python is a simple and easy to understand language which feels like reading simple
English.
This Pseudo code nature is easy to learn and understandable by beginners.
Python is a clear and powerful object-oriented programming language, comparable to
Perl, Ruby, Scheme, or Java.
In the late 1980s, Guido van Rossum dreamed of developing Python.
The first version of Python 0.9.0 was released in 1991 by Guido Van Rossum. Since
its release, Python started gaining popularity.
According to reports, Python is now the most popular programming language among
developers because of its high demands in the tech realm.
Features:-
Python Intrepeter:-
A python interpreter is a computer program that converts each high-level program
statement into machine code.
An interpreter translates the command that you write out into code that the computer can
understand.
Machines only understand machine code or machine language, a language represented by
strings of bits — 1s and 0s.
So how do we bridge the gap between what a human programmer writes and what the
machine understands and thus executes? By using an interpreter.
When using a Python interpreter, the programmer types in the command, the interpreter
reads the command, evaluates it, prints the results, and then goes back to read the
command.
Tokens
Tokens are the various elements in the Python program that are identified by Python interpreter.
A token is the smallest individual unit, or element in the Python program, which is identified by
interpreter. They are building blocks of the source code.
Python language supports the different types of tokens that are as follows:
Keywords (Reserved words) : True, False, None, class, continue, break, if, elif, else,
from, or, def, del, import, etc.
Identifier : User-defined names
Literals : String, Numeric, Boolean, Collection,
Delimeters : ( ), { }, [ ], :, ., =, ;, +=, -=, *=, /=, %=, etc.
Operators : +, -, *, **, /, %, <<, >>, etc.
Keywords:- (35+)
Keywords are the reserved words in Python. We cannot use a keyword as a variable name,
function name or any other identifier.
Here's a list of all keywords in Python Programming
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
The above keywords may get altered in different versions of Python. Some extra might get added
or some might be removed.
You can always get the list of keywords in your current version by typing the following in
the prompt.
Identifiers:-
Python Identifiers
Identifiers are the name given to variables, classes, methods(functions), etc.
For example,
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-in to
Python.
For example,
continue = 'Python'
The above code is wrong because we have used continue as a variable name.
Things to Remember
Python is a case-sensitive language.
This means, Variable and variable are not the same.
Always give the identifiers a name that makes sense.
While c = 10 is a valid name, writing count = 10 would make more sense, and it would be
easier to figure out what it represents when you look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.
Python Literals
Python Literals can be defined as data that is given in a variable or constant. Python Literals can
be defined as data that is given in a variable or constant
.
Python supports the following literals:
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes to create a string.
Example:
1. "Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.
Example:
1. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
There are two ways to create multiline strings:
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0
Output:
x is True
y is False
z is False
a: 11
b: 10
IV. Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for the end of lists in Python.
Example - Special Literals
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals,
and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square
brackets([]). We can store different types of data in a List.
Example - List literals
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
Dictionary:
o Python dictionary stores the data in the key-value pair.
o It is enclosed by curly-braces {} and each pair is separated by the commas(,).
Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
o Python tuple is a collection of different data-type. It is immutable which means it cannot
be modified after creation.
o It is enclosed by the parentheses () and each element is separated by the comma(,).
Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).
Example: - Set Literals
1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Python Operators
Operators are special symbols that perform operations on variables and values.
For example,
print(5 + 6) # 11
Here, + is an operator that adds two numbers: 5 and 6.
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
In the above example, we have used multiple arithmetic operators,
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
% to get the remainder
** to get a to the power b
# assign 5 to b
b=5
print(a)
# Output: 15
Here, we have used the += operator to assign the sum of a and b to a.
Similarly, we can use any other assignment operators as per our needs.
b=2
# equal to operator
print('a == b =', a == b)
or a or b Logical OR:
True if at least one of the operands is True
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
5. Python Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit,
hence the name.
For example, 2 is 10 in binary, and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x 0010 1000)
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
Output
In the above example, we have created three variables named num1, num2 and num3 with
values 5, 5.0, and 1+2j respectively.
We have also used the type() function to know which class a certain variable belongs to.
Since,
5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class
'complex'>
print(capital_city)
Output
{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
In the above example, we have created a dictionary named capital_city. Here,
1. Keys are 'Nepal', 'Italy', 'England'
2. Values are 'Kathmandu', 'Rome', 'London'
Access Dictionary Values Using Keys
We use keys to retrieve the respective value. But not the other way around. For example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
print(num2)
print(num3)
.
Output:
-25.0
(-25+0j)
.
To convert from float to integer, we use int() function. int() function rounds of the given
number to the nearest integer value.
print(num2)
print(num3)
.
Output:
8
(8.4+0j)
.
Note: complex numbers cannot be converted to integer or float.
Type Casting
Similar to type conversion, type casting is done when we want to specify a type on a variable.
Example:
str1 = "7"
str2 = "3.142"
str3 = "13"
num1 = 29
num2 = 6.67
print(int(str1))
print(float(str2))
print(float(str3))
print(str(num1))
print(str(num2))
.
Output:
7
3.142
13.0
29
6.67
.
Python Booleans
Boolean consists of only two values; True and False.
Thus Booleans are used to know whether the given expression is True or False.
bool() function evaluates values and returns True or False.
Here are some examples where the Boolean returns True/False values for different datatypes.
None:
print("None: ",bool(None))
.
Output:
None: False
Numbers:
print("Zero:",bool(0))
print("Integer:",bool(23))
print("Float:",bool(3.142))
print("Complex:",bool(5+2j))
Output:
Zero: False
Integer: True
Float: True
Complex: True
.
Strings:
#Strings
print("Any string:",bool("Nilesh"))
print("A string containing number:",bool("8.5"))
print("Empty string:" ,"")
Output:
Any string: True
A string containing number: True
Empty string: False
.
Lists:
print("Empty List:",bool([]))
print("List:",bool([1,2,5,2,1,3]))
Output:
Empty List: False
List: True
.
Tuples:
#Tuples
print("Empty Tuple:",bool(()))
print("Tuple:",bool(("Horse", "Rhino", "Tiger")))
Output:
Empty Tuple: False
Tuple: True
.
Python Strings
What are strings?
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 = "Samuel"
print("Hello, " + name)
.
Output:
Hello, Samuel
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?
Wrong way ❌
print("He said, "I want to eat an apple".")
Output:
print("He said, "I want to eat an apple".")
^
SyntaxError: invalid syntax
.
Right way ✔️
print('He said, "I want to eat an apple".')
#OR
print("He said, \"I want to eat an apple\".")
.
Output:
He said, "I want to eat an apple".
He said, "I want to eat an apple".
.
note = '''
This is a multiline string
It is used to display multiline message in the program
'''
print(note)
Output:
1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat
Operation on Strings
Length of a String:
We can find the length of a string using len() function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")
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])
print(pie[6]) #returns character at specified index
Output:
Apple
i
.
Note: This method of specifying the start and end index to specify a part of a string is called
slicing.
Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index
Output:
Apple
Pie
pleP
ApplePie
.
String Methods
Python provides a set of built-in methods that we can use to alter and modify the strings.
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:
str3 = "Hello !!!"
print(str3.rstrip("!"))
.
Output:
Hello
.
split() : The split() method splits the give string at the specified instance and returns the
separated strings as list items.
Example:
str2 = "Silver Spoon"
print(str2.split(" ")) #Splits the string at the whitespace " ".
.
Output:
['Silver', 'Spoon']
.
There are various other string methods that we can use to modify our strings.
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)
str2 = "hello WorlD"
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 1:
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
.
Output:
True
.
Example 2:
str1 = "Welcome to the Console !!!"
print(str1.endswith("Console"))
.
Output:
False
.
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
Example 2:
str1 = "Welcome To The Console"
print(str1.isalnum())
str2 = "Hurray!!!"
print(str2.isalnum())
Output:
False
False
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 1:
str1 = "Welcome"
print(str1.isalpha())
Output:
True
Example 2:
tr1 = "I'm 18 years old"
print(str1.isalpha())
str2 = "Hurray!!!"
print(str2.isalnum())
Output:
False
False
islower() : The islower() method returns True if all the characters in the string are lower
case, else it returns False.
Example 1:
str1 = "hello world"
print(str1.islower())
Output:
True
Example 2:
str1 = "welcome Mike"
print(str1.islower())
str2 = "Hurray!!!"
print(str2.islower())
Output:
False
False
isprintable() : The isprintable() method returns True if all the values within the given string
are printable, if not, then return False.
Example 1:
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
Output:
True
Example 2:
str2 = "Hello, \t\t.Mike"
print(str2.isprintable())
Output:
False
isspace() : The isspace() method returns True only and only if the string contains white
spaces, else returns False.
Example 1:
str1 = " " #using Spacebar
print(str1.isspace())
str2 = " " #using Tab
print(str2.isspace())
.
Output:
True
True
.
Example 2:
str1 = "Hello World"
print(str1.isspace())
.
Output:
False
.
istitle() : The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example 1:
str1 = "World Health Organization"
print(str1.istitle())
.
Output:
True
Example 2:
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 1:
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
.
Output:
True
.
Example 2:
str2 = "To kill a Mocking bird"
print(str2.isupper())
.
Output:
False
.
replace() : The replace() method can be used to replace a part of the original string with
another string.
Example:
str1 = "Python is a Compiled Language."
print(str1.replace("Compiled", "Interpreted"))
Output:
Python is a Interpreted Language.
startswith() : The endswith() method checks if the string starts with a given value. If yes then
return True, else return False.
Example 1:
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
Output:
True
.
Example 2:
str1 = "Python is a Interpreted Language"
print(str1.startswith("a"))
.
Output:
False
.
We can even also check for a value in-between the string by providing start and end index
positions.
Example:
str1 = "Python is a Interpreted Language"
print(str1.startswith("Inter", 12, 20))
.
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.
Format Strings
What if we want to join two separated strings?
We can perform concatenation to join two or more separate strings.
Example:
str4 = "Captain"
str5 = "America"
str6 = str4 + " " + str5
print(str6)
.
Output:
Captain America
.
In the above example, we saw how one can concatenate two strings. But how can we concatenate
a string and an integer?
name = "Guzman"
age = 18
print("My name is" + name + "and my age is" + age)
.
Output:
TypeError: can only concatenate str (not "int") to str
.
As we can see, we cannot concatenate a string to another data type.
So what’s the solution?
We make the use of format() method. The format() methods places the arguments within the string
wherever the placeholders are specified.
Example:
name = "Guzman"
age = 18
statement = "My name is {} and my age is {}."
print(statement.format(name, age))
Output:
My name is Guzman and my age is 18.
We can also make the use of indexes to place the arguments in specified order.
Example:
quantity = 2
fruit = "Apples"
cost = 120.0
statement = "I want to buy {2} dozen {0} for {1}$"
print(statement.format(fruit,cost,quantity))
.
Output:
I want to buy 2 dozen Apples for $120.0
Escape Characters
Escape Characters are very important in python. It allows us to insert illegal characters into a
string like a back slash, new line or a tab.
Single/Double Quote: used to insert single/double quotes in the string.
Example:
str1 = "He was \"Flabergasted\"."
str2 = 'He was \'Flabergasted\'.'
print(str1)
print(str2)
.
Output:
He was "Flabergasted".
He was 'Flabergasted'.
Example:
str1 = "I love doing Yoga. \nIt cleanses my mind and my body."
print(str1)
.
Output:
I love doing Yoga.
It cleanses my mind and my body.
.
Python Lists
Lists are ordered collection of data items.
They store multiple items in a single variable.
List items are separated by commas and enclosed within square brackets [].
Lists are changeable meaning we can alter them after creation.
Example 1:
lst1 = [1,2,2,3,5,4,6]
lst2 = ["Red", "Green", "Blue"]
print(lst1)
print(lst2)
.
Output:
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']
.
Example 2:
details = ["Abhijeet", 18, "FYBScIT", 9.8]
print(details)
.
Output:
['Abhijeet', 18, 'FYBScIT', 9.8]
.
As we can see, a single list can contain items of different datatypes.
List Indexes
Each item/element in a list has its own unique index. This index can be used to access any
particular item from the list. The first item has index [0], second item has index [1], third item has
index [2] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
.
Positive Indexing:
As we have seen that list items have index, as such we can access items using these indexes.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
print(colors[4])
print(colors[0])
.
Output:
Blue
Green
Red
.
Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but from the end of
the list. The last item has index [-1], second last item has index [-2], third last item has index [-3]
and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [-5] [-4] [-3] [-2] [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])
.
Output:
Green
Blue
Red
.
Range of Index:
You can print a range of list items by specifying where do you want to start, where do you want to
end and if you want to skip elements in between the range.
Syntax:
List[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: printing all element from a given index till the end
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
.
Output:
['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']
.
When no end index is provided, the interpreter prints all the values till the end.
print(colors)
.
Output:
['voilet', 'green', 'indigo', 'blue']
.
What if you want to append an entire list or any other collection (set, tuple, dictionary) to
the existing list?
extend():
This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the
existing list.
Example 1:
#add a list to a list
colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)
.
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
.
Example 2:
#add a tuple to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = ("Mercedes", "Volkswagen", "BMW")
cars.extend(cars2)
print(cars)
.
Output:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'Volkswagen', 'BMW']
.
Example 3:
#add a set to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = {"Mercedes", "Volkswagen", "BMW"}
cars.extend(cars2)
print(cars)
.
Output:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'BMW', 'Volkswagen']
.
Example 4:
#add a dictionary to a list
students = ["Sakshi", "Aaditya", "Ritika"]
students2 = {"Yash":18, "Devika":19, "Soham":19} #only add keys, does not add values
students.extend(students2)
print(students)
.
Output:
['Sakshi', 'Aaditya', 'Ritika', 'Yash', 'Devika', 'Soham']
.
pop():
This method removes the last item of the list if no index is provided. If an index is provided, then
it removes item at that specified index.
Example 1:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop() #removes the last item of the list
print(colors)
.
Output:
['Red', 'Green', 'Blue', 'Yellow']
.
Example 2:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop(1) #removes item at index 1
print(colors)
.
Output:
['Red', 'Blue', 'Yellow', 'Green']
.
remove():
This method removes specific item from the list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.remove("blue")
print(colors)
.
Output:
['voilet', 'indigo', 'green', 'yellow']
.
del:
del is not a method, rather it is a keyword which deletes item at specific from the list, or deletes
the list entirely.
Example 1:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors[3]
print(colors)
.
Output:
['voilet', 'indigo', 'blue', 'yellow']
.
Example 2:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors
print(colors)
.
Output:
NameError: name 'colors' is not defined
.
We get an error because our entire list has been deleted and there is no variable called colors
which contains a list.
What if we don’t want to delete the entire list, we just want to delete all items within that
list?
clear():
This method clears all items in the list and prints an empty list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.clear()
print(colors)
.
Output:
[]
Change List Items
Changing items from list is easier, you just have to specify the index where you want to replace
the item with existing item.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2] = "Millie"
print(names)
.
Output:
['Harry', 'Sarah', 'Millie', 'Oleg', 'Steve']
.
You can also change more than a single item at once. To do this, just specify the index range
over which you want to change the items.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:4] = ["juan", "Anastasia"]
print(names)
Output:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Steve']
What if the range of the index is more than the list of items provided?
In this case, all the items within the index range of the original list are replaced by the items that
are provided.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[1:4] = ["juan", "Anastasia"]
print(names)
.
Output:
['Harry', 'juan', 'Anastasia', 'Steve']
.
What if we have more items to be replaced than the index range provided?
In this case, the original items within the range are replaced by the new items and the remaining
items move to the right of the list accordingly.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:3] = ["juan", "Anastasia", "Bruno", "Olga", "Rosa"]
print(names)
.
Output:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Bruno', 'Olga', 'Rosa', 'Oleg', 'Steve']
List Comprehension
List comprehensions are used for creating new lists from other iterables like lists, tuples,
dictionaries, sets, and even in arrays and strings.
Syntax:
List = [expression(item) for item in iterable if condition]
expression: it is the item which is being iterated.
iterable: it can be list, tuples, dictionaries, sets, and even in arrays and strings.
condition: condition checks if the item should be added to the new list or not.
Example 1: accepts items with the small letter “o” in the new list
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)
.
Output:
['Milo', 'Bruno', 'Rosa']
.
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)
.
Output:
['blue', 'green', 'indigo', 'voilet']
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
.
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort(reverse=True)
print(num)
.
Output:
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]
.
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.reverse()
print(num)
.
Output:
['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]
.
index(): This method returns the index of the first occurrence of the list item.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.index("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))
.
Output:
1
3
.
count(): Returns the count of the number of items with the given value.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
.
Output:
2
3
.
.(): Returns . of the list. This can be done to perform operations on the list without
modifying the original list.
Example:
colors = ["voilet", "green", "indigo", "blue"]
newlist = colors..()
print(colors)
print(newlist)
.
Output:
['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']
Python Tuples
Tuples are ordered collection of data items. They store multiple items in a single variable. Tuple
items are separated by commas and enclosed within round brackets (). Tuples are unchangeable
meaning we can not alter them after creation.
Example 1:
tuple1 = (1,2,2,3,5,4,6)
tuple2 = ("Red", "Green", "Blue")
print(tuple1)
print(tuple2)
.
Output:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')
.
Example 2:
details = ("Abhijeet", 18, "FYBScIT", 9.8)
print(details)
.
Output:
('Abhijeet', 18, 'FYBScIT', 9.8)
Tuple Indexes
Each item/element in a tuple has its own unique index. This index can be used to access any
particular item from the tuple. The first item has index [0], second item has index [1], third item
has index [2] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
.
I. Positive Indexing:
As we have seen that tuple items have index, as such we can access items using these indexes.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[1])
print(country[3])
print(country[0])
.
Output:
Italy
England
Spain
.
Example 2:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Russia" in country:
print("Russia is present.")
else:
print("Russia is absent.")
.
Output:
Russia is absent.
Syntax:
Tuple[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.
Example: printing all element from a given index till the end
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
.
Output:
('pig', 'horse', 'donkey', 'goat', 'cow')
('horse', 'donkey', 'goat', 'cow')
.
When no end index is provided, the interpreter prints all the values till the end.
Manipulating Tuples
Tuples are immutable, hence if you want to add, remove or change tuple items, then first you must
convert the tuple to a list. Then perform operation on that list and convert it back to tuple.
Example:
countries = ("Spain", "Italy", "India", "England", "Germany")
temp = list(countries)
temp.append("Russia") #add item
temp.pop(3) #remove item
temp[2] = "Finland" #change item
countries = tuple(temp)
print(countries)
Output:
('Spain', 'Italy', 'Finland', 'Germany', 'Russia')
Thus, we convert the tuple to a list, manipulate items of the list using list methods, then
convert list back to a tuple.
However, we can directly concatenate two tuples instead of converting them to list and back.
Example:
countries = ("Pakistan", "Afghanistan", "Bangladesh", "ShriLanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries + countries2
print(southEastAsia)
.
Output:
('Pakistan', 'Afghanistan', 'Bangladesh', 'ShriLanka', 'Vietnam', 'India', 'China')
Python Dictionaries
Dictionaries are ordered collection of data items. They store multiple items in a single variable.
Dictionaries items are key-value pairs that are separated by commas and enclosed within curly
brackets {}.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
Access Items
Accessing Dictionary items:
I. Accessing single values:
Values in a dictionary can be accessed using keys. We can access dictionary values by mentioning
keys either in square brackets or by using get method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
Output:
Karan
True
.
clear(): The clear() method removes all the items from the list.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
.
Output:
{}
.
pop(): The pop() method removes the key-value pair whose key is passed as a parameter.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
.
Output:
{'name': 'Karan', 'age': 19}
.
popitem(): The popitem() method removes the last key-value pair from the dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
.
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
.
apart from these three methods, we can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
.
Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
.
If key is not provided, then the del keyword will delete the dictionary entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info
print(info)
.
Output:
NameError: name 'info' is not defined
. Dictionaries
We can use the .() method to . the contents of one dictionary into another dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
newDictionary = info..()
print(newDictionary)
.
Output:
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
.
Or we can use the dict() function to make a new dictionary with the items of original dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
newDictionary = dict(info)
print(newDictionary)
.
Output:
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003
Conditional Statements
if Statement
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 then 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, elif, nested if.
if Statement:
A simple if statement works on following principle,
execute the block of code inside if statement if the expression evaluates True.
ignore the block of code inside if statement if the expression evaluates False and return to
the code outside if statement.
Example:
applePrice = 180
budget = 200
if (applePrice <= budget):
print("Alexa, add 1kg Apples to the cart.")
.
Output:
Alexa, add 1kg Apples to the cart.
if-else Statement
An if……else statement works on the following principle,
execute the block of code inside if statement if the expression evaluates True. After
execution return to the code out of the if……else block.
execute the block of code inside else statement if the expression evaluates False. After
execution return to the code out of the if……else block.
Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")
.
Output:
Alexa, do not add Apples to the cart.
elif Statement
Sometimes, the programmer may want to evaluate more than one condition, this can be done
using an elif statement.
Nested if Statement
We can use if, if….else, elif statements inside other if statements.
Example:
num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")
.
Output:
Number is between 11-20
Python Loops
for Loop
for loops can iterate over a sequence of iterable objects in python. Iterating over a
sequence is nothing but iterating over strings, lists, tuples, sets and dictionaries.
name = 'Abhishek'
for i in name:
print(i, end=", ")
.
Output:
A, b, h, i, s, h, e, k,
Example: iterating over a tuple:
.
Output:
Red
Green
Blue
Yellow
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?
Here, we can use the range() function.
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.
But we can also loop over a specific range.
Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8
count = 5
while (count > 0):
print(count)
count = count - 1
Output:
5
4
3
2
1
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.
We can even use the else statement with the while loop. Essentially what the else
statement does is that as soon as the while loop condition becomes False, the interpreter
comes out of the while loop and the else statement is executed.
Example:
x=5
while (x > 0):
print(x)
x=x-1
else:
print('counter is 0')
Output:
5
4
3
2
1
counter is 0
Nested Loops
We can use loops inside other loops, such types of loops are called as nested loops.
Example: nesting for loop in while loop
while (i<=3):
for k in range(1, 4):
print(i, "*", k, "=", (i*k))
i=i+1
print()
Output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
.
Output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
Control Statements
There are three control statements that can be used with for and while loops to alter their
behaviour.
They are pass, continue and break.
1. pass:
Whenever loops, functions, if statements, classes, etc are created, it is needed that we should
write a block of code in it. An empty code inside loop, if statement or function will give an
error.
Example:
i=1
while (i<5):
Output:
To avoid such an error and to continue the code execution, pass statement is used. pass
statement acts as a placeholder for future code.
Example:
i=1
while (i<5):
pass
for j in range(5):
pass
if (i == 2):
pass
.
The above code does not give an error.
2. continue:
This keyword is used in loops to end the current iteration and continue the next iteration of the
loop. Sometimes within a loop, we might need to skip a specific iteration. This can be done
using the continue keyword.
Example 1:
for i in range(1,10):
if(i%2 == 0):
continue
print(i)
.
Output:
1
3
5
7
9
Example 2:
i=1
while (i <= 10):
i=i+1
if (i%2 != 0):
continue
print(i)
Output:
2
4
6
8
10
3. break:
The break keyword is used to bring the interpreter out of the loop and into the main body of the
program. Whenever the break keyword is used, the loop is terminated and the interpreter starts
executing the next series of statements within the main program.
Example 1:
i=1
while (i <= 10):
i=i+1
if (i == 5):
break
print(i)
.
Output:
2
3
4
Example 2:
.
Output:
1
2
3
4
5