Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

UNIT-1 - Fundamentals of Python

Uploaded by

aishwarya.pawar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

UNIT-1 - Fundamentals of Python

Uploaded by

aishwarya.pawar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Unit No-1 Fundamentals of Python

Unit Contents Weightage No of


No. in % Sessions
1 Fundamentals of Python
1.1 Introduction
1.2 Keywords, Identifiers, Literals, Operators
1.3 Data Types- Number, Strings, Lists, Tuples,
Dictionaries, Sets
1.4 Understanding Python blocks 15 9
1.5 Control flow- if, else, elif
1.6 Loops- while, for, continue, break
1.7 Loop manipulation using pass, continue, break and else
1.8 For loop using ranges, string, list and dictionaries
1.9 Programming using Python conditional and loops
block
1.10 Comprehensions on List, Tuple, Dictionaries
1.1 Introduction

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:-

Why the Name Python?


 There is a fact behind choosing the name Python. Guido van Rossum was reading the
script of a popular BBC comedy series "Monty Python's Flying Circus". It was late on-
air 1970s.
 Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he
decided to select naming Python after the "Monty Python's Flying Circus" for their
newly created programming language.
 Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop
Application, Scientific Calculation, etc.

Download and Install Python


 Python has two main different versions: Python 2 and Python 3. Both are really different.
 Python develops new versions with changes periodically and releases them according to
version numbers. Python is currently at version 3.12.8
 Installation on Windows
 Visit the link https://www.python.org to download the latest release of python

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.

How does an interpreter work in python?


The Python interpreter is CPython and is written in the C programming language. So how does
CPython work? Let’s see.
1. Interpreters start with source code analysis.
 First, the interpreter checks or analyzes the source code. By now, we assume you know
what the source code means. It’s the high-level language you write programs in.
 So, CPython receives the source code and initializes several commands to do some vital
things.
 First, the interpreter ensures you follow Python’s syntax for writing code.
 It also checks for incorrect lines of code. If it encounters any error in a line, it stops the
program from running and produces an error message.
 This analysis divides the source code files into a list of tokens.

2.The interpreter then generates byte code.


 After lexical analysis, which is the process described in the section above, the interpreter
moves to the second stage, byte code generation.
 After receiving the tokens, the interpreter generates the Abstract Syntax Tree or AST. This
tree is converted to machine language (i.e., 1s and 0s). Because this is a Python interpreter,
the code can be saved in a file with the .pyc extension.

3.Next, the interpreter initializes a PVM.


 The interpreter initializes the Python Virtual Machine (PVM) in the next step. PVM is
crucial because it’s what converts the byte code into binary code.
 After conversion, the results are then printed. Python prints out the correct result if there
are no high-level language errors. Otherwise, it prints out an error message.
 Now that we have a high-level view of how the compiler works, let’s now show you how
to set up and use a Python interpreter.
Popular IDE of Python:-

Python Character set


A character set is a set of valid characters acceptable by a programming language in scripting.
In this case, we are talking about the Python programming language. So, the Python character set
is a valid set of characters recognized by the Python language. These are the characters we can use
during writing a script in Python. Python supports all ASCII / Unicode characters that include:
 Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits 0-9.
 Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ `
&*()_+–={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and carriage return.
 Other: All ASCII and UNICODE characters are supported by Python that constitutes the
Python character set.

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.

The following diagram shows you different tokens used in Python.

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.

>>> import keyword


>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

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.

Rules for Naming an Identifier


 Identifiers cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter or _. The
first letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python


Valid Identifiers Invalid Identifiers
Score @core
return_value return
highest_score highest score
name1 1name
convert_to_string convert to_string

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:

1) Adding black slash at the end of each line.


Example:
1. text1='hello\
2. user'
3. print(text1)
'hellouser'
2) Using triple quotation marks:-
Example:
1. str2='''''welcome
2. to
3. SSSIT'''
4. print str2
Output:
welcome
to
SSSIT

II. Numeric literals:


Numeric Literals are immutable. Numeric literals can belong to following four different numerical
types.
Example –
Numeric Literals
x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal

#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

III. Boolean literals:


A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)

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.

Types of Python Operators


Here's a list of different types of Python operators .
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators

1. Python Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc. For example,
sub = 10 - 5 # 5
Here, - is an arithmetic operator that subtracts two values or variables.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16

Example 1: Arithmetic Operators in Python


a=7
b=2

# 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

2. Python Assignment Operators


Assignment operators are used to assign values to variables. For example,
# assign 5 to x
x=5
Here, = is an assignment operator that assigns 5 to x.
Here's a list of different assignment operators available in Python.
Operator Name Example
= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10

Example 2: Assignment Operators


# assign 10 to a
a = 10

# assign 5 to b
b=5

# assign the sum of a and b to a


a += b #a=a+b

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.

3. Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or False.
For example,
a=5
b=2

print (a > b) # True


Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True

Example 3: Comparison Operators


a=5

b=2

# equal to operator
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)
Run Code
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Note: Comparison operators are used in decision-making and loops.

4. Python Logical Operators


Logical operators are used to check whether an expression is True or False. They are used in
decision-making. For example,
a=5
b=6
print((a > 2) and (b >= 6)) # True
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.
Operator Example Meaning

and a and b Logical AND:


True only if both the operands are True

or a or b Logical OR:
True if at least one of the operands is True

not not a Logical NOT:


True if the operand is False and vice-versa.

Example 4: Logical Operators


# logical AND
print(True and True) # True
print(True and False) # False

# 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)

6. Python Special operators


Python language offers some special types of operators like the identity operator and
the membership operator. They are described below with examples.
Identity operators
In Python, is and is not are used to check if two values are located at the same memory location.
It's important to note that having two variables with equal values doesn't necessarily mean they
are identical.
Operator Meaning Example
Is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False


print(x2 is y2) # prints True
print(x3 is y3) # prints False
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical.
The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them
separately in memory, although they are equal.
7.Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or
variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary, we can only test for the presence of a key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example 5: Membership operators in Python


message = 'Hello world'
dict1 = {1:'a', 2:'b'}

# check if 'H' is present in message string


print('H' in message) # prints True

# check if 'hello' is present in message string


print('hello' not in message) # prints True

# check if '1' key is present in dict1


print(1 in dict1) # prints True

# check if 'a' key is present in dict1


print('a' in dict1) # prints False
Output
True
True
True
False
Here, 'H' is in message, but 'hello' is not present in message (remember, Python is case-sensitive).
Similarly, 1 is key, and 'a' is the value in dictionary dict1. Hence, 'a' in y returns False.
DATA TYPES:-
In computer programming, data types specify the type of data that can be stored inside a variable.
For example,
num = 24
Here, 24 (an integer) is assigned to the num variable. So the data type of num is of the int class.

Python Data Types


Data Types Classes Description
Numeric int, float, complex holds numeric values
String str holds sequence of characters
Sequence list, tuple, range holds collection of items
Mapping dict holds data in key-value pair form
Boolean bool holds either True or False
Set set, frozenset hold collection of unique items

Since everything is an object in Python programming, data types are


actually classes and variables are instances(object) of these classes.
Python Numeric Data type
In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall under Python numbers category. They
are defined as int, float and complex classes in Python.
 int - holds signed integers of non-limited length.
 float - holds floating decimal points and it's accurate up to 15 decimal places.
 complex - holds complex numbers.
We can use the type() function to know which class a variable or a value belongs to.
Let's see an example,
num1 = 5
print(num1, 'is of type', type(num1))

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'>

Python List Data Type


List is an ordered collection of similar or different types of items separated by commas and
enclosed within brackets [ ]. For example,
languages = ["Swift", "Java", "Python"]
Here, we have created a list named languages with 3 string values inside it.
Access List Items
To access items from a list, we use the index number (0, 1, 2 ...). For example,
languages = ["Swift", "Java", "Python"]
# access element at index 0
print(languages[0]) # Swift

# access element at index 2


print(languages[2]) # Python
In the above example, we have used the index values to access items from the languages list.
 languages[0] - access first item from languages i.e. Swift
 languages[2] - access third item from languages i.e. Python

Python Tuple Data Type


Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
In Python, we use the parentheses () to store items of a tuple. For example,
product = ('Xbox', 499.99)
Here, product is a tuple with a string value Xbox and integer value 499.99.
Access Tuple Items
Similar to lists, we use the index number to access tuple items in Python . For example,
# create a tuple
product = ('Microsoft', 'Xbox', 499.99)

# access element at index 0


print(product[0]) # Microsoft

# access element at index 1


print(product[1]) # Xbox

Python String Data Type


String is a sequence of characters represented by either single or double quotes. For example,
name = 'Python'
print(name)

message = 'Python for beginners'


print(message)
Output
Python
Python for beginners
In the above example, we have created string-type variables: name and message with
values 'Python' and 'Python for beginners' respectively.

Python Set Data Type


Set is an unordered collection of unique items. Set is defined by values separated by commas
inside braces { }. For example,
# create a set named student_id
student_id = {112, 114, 116, 118, 115}

# display student_id elements


print(student_id)

# display type of student_id


print(type(student_id))
Output
{112, 114, 115, 116, 118}
<class 'set'>
Here, we have created a set named student_info with 5 integer values.
Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does
not work.

Python Dictionary Data Type


Python dictionary is an ordered collection of items. It stores elements in key/value pairs.
Here, keys are unique identifiers that are associated with each value.
Let's see an example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

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(capital_city['Nepal']) # prints Kathmandu

print(capital_city['Kathmandu']) # throws error message


Here, we have accessed values using keys from the capital_city dictionary.
Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu
However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an
error message.
Data Conversion
 The process of converting numeric data from one type to another is called as type
conversion.
 To convert from integer to float, we use float() function.

To convert from integer to complex, we use the complex() function.


Example:
num1 = -25
num2 = float(num1)
num3 = complex(num1)

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.

To convert from float to complex, we use the complex() function.


Example:
num1 = 8.4
num2 = int(num1)
num3 = complex(num1)

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.

Why are Boolean’s needed?


Consider the following if-else statement:
x = 13
if(x>13):
print("X is a prime number.")
else:
print("X is not a prime number.")
.
Is it True that X is greater than 13 or is it 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
.

Sets and Dictionaries:


print("Empty Dictionary:",bool({}))
print("Empty Set:",bool({"Mike", 22, "Science"}))
print("Dictionary:",bool({"name":"Lakshmi", "age":24 ,"job":"unemployed"}))
Output:
Empty Dictionary: False
Empty Set: True
Dictionary: 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".
.

What if you want to write multiline strings?


Sometimes the programmer might want to include a note, or a set of instructions, or just might
want to explain a piece of code. Although this might be done using multiline comments, the
programmer may want to display this in the execution of programmer. This is done using
multiline strings.
Example:
receipe = """
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
"""
print(receipe)

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

This is a multiline string


It is used to display multiline message in the program

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
.

Loop through a String:


Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E

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 upper 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:
str3 = "Hello !!!"
print(str3.rstrip("!"))
.
Output:
Hello
.

replace() : the replace() method replaces a string with another string.


Example:
str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))
.
Output:
Silver Moon
.

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'.

New Line: inserts a new line wherever specified.

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.
.

Tab: inserts a tab wherever specified.


Example:
str2 = "Hello \t\tWorld \t!!!"
print(str2)
.
Output:
Hello World !!!
.

Backspace: erases the character before it wherever it is specified.


Example:
str2 = "Hello \bWorld !!!"
print(str2)
.
Output:
Hello World !!!
.

Backslash: used to insert a backslash into a string.


Example:
str3 = "What will you eat? Apple\\Banana"
print(str3)
.
Output:What will you eat? Apple\Banana

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]
.

Accessing list items:

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
.

Check for item:


We can check if a given item is present in the list. This is done using the in keyword.
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Yellow" in colors:
print("Yellow is present.")
else:
print("Yellow is absent.")
.
Output:
Yellow is present.
.

colors = ["Red", "Green", "Blue", "Yellow", "Green"]


if "Orange" in colors:
print("Orange is present.")
else:
print("Orange is absent.")
.
Output:
Orange is absent.
.

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 elements within a particular range:


animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes
.
Output:
['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']
.
Here, we provide index of the element from where we want to start and the index of the element
till which we want to print the values.
Note: The element of the end index provided will not be included.

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.

Example: printing all elements from start to a given index


animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes
.
Output:
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
.
When no start index is provided, the interpreter prints all the values from start up to the end index
provided.
Example: print alternate values
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes
.
Output:
['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']
.
Here, we have not provided start and index, which means all the values will be considered. But as
we have provided a jump index of 2 only alternate values will be printed.

Example: printing every 3rd consecutive withing given range


animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[1:8:3])
.
Output:
['dog', 'pig', 'goat']
.
Here, jump index is 3. Hence it prints every 3rd element within given index.
Add List Items
There are three methods to add items to list: append(), insert() and extend()
append():
This method appends items to the end of the existing list.
Example:
colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
.
Output:
['voilet', 'indigo', 'blue', 'green']
.
What if you want to insert an item in the middle of the list? At a specific index?
insert():
This method inserts an item at the given index. User has to specify index and the item to be
inserted within the insert() method.
Example:
colors = ["voilet", "indigo", "blue"]
# [0] [1] [2]

colors.insert(1, "green") #inserts item at index 1


# updated list: colors = ["voilet", "green", "indigo", "blue"]
# indexs [0] [1] [2] [3]

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']
.

concatenate two lists:


you can simply concatenate two list to join two lists.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)
.
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Remove List Items
There are various methods to remove items from the list: pop(), remove(), del(), clear()

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']
.

What if you want to remove a specific item from the list?

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']
.

Example 2: accepts items which have more than 4 letters


names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if (len(item) > 4)]
print(namesWith_O)
.
Output:
['Sarah', 'Bruno', 'Anastasia']
List Methods
We have discussed methods like append(), clear(), extend(), insert(), pop(), remove() before. Now
we will learn about some more list methods:

sort(): This method sorts the list in ascending order.


Example 1:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort()
print(colors)

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]
.

What if you want to print the list in descending order?


We must give reverse=True as a parameter in the sort method.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)

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]
.

The reverse parameter is set to False by default.


Note: Do not mistake the reverse parameter with the reverse method.

reverse(): This method reverses the order of the list.


Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.reverse()
print(colors)

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]
.

Accessing tuple items:

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
.

II. Negative Indexing:


Similar to positive indexing, negative indexing is also used to access items, but from the end of
the tuple. The last item has index [-1], second last item has index [-2], third last item has index [-
3] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[-1])
print(country[-3])
print(country[-4])
.
Output:
Germany
India
Italy
.

III. Check for item:


We can check if a given item is present in the tuple. This is done using the in keyword.
Example 1:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Germany" in country:
print("Germany is present.")
else:
print("Germany is absent.")
.
Output:
Germany is present.
.

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.

IV. Range of Index:


You can print a range of tuple 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:
Tuple[start : end : jumpIndex]
Note: jump Index is optional. We will see this in given examples.

Example: printing elements within a particular range:


animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes
.
Output:
('mouse', 'pig', 'horse', 'donkey')
('bat', 'mouse', 'pig', 'horse', 'donkey')
.
Here, we provide index of the element from where we want to start and the index of the element
till which we want to print the values.
Note: The element of the end index provided will not be included.

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.

Example: printing all elements from start to a given index


animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes
.
Output:
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
.
When no start index is provided, the interpreter prints all the values from start up to the end index
provided.

Example: print alternate values


animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes
.
Output:
('cat', 'bat', 'pig', 'donkey', 'cow')
('dog', 'mouse', 'horse', 'goat')
.
Here, we have not provided start and index, which means all the values will be considered. But as
we have provided a jump index of 2 only alternate values will be printed.

Example: printing every 3rd consecutive withing given range


animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[1:8:3])
.
Output:
('dog', 'pig', 'goat')
.
Here, jump index is 3. Hence it prints every 3rd element within given index.

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
.

II. Accessing multiple values:


We can print all the values in the dictionary using values() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
.
Output:
dict_values(['Karan', 19, True])
.

III. Accessing keys:


We can print all the keys in the dictionary using keys() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
.
Output:
dict_keys(['name', 'age', 'eligible'])
.

IV. Accessing key-value pairs:


We can print all the key-value pairs in the dictionary using items() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
Output:
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
Add/Remove Items
Adding items to dictionary:
There are two ways to add items to a dictionary.
I. Create a new key and assign a value to it:
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info['DOB'] = 2001
print(info)
.
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2001}
.

II. Use the update() method:


The update() method updates the value of the key provided to it if the item already exists in the
dictionary, else it creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
.
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}

Removing items from dictionary:


There are a few methods that we can use to remove items from dictionary.

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.

An elif statement works on the following principle,


 execute the block of code inside if statement if the initial expression evaluates to True.
After execution return to the code out of the if block.
 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
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
.
Output:
Number is Zero.

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

Python for Loop

 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 types; for loop, while loop, nested 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.

 Example: iterating over a string:

 name = 'Abhishek'
 for i in name:
 print(i, end=", ")

.
 Output:

 A, b, h, i, s, h, e, k,
 Example: iterating over a tuple:

 colors = ("Red", "Green", "Blue", "Yellow")


 for x in colors:
 print(x)

 .
 Output:

 Red
 Green
 Blue
 Yellow

 Similarly, we can use loops for lists, sets and dictionaries.

 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

Python while Loop


 As the name suggests, while loops execute statements while the condition is True. As
soon as the condition becomes False, the interpreter comes out of the while loop.
 Example:

 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

 Example: nesting while loop in for loop

 for i in range(1, 4):


 k=1
 while (k<=3):
 print(i, "*", k, "=", (i*k))
 k=k+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

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:

IndentationError: expected an indented block

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:

for i in range(1, 10):


print(i)
if (i == 5):
break

.
Output:

1
2
3
4
5

You might also like