3.FPP Class Note Unit-I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

PYTHON Python 2.

Python 2.1
October 16, 2000

April 17, 2001


UNIT-I Python 2.2 December 21, 2001
What is Python? Python 2.3 July 29, 2003
Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications. Python 2.4 November 30, 2004
It is simple and easy to learn and provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it Python 2.5 September 19, 2006
attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal Python 2.6 October 1, 2008
language for scripting and rapid application development. Python 2.7 July 3, 2010
Python supports multiple programming pattern, including object-oriented,
imperative, and functional or procedural programming styles. Python 3.0 December 3, 2008
Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with Python 3.1 June 27, 2009
web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically Python 3.2 February 20, 2011
typed so we can write a=10 to assign an integer value in an integer variable. Python 3.3 September 29, 2012
Python makes the development and debugging fast because there is no compilation
step included in Python development, and edit-test-debug cycle is very fast. Python 3.4 March 16, 2014
Python History:
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea Python 3.5 September 13, 2015
of Python programming language has taken from the ABC programming language or
Python 3.6 December 23, 2016
we can say that ABC is a predecessor of Python language.
Python = ABC + Modula-3 Python 3.7 June 27, 2018
Guido van Rossum was a fan of the popular BBC comedy show of that time, "Monty
Python's Flying Circus". So he decided to pick the name Python for his newly Python 3.8 October 14, 2019
created programming language.
Python Version List
Python 2 vs. Python 3
Python Version Released Date
in the case of Python, the two versions Python 2 and Python 3 are very much different
Python 1.0 January 1994 from each other.
1. Python 2 uses print as a statement and used as print "something" to print
Python 1.5 December 31, 1997
some string on the console. On the other hand, Python 3 uses print as a
Python 1.6 September 5, 2000 function and used as print("something") to print something on the console.

Murali Krishna Senapaty


Date: 18-04-2022
2. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit Python has wide range of libraries and frameworks widely used in various fields such as
machine learning, artificial intelligence, web applications, etc. We define some popular
string type is Unicode. frameworks and libraries of Python as follows.

Features of Python: o Web development (Server-side) - Django Flask, Pyramid, CherryPy


1) Expressive language o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
2) Interpreted language o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
3) Cross platform language o Mathematics - Numpy, Pandas, etc.
4) Open-source Language
5) Object oriented language Anaconda: It is a distribution software which provides editors like spider and Jupiter
6) Large standard library for writing and executing python programs.
7) GUI programming Support Miniconda: It is a smaller version of Anaconda with limited features.
8) Dynamic Memory Allocation www.anaconda.com/downloads
9) Integrated easily with C++, Java
Python development environment:
Applications: =============================
1) Web application development 1) Python shell
2) GUI applications 2) IDEs
3) S/W development process 3) Notebook environments
4) Scientific and numerical calculations 4) Text Editors
5) Multimedia application
Python Shell:
6) CAD, CAM application
=========== When we open python shell we get python prompt >>>
7) Data science and Data Mining Where we can type and execute python commands.
8) Mobile Applications 1) Go to Cmd prompt,
9) ERP, Ecommerce type python or python3
10) Artificial Intelligence and Machine Learning 2) Click on python IDLE
11) Image Processing Applications.
12) Speech Recognitions Ex1:p1.py
A=20
Advantages of Python: B=40
1) Easy to write and understand A+B
2) Huge library available
IDLE: integrated development for Learning Environment
3) Less code to solve a problem
IDE: integrated development Environment.
Benefits of IDE:
Python Popular Frameworks and Libraries 1)
2)
To presents the code, output, error or message windows in a single screen
To create a project folder and interact with the programs of the project.
3) It is maintained by the developer team to update the software time to time.
Python Web framework is a collection of packages or modules that allow Two types of IDEs:
developers to write Web applications or services. With it, developers don't need to 1) Pro version : it need to be purchased
handle low-level details like protocols, sockets or process/thread management. 2) Community version : it is free ware.
Popular IDEs available in market:
Pycharm, Spider, Eclipse+Pydev, IDLE, Atom, Visual Studio Code, Sub.lime Text3,
Thonny etc
Murali Krishna Senapaty
Date: 18-04-2022
3
Jupyter Notebook Environment: 4
1) Here we can see the input code and output very next to each other. End of for loop
2) We can visualize all the recent codings at a time in a single page
3) We can run any piece of code anytime
Comments in Python
Here the default extension name in Jupyter notebook is .ipynb
Ipython notebook Comments are essential for defining the code and help us and other to understand the
code. By looking the comment, we can easily understand the intention of every line that
GITs: It is a software for controlling the versions of python. we have written in code. We can also find the error very easily, fix them, and use in
Here we can change the version of a coding. other applications.

How to execute the python code: In Python, we can apply comments using the # hash character. The Python interpreter
1) Using interactive mode: entirely ignores the lines followed by a hash character. A good programmer always uses
In >>> prompt we can type individual code the comments to make code under stable. Let's see the following example of a
2) Script mode: comment.
Here we can write a program using some editor Notepad and then we can
execute the program from commands prompt. name = "Thomas" # Assigning string value to the name variable
3) Using IDE: We can add comment in each line of the Python code.
Here we can write a program, save, debug, and execute programs.
Fees = 10000 # defining course fees is 10000
Python Basic Syntax Fees = 20000 # defining course fees is 20000

There is no use of curly braces or semicolon in Python programming language. It is Types of Comment
English-like language. But Python uses the indentation to define a block of code.
Indentation is nothing but adding whitespace before the statement when it is Python provides the facility to write comments in two ways- single line comment and
needed. For example - multi-line comment.
def func():
statement 1 Single-Line Comment - Single-Line comment starts with the hash # character followed
statement 2 by text for further explanation.
…………………
………………… 1. # defining the marks of a student
statement N 2. Marks = 90
Example -
list1 = [1, 2, 3, 4, 5] We can also write a comment next to a code statement. Consider the following
for i in list1: example.
print(i)
if i==4: 1. Name = "James" # the name of a student is James
break 2. Marks = 90 # defining student's marks
print("End of for loop")
3. Branch = "Computer Science" # defining student branch
Output:
Multi-Line Comments - we can use “ “ “ character to the multiple lines.

1
For example -
2

Murali Krishna Senapaty


Date: 18-04-2022
We can also use another way. In python-2 keywords are 31 and in python 3.3 it is 33.
""" Examples:
This is an example Return True if both statements are True:
Of multi-line comment x = (5 > 3 and 5 < 10)
Using triple-quotes print(x)
"""
Example
Character set in Python: Skip the iteration if the variable i is 3, but continue with the next iteration:
========================== for i in range(9):
Python initially supporting ASCII code up to version 2.6 then 2.7 onwards it is if i == 3:
supporting Unicode characters. continue
Unicode is a standardized code which helps to represent not only the characters of print(i)
ASCII but also Greek letter, mathematical symbols, emojis, historical symbols etc.
ASCII having ASCII-7 and ASCII-8 Example
But in Unicode supports 8 bits, 16 bits, 32 bits. Import the datetime module and display the current date and time:
import datetime
How does the interpreter runs python script ? x = datetime.datetime.now()
There is a Python Virtual machine (PVM) exist. print(x)
Here the interpreter generates a bytecode for a program. The purpose of it is to
optimize the code execution. So, the during next execution it will bypass this step. Example
Print the result of the comparison "7 is larger than 6":
Tokens and their types: print(7 > 6)
The tokens are each individual words in a statement in program.
There are 4 types of tokens exist: Example
1) Keywords Assign the value None to a variable:
2) Identifiers x = None
3) Literals print(x)
4) Operators example:
>>>True+True
Python Keywords 2
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These Example:
keywords can't be used as a variable. Following is the List of Python Keywords. >>>None==0
False
True False None and as
Example
asset def class continue break Check if "banana" is present in the list:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
else finally elif del except print("yes")

global for if from import


Python Identifiers
raise try or return pass
Python identifiers refer to a name used to identify a variable, function, module, class,
nonlocal in not is lambda module or other objects. There are few rules to follow while naming the Python Variable.

Murali Krishna Senapaty


Date: 18-04-2022
o A variable name must start with either an English letter or underscore (_). Let's understand the following example
o A variable name cannot start with the number. 1. a = 50
o Special characters are not allowed in the variable name.
o The variable's name is case sensitive.
o Identifier name must not be similar to any keyword defined in the language. In the above image, the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
Examples of valid identifiers: a123, _n, n_9, etc. a = 50
Examples of invalid identifiers: 1a, n%4, n 9, etc.
b=a
Let's understand the following example.
Example -
The variable b refers to the same object that a points to because Python does not
number = 10
create another object.
print(num)
_a = 100
Let's assign the new value to b. Now both variables will refer to the different objects.
print(_a)
a = 50
b =100
x_y = 1000
print(x_y)
Output:
10
100
1000
Python manages memory efficiently if we assign the same variable to two different
* the datatype of a variable can be changed: values.
Ex:
a=25
print(a, type(a)) Multiple Assignment
a="hello"
print(a, type(a)) Python allows us to assign a value to multiple variables in a single statement, which is
a=123.456 also known as multiple assignments.
print(a, type(a))
So, for a variable the datatype is not fixed. And declaration is not necessary. 1. Assigning single value to multiple variables
So, the datatype of a variable is purely based on the assigned data to it.
Eg:
Object References
1. x=y=z=50
2. print(x)
It is necessary to understand how the Python interpreter works when we declare a 3. print(y)
variable. The process of treating variables is somewhat different from many other 4. print(z)
programming languages.
In Python, variables are a symbolic name that is a reference or pointer to an object. Output:
The variables are used to denote objects by that name. 50

Murali Krishna Senapaty


Date: 18-04-2022
50 c=a+b
50 print("The sum is:", c)

# Calling a function
2. Assigning multiple values to multiple variables:
add()
#print(a+b) # it is invalid as a,b are local for function add()
Eg:

a,b,c=5,10,15 Global Variables


print (a )
print (b) Global variables can be used throughout the program, and its scope is in the entire
print (c ) program. We can use global variables inside or outside the function.
Output:
A variable declared outside the function is the global variable by default. Python
5 provides the global keyword to use global variable inside the function. If we don't use
10 the global keyword, the function treats it as a local variable. Let's understand the
15 following example.
Python Variable Types Example -
There are two types of variables in Python - Local variable and Global variable. Let's understand
the following variables.
# Declare a variable and initialize it
Local Variable x = 101
Local variables are the variables that declared inside the function and have scope within the
# Global variable in function
function. Let's understand the following example. def mainFunction():
# printing a global variable
Example - global x
print(x)
# Declaring a function # modifying a global variable
def add(): x = 'Welcome To Python'
# Defining local variables. They has scope only within a function print(x)
a = 20
b = 30 mainFunction()
c=a+b print(x)
print("The sum is:", c)
Output:
# Calling a function
add() 101
Welcome To Python
Output:The sum is: 50 Welcome To Python

Ex2: Ex2:
def add(): a,b=10,20
# Defining local variables. They has scope only within a function
a = 20 def add():
b = 30 # ReDefining global variables.
Murali Krishna Senapaty
Date: 18-04-2022
global a,b As we can see in the above example, we assigned a large integer value to
a = 20 variable x and checked its type. It printed class <int> not long int. Hence, there is no
b = 30 limitation number by bits and we can expand to the limit of our memory.
c=a+b
print("The sum is:", c) Python doesn't have any special data type to store larger numbers.

# Calling a function Example -


add()
# A Python program to display that we can store
a,b=11,22 # large numbers in Python
print(a+b) # it is invalid as a,b are global for function add()
o/p:
a = 10000000000000000000000000000000000000000000 #10^43
The sum is: 50
a=a+1
33 print(type(a))
print (a)
Delete a variable
Output:
We can delete the variable using the del keyword. The syntax is given below. <class 'int'>
10000000000000000000000000000000000000000001
Syntax - del <variable_name>
Literals:
Python Literals can be defined as data that is given in a variable or constant.
In the following example, we create a variable x and assign value to it. We deleted Python supports the following literals:
variable x, and print it, we get the error "variable x is not defined" 1) String Literals
2) Numeric Literals
Example - 3) Boolean Literals
# Assigning a value to x 4) Special Literals
x=6 5) Literal Collections
print(x)
# deleting a variable. 1. String literals:
del x String literals can be formed by enclosing a text in the quotes. We can use both
print(x) single as well as double quotes to create a string.

Output: 6 Example:
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line "Aman" , '12345'
389, in Types of Strings:
print(x)
NameError: name 'x' is not defined There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-line are known as
Maximum Possible Value of an Integer in Python Single line Strings.
Example:
Unlike the other programming languages, Python doesn't have long int or float data text1='hello'
types. It treats all integer values as an int data type
b) Multi-line String - A piece of text that is written in multiple lines is known as
multiple lines string.
Murali Krishna Senapaty
Date: 18-04-2022
There are two ways to create multiline strings:
1) Adding black slash at the end of each line. III. Boolean literals:
Example: A Boolean literal can have any of the two values: True or False.
text1='hello\ Example - Boolean Literals
user' x = (1 == True)
print(text1) y = (2 == False)
'hellouser' z = (3 == True)
a = True + 10
2) Using triple quotation marks:- b = False + 10
Example: print("x is", x)
str2='''''welcome print("y is", y)
to print("z is", z)
SSSIT''' print("a:", a)
print str2 print("b:", b)
Output: Output:
welcome x is True
to y is False
SSSIT z is False
a: 11
II. Numeric literals: b: 10
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types. IV. Special literals.
 Integer Python contains one special literal i.e., None.
 Long Integer None is used to specify to that field that is not created. It is also used for the end of
 Float lists in Python.
 Complex
Example - Special Literals
Example: val1=10
x = 0b10100 #Binary Literals val2=None
y = 100 #Decimal Literal print(val1)
z = 0o215 #Octal Literal print(val2)
u = 0x12d #Hexadecimal Literal Output:
10
#Float Literal None
float_1 = 100.5
float_2 = 1.5e2 V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals,
#Complex Literal Dict literals, and Set literals.
a = 5+3.14j
print(x, y, z, u) List:
print(float_1, float_2) List contains items of different data types. Lists are mutable i.e., modifiable.
print(a, a.imag, a.real) The values stored in List are separated by comma(,) and enclosed within square
Output: brackets([]). We can store different types of data in a List.
Example - List literals
20 100 141 301 list=['John',678,20.4,'Peter']
100.5 150.0 list1=[456,'Andrew']
(5+3.14j) 3.14 5.0 print(list)
Murali Krishna Senapaty
Date: 18-04-2022
print(list + list1) int
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
datatypes are 6 types:
Numbers
Dictionary: String
Python dictionary stores the data in the key-value pair. List
It is enclosed by curly-braces {} and each pair is separated by the commas(,). Tuple
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
Dictionary
print(dict) Set
Output: Boolean
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Numbers type:
Tuple: Python allows
Python tuple is a collection of different data-type. It is immutable which means it int,
cannot be modified after creation. float,
It is enclosed by the parentheses () and each element is separated by the comma(,). long,
Example complex
tup = (10,20,"Dev",[2,3,4]) *Here we can store a large integer value as per the memory available.
print(tup) *float type supports by default up to 15 decimal points.
Output: *long supports up to python 2.x and after that it is merged with int type
(10, 20, 'Dev', [2, 3, 4])
Example: Assignment of data
Set: x=10; //single assignment
Python set is the collection of the unordered dataset. x=y=z=40; //multiple assignments
It is enclosed by the {} and each element is separated by the comma(,). x,y,z=20,30,40; //multiple assignment with different values.
Example: - Set Literals x=5+7j
set = {'apple','grapes','guava','papaya'} print(type(x))
print(set) o/p: <class, ‘complex’>
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Operators:
Example
Operators: x = 1 # int
The operators are the symbols which are responsible for particular operations between
y = 2.8 # float
operands. Python provides many types of operators.
z = 1j # complex

Python Datatypes: Example


In Python the variable declaration is not necessary. As and when a variable is required, print(type(x))
we can use an identifier. So, when we write an identifier and assign a data then print(type(y))
according to the type of data the datatype of the variable will be decided. print(type(z))
Ex:
X=250
print(type(X))
Example
output:
Murali Krishna Senapaty
Date: 18-04-2022
Integers: center() Returns a centered string
x=1
y = 35656222554887711 count() Returns the number of times a specified value occurs in a
z = -3255522 string
print(type(x))
print(type(y)) encode() Returns an encoded version of the string
print(type(z))
endswith() Returns true if the string ends with the specified value

Example expandtabs() Sets the tab size of the string

Floats: find() Searches the string for a specified value and returns the
x = 1.10 position of where it was found
y = 1.0
format() Formats specified values in a string
z = -35.59
print(type(x)) format_map() Formats specified values in a string
print(type(y))
print(type(z)) index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric


Example
isalpha() Returns True if all characters in the string are in the alphabet
Complex:
x = 3+5j isdecimal() Returns True if all characters in the string are decimals
y = 5j
isdigit() Returns True if all characters in the string are digits
z = -5j
print(type(x)) isidentifier() Returns True if the string is an identifier
print(type(y))
print(type(z)) islower() Returns True if all characters in the string are lower case
++++++++++++++++++++++++++++++++++++++++++++++
isnumeric() Returns True if all characters in the string are numeric
STRING TYPE:
isprintable() Returns True if all characters in the string are printable

Python has a set of built-in methods that you can use on strings. isspace() Returns True if all characters in the string are whitespaces

Note: All string methods returns new values. They do not change the original string. istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case
Method Description
join() Joins the elements of an iterable to the end of the string
capitalize() Converts the first character to upper case
ljust() Returns a left justified version of the string
casefold() Converts string into lower case

Murali Krishna Senapaty


Date: 18-04-2022
lower() Converts a string into lower case
# defining strings in Python
# all of the following are equivalent
lstrip() Returns a left trim version of the string
my_string = 'Hello'
maketrans() Returns a translation table to be used in translations
print(my_string)

partition() Returns a tuple where the string is parted into three parts my_string = "Hello"
print(my_string)
replace() Returns a string where a specified value is replaced with a
specified value my_string = '''Hello'''
print(my_string)
rfind() Searches the string for a specified value and returns the last
position of where it was found # triple quotes string can extend multiple lines
my_string = """Hello, welcome to
rindex() Searches the string for a specified value and returns the last the world of Python"""
position of where it was found print(my_string)

rjust() Returns a right justified version of the string


Slicing
rpartition() Returns a tuple where the string is parted into three parts
it allows to interact with subset of characters with slice operator [ ] and :
rsplit() Splits the string at the specified separator, and returns a list
Ex1:
rstrip() Returns a right trim version of the string >>>str= “hello world”
>>>print(str)
split() Splits the string at the specified separator, and returns a list o/p: hello world
Ex2:
splitlines() Splits the string at line breaks and returns a list >>>print(str[4])
o/p: o
startswith() Returns true if the string starts with the specified value ex3:
>>>print(str[2:7])
strip() Returns a trimmed version of the string o/p: llo w
//here it prints the characters from index 2 to less than index 7
swapcase() Swaps cases, lower case becomes upper case and vice versa
Example
title() Converts the first character of each word to upper case
The len() function returns the length of a string:
translate() Returns a translated string
a = "Hello, World!"
upper() Converts a string into upper case print(len(a))
o/p: 13
zfill() Fills the string with a specified number of 0 values at the
beginning Example
Strings can be created by enclosing characters inside a single quote or double-quotes. Get the characters from the start to position 5 (not included):
Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.
Murali Krishna Senapaty
Date: 18-04-2022
b = "Hello, World!" The strip() method removes any whitespace from the beginning or the end:
print(b[:5])
o/p: Hello a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Example
Example
Get the characters from position 2, and all the way to the end:
The replace() method replaces a string with another string:
b = "Hello, World!"
print(b[2:]) a = "Hello, World!"
print(a.replace("H", "J"))
Example: Use negative indexes to start the slice from the end of the string:
a = "Hello, World!" Example
print(a[::-1])
o/p: !dlroW ,olleH The split() method splits the string into substrings if it finds instances of the separator:

Example a = "Hello, World!"


print(a.split(",")) # returns ['Hello', ' World!']
b = "Hello, World!"
print(b[-5:-2])

o/p: orl Example


Merge variable a with variable b into variable c:
Example
a = "Hello"
b = "Hello friends"
b = "World"
print(b[::-2])
c=a+b
print(c)
o/p: snifolH

Example Example
The upper() method returns the string in upper case: x="python"
x=x.capitalize()
a = "Hello, World!" print(x)
print(a.upper())
o/p: Python
Example
The lower() method returns the string in lower case: Example
x="python"
a = "Hello, World!" x=x.upper()
print(a.lower()) print(x)
Example o/p: PYTHON
Murali Krishna Senapaty
Date: 18-04-2022
print(len(a))
a.upper()
String Format
Example
But we can combine strings and numbers by using the format() method! # index must be in range
my_string=”hello”
The format() method takes the passed arguments, formats them, and places them in the >>> print(my_string[15])
string where the placeholders {} are: ...
IndexError: string index out of range
Example
Use the format() method to insert numbers into strings: Example
age = 36 x="hello"
txt = "My name is John, and I am {}" print(x[20:])
print(txt.format(age)) o/p: NO OUTPUT as out of range

Example Example
quantity = 3 # index must be an integer
itemno = 567 >>> my_string[1.5]
price = 49.95 ...
myorder = "I want {} pieces of item {} for {} dollars." TypeError: string indices must be integers
print(myorder.format(quantity, itemno, price))
Example
Example
quantity = 3 Loop through the letters in the word "banana":
itemno = 567 for x in "banana":
price = 49.95 print(x)
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price)) o/p:
b
* With string we can use + and * operators
a
+ is used for concatenation n
And * is used for repetition a
Ex3:
>>>a= “Manohar” n
>>>b= “Singh” a
>>>print(a+b)
o/p: ManoharSingh
Example
Ex4:
>>>print(a*3) Check if "free" is present in the following text:
o/p: ManoharManoharManohar txt = "The best things in life are free!"
print("free" in txt)
ex: o/p: True
a="manohar"
Murali Krishna Senapaty
Date: 18-04-2022
Example Example
>>> word='python'
Print only if "free" is present: >>> word[0]='q'
txt = "The best things in life are free!" TypeError: 'str' object does not support item assignment
if "free" in txt:
print("Yes, 'free' is present.")
o/p: Yes, 'free' is present.
Escape Characters
Code Result
Example
# Iterating through a string \' Single Quote
count = 0
for letter in 'Hello World': \\ Backslash
if(letter == 'l'):
count += 1 \n New Line
print(count,'letters found')
\r Carriage Return
In Python the strings can be manipulated with index positions or subscripts.
\t Tab
Example
>>>word=”python” \b Backspace
Ex:
>>>word[-1] \f Form Feed
o/p: ‘n’
\ooo Octal value
Example
>>>word[-6] \xhh Hex value
o/p: ‘p’
We can even interact with a range of characters:
>>>word[2:5] Python Collections (Arrays)
o/p: ‘tho’
* In string type in the range specification, the starting and ending position is optional. There are four collection data types in the Python programming language:
Ex:
>>>word[:2]
o/p: ‘py’ 
List is a collection which is ordered and changeable. Allows duplicate
members.
Ex:  Tuple is a collection which is ordered and unchangeable. Allows
>>>word[2:] duplicate members.
o/p: ‘thon’  Set is a collection which is unordered, unchangeable*, and
ex: >>>word[:2]+word[2:]
unindexed. No duplicate members.
o/p: ‘python’  Dictionary is a collection which is ordered** and changeable. No
duplicate members.
>>> word[:] ++++++++++++++++++++++++++++++++++++++++++++++
'python'
As string is immutable so we cannot modify the content, if we do then it shows error as:
LIST DATA TYPE:
===========================
It is a compound data type.
Murali Krishna Senapaty
Date: 18-04-2022
So, we can store different type of data here. >>> print(list1)
The list type can be indexed similar to string type. The list type is mutable or [1, 2, 3, 4]
changeable.
Example2:
List Methods >>> l1=['a', "murali", 10, 20, 1.23]
>>> l1
Python has a set of built-in methods that you can use on lists. ['a', 'murali', 10, 20, 1.23]
Method Description
Example3: concatenation using +
append() Adds an element at the end of the list >>> l1+l1
['a', 'murali', 10, 20, 1.23, 'a', 'murali', 10, 20, 1.23]
clear() Removes all the elements from the list Example4: repetition using *
>>> list1=[1, 2, 3, 4]
copy() Returns a copy of the list >>> list1*3
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
count() Returns the number of elements with the specified value
Example4: concatenating two lists
extend() Add the elements of a list (or any iterable), to the end of >>> l1=['a', "murali", 10, 20, 1.23]
the current list >>> l2=[10,20, 'a', 'b']
>>> l1+l2
index() Returns the index of the first element with the specified ['a', 'murali', 10, 20, 1.23, 10, 20, 'a', 'b']
value
Example5:
>>> print(l1[0])
insert() Adds an element at the specified position
a
>>> print(l1[2])
pop() Removes the element at the specified position 10
>>> print(l1[1])
remove() Removes the item with the specified value Murali

reverse() Reverses the order of the list Example6: datatype of list l1


>>> type(l1)
sort() Sorts the list <class 'list'>

Example7: datatype of specific index data of list l1


List: It is similar to array. It can store any data within [ ]. It can use indexing. >>> type(l1[0])
# empty list <class 'str'>
my_list = [] >>> type(l1[2])
<class 'int'>
# list with mixed data types
my_list = [1, "Hello", 3.4] Example8: to print specific characters of an item in list:
>>> print(l1[1][0:2])
Example1: mu
>>> list1=[1,2,3,4] or
>>> list1 >>> print(l1[1][0:2:1]) # indexing incremented by 1
[1, 2, 3, 4] mu
Murali Krishna Senapaty
Date: 18-04-2022
16
example9: prints reverse order
>>> print(l1[1][::-1]) Here also we can use negative indexing:
ilarum >>>list1[-1]
o/p: 25
example10: Nested List:
n_list = ["Happy", [2, 0, 1, 5]] ex:

# Nested indexing Ex:


print(n_list[0][1]) >>> list1[2:5]
o/p: a [8, 16, 25]

print(n_list[1][3]) Ex:
o/p: 5 >>> list1[-5:-3]
[1, 4]
example11: Negative indexing
# Negative indexing in lists Ex:
my_list = ['p','r','o','b','e'] >>> list1[3:]
print(my_list[-1]) [16, 25]
o/p: e
Ex:
# fifth last item >>> list1[:3]
print(my_list[-5]) [1, 4, 8]
Output: p
Ex:
Example12: Add/Change List Elements >>> list1[:]
# Correcting mistake values in a list [1, 4, 8, 16, 25]
odd = [2, 4, 6, 8]
Ex:
# change the 1st item >>> list1[:45]
odd[0] = 1 [1, 4, 8, 16, 25]
print(odd)
o/p: [1, 4, 6, 8] * List type also supports concatenation:
>>>list1=[1,4,8,16,25]
# change 2nd to 4th items >>>list2=[36,49,64,81,100]
odd[1:4] = [3, 5, 7] >>>list3=list1+list2
print(odd) >>>list3
o/p: [1, 3, 5, 7] o/p: [1,4,8,16,25, 36,49,64,81,100]

Examples : * It is possible to change the content of a list:


>>> list1=[1,4,8,16,25] Ex:
>>> list1 >>>list1=[1,4,8,16,25]
[1, 4, 8, 16, 25] >>>list1[3]=999
We can interact with indices as: >>>list1
>>> list1[0] [1,4,8,999,25]
1
>>> list1[3]
Murali Krishna Senapaty
Date: 18-04-2022
* we can use append() method to add more items to the list: List.sort() : to sort the items and to store in same place
>>>list1=[1,4,8,16,25] List.reverse() : to reverse the items and store in same place.
>>>list1.append(36)
>>>list1
o/p: [1,4,8,16,25,36] Examples:
ex: fruits=['apple','banana','gua','orange','banana']
>>>list1.append(7**2) fruits.count('banana')
>>>list1 o/p : 1
o/p: [1,4,8,16,25,36,49]
fruits.insert(2,'cherry')
* we can also add individual characters for storing to a list: fruits
Ex:
>>>list1=[‘a’,’b’,’c’] #cherry inserted at index 2
>>>list1 o/p: ['apple','banana', ‘cherry’, 'gua','orange','banana']
o/p:
[‘a’,’b’,’c’] fruits.append(‘xyz’)
fruits
If we want to change the content in a list: o/p: ['apple','banana', ‘cherry’, 'gua','orange','banana',’xyz’]
We can use index positions for it fruits.remove('cherry')
Ex: fruits
>>>list1=[‘a’,’b’,’c’,’d’,’e’,’f’]
>>>list1[2]=’C’ fruits.sort()
>>>list1 fruits
o/p: [‘a’,’b’,’C’,’d’,’e’,’f’] o/p:
fruits.reverse()
ex:to replace items in a range fruits
ex: o/p:
>>>list1[3:5]=[‘D’,’E’] x=fruits.pop()
>>>list1 print(x)
o/p: o/p:
[‘a’,’b’,’C’,’D’,’E’,’f’] Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
Nesting of list type: thislist.sort(reverse = True)
Ex: print(thislist)
>>>list1=[‘a’,’b’,’c’]
>>>list2=[1,2,3] Make a copy of a list with the copy() method:
>>>list3=[list1,list2] thislist = ["apple", "banana", "cherry"]
>>>list3[0][1] mylist = thislist.copy()
o/p: ‘b’ print(mylist)

more functions on list are: Make a copy of a list with the list() method:
list.append() : to add content at end thislist = ["apple", "banana", "cherry"]
list.insert(i,x) : to insert content at specific ith index mylist = list(thislist)
list.remove(x) : to remove x by searching. print(mylist)
List.clear() : to clear all the items of list.
List.count() : to count the no. of items exist.
Murali Krishna Senapaty
Date: 18-04-2022
Append list2 into list1: Example
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
Tuples allow duplicate values:
for x in list2: thistuple = ("apple", "banana", "cherry", "apple", "cherry")
list1.append(x) print(thistuple)
print(list1)

Use the extend() method to add list2 at the end of list1:


Tuple Length
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3] To determine how many items a tuple has, use the len() function:

list1.extend(list2)
print(list1)
Example
so a list can be used like a stack with append() and pop() methods for push/pop Print the number of items in the tuple:
operations. thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
++++++++++++++++++++++++++++++++++++++++++++++
Create Tuple With One Item
Tuple Datatype: To create a tuple with only one item, you have to add a comma after the
Tuple is similar to list, it is immutable or cannot be changed or read only.
item, otherwise Python will not recognize it as a tuple.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets. Example
example:
Tuple1=(123,”hello”,12.34) One item tuple, remember the comma:
Tuple1 thistuple = ("apple",)
print(type(thistuple))
As tuple cannot not changed so , we can apply list() method for conversion and then we
can change it. #NOT a tuple
thistuple = ("apple")
Example print(type(thistuple))
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items - Data Types
Tuple items can be of any data type:
Example
Allow Duplicates String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
Since tuples are indexed, they can have items with the same value: tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Murali Krishna Senapaty
Date: 18-04-2022
thistuple = ("apple", "banana", "cherry")
Example print(thistuple[-1])
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
Range of Indexes
Example You can specify a range of indexes by specifying where to start and where
What is the data type of a tuple? to end the range.
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
When specifying a range, the return value will be a new tuple with the
o/p: <class 'tuple'> specified items.

Example
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple. Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
Example print(thistuple[2:5])
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-
brackets
print(thistuple) By leaving out the start value, the range will start at the first item:
Access Tuple Items Example
You can access tuple items by referring to the index number, inside square
brackets:
This example returns the items from the beginning to, but NOT included,
Example "kiwi":
Print the second item in the tuple: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
thistuple = ("apple", "banana", "cherry") print(thistuple[:4])
print(thistuple[1])
By leaving out the end value, the range will go on to the end of the list:
Negative Indexing Example
Negative indexing means start from the end.
This example returns the items from "cherry" and to the end:
-1 refers to the last item, -2 refers to the second last item etc. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Example
Print the last item of the tuple: Range of Negative Indexes
Murali Krishna Senapaty
Date: 18-04-2022
Specify negative indexes if you want to start the search from the end of the
tuple:
Add Items
Example
Since tuples are immutable, they do not have a build-in append() method,
This example returns the items from index -4 (included) to index -1 but there are other ways to add items to a tuple.
(excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") 1. Convert into a list: Just like the workaround for changing a tuple, you
print(thistuple[-4:-1]) can convert it into a list, add your item(s), and convert it back into a tuple.

Check if Item Exists Example


Convert the tuple into a list, add "orange", and convert it back into a tuple:
To determine if a specified item is present in a tuple use the in keyword: thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
Example y.append("orange")
thistuple = tuple(y)
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple: 2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
print("Yes, 'apple' is in the fruits tuple") want to add one item, (or many), create a new tuple with the item(s), and
add it to the existing tuple:

Change Tuple Values Example


Once a tuple is created, you cannot change its values. Tuples Create a new tuple with the value "orange", and add that tuple:
are unchangeable, or immutable as it also is called. thistuple = ("apple", "banana", "cherry")
y = ("orange",)
But there is a workaround. You can convert the tuple into a list, change the thistuple += y
list, and convert the list back into a tuple.
print(thistuple)
Example o/p: ("apple", "banana", "cherry", "orange")
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x) Remove Items
y[1] = "kiwi"
x = tuple(y) Note: You cannot remove items in a tuple.

print(x)
Murali Krishna Senapaty
Date: 18-04-2022
Tuples are unchangeable, so you cannot remove items from it, but you can If the number of variables is less than the number of values, you can add
use the same workaround as we used for changing and adding tuple items: an * to the variable name and the values will be assigned to the variable as
a list:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
thistuple = ("apple", "banana", "cherry")
Assign the rest of the values as a list called "red":
y = list(thistuple)
y.remove("apple") fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
thistuple = tuple(y)
(green, yellow, *red) = fruits
you can delete the tuple completely:
print(green)
Example print(yellow)
print(red)
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry") o/p:
del thistuple apple
print(thistuple) #this will raise an error because the tuple no longer exists banana
['cherry', 'strawberry', 'raspberry']

Unpacking a Tuple
Example
When we create a tuple, we normally assign values to it.
Add a list of values the "tropic" variable:
Packing a tuple:
fruits = ("apple", "banana", "cherry") fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
a, b, c = fruits
(green, *tropic, red) = fruits
print(a)
print(b) print(green)
print(c) print(tropic)
o/p:
print(red)
apple
banana
o/p:
cherry
apple
['mango', 'papaya', 'pineapple']
Cherry
Using Asterisk*
Loop Through a Tuple
Murali Krishna Senapaty
Date: 18-04-2022
You can loop through the tuple items by using a for loop. Print all items, using a while loop to go through all the index numbers:

thistuple = ("apple", "banana", "cherry")


Example i=0
while i < len(thistuple):
Iterate through the items and print the values: print(thistuple[i])
i=i+1
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Join Two Tuples
Loop Through the Index Numbers To join two or more tuples you can use the + operator:

You can also loop through the tuple items by referring to their index number. Example
Use the range() and len() functions to create a suitable iterable. Join two tuples:

tuple1 = ("a", "b" , "c")


Example tuple2 = (1, 2, 3)

Print all items by referring to their index number: tuple3 = tuple1 + tuple2
print(tuple3)
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i]) Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you
Using a While Loop can use the * operator:

You can loop through the list items by using a while loop.
Example
Multiply the fruits tuple by 2:
Use the len() function to determine the length of the tuple, then start at 0 fruits = ("apple", "banana", "cherry")
and loop your way through the tuple items by refering to their indexes. mytuple = fruits * 2
Remember to increase the index by 1 after each iteration. print(mytuple)

Example
Tuple Methods
Murali Krishna Senapaty
Date: 18-04-2022
Python has two built-in methods that you can use on tuples. Python has a set of built-in methods that you can use on sets.
Method Description Method Description

count() Returns the number of times a specified add() Adds an element to the set
value occurs in a tuple
clear() Removes all the elements from the set
index() Searches the tuple for a specified value
and returns the position of where it was copy() Returns a copy of the set
found
difference() Returns a set containing the difference
between two or more sets
++++++++++++++++++++++++++++++++++++++++++++++
difference_update Removes the items in this set that are also
Set DATATYPE: () included in another, specified set

Sets are used to store multiple items in a single variable. discard() Remove the specified item
A set is a collection which is unordered, unchangeable*, Returns a set, that is the intersection of two
intersection()
and unindexed. other sets
* Note: Set items are unchangeable, but you can remove
items and add new items. intersection_upda Removes the items in this set that are not
te() present in other, specified set(s)
Sets are written with curly brackets.
isdisjoint() Returns whether two sets have a
So, set is a collection of unordered and unindexed items.
intersection or not
syntax/example:
set1={‘a’,’b’,’c’} issubset() Returns whether another set contains this
set or not

Example issuperset() Returns whether this set contains another


set or not
Create a Set:
pop() Removes an element from the set
thisset = {"apple", "banana", "cherry"}
print(thisset)
remove() Removes the specified element
o/p:
{'banana', 'apple', 'cherry'} symmetric_differe Returns a set with the symmetric
nce() differences of two sets

symmetric_differe inserts the symmetric differences from this


Set Methods nce_update() set and another

Murali Krishna Senapaty


Date: 18-04-2022
A set with strings, integers and boolean values:
union() Return a set containing the union of sets
set1 = {"abc", 34, True, 40, "male"}
update() Update the set with the union of this set and
others o/p:
{True, 34, 40, 'male', 'abc'}

Duplicates Not Allowed The set() Constructor


Sets cannot have two items with the same value. It is also possible to use the set() constructor to make a set.

Example Example
Duplicate values will be ignored: Using the set() constructor to make a set:
thisset = {"apple", "banana", "cherry", "apple"}
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset) print(thisset)

o/p: o/p:
{'banana', 'cherry', 'apple'} {'apple', 'cherry', 'banana'}

We cannot access items of set using index because set does not have indexing.
but we can access items using in statement in a for loop/if statement.
Set Items - Data Types ex:
Set items can be of any data type: s1={'apple', 'banana', 'cherry'}
print("banana" in s1)
Example o/p: true
String, int and boolean data types: ex:
s1={‘apple’, ‘banana’, ‘cherry’}
set1 = {"apple", "banana", "cherry"} for x in s1:
set2 = {1, 5, 7, 9, 3} print(x)
set3 = {True, False, False} o/p:
apple
o/p: banana
{'cherry', 'apple', 'banana'} cherry
{1, 3, 5, 7, 9}
ex:
{False, True}
s1={'apple','banana','cherry'}
if('banana' in s1):
A set can contain different data types: print("exist")
else:
print("not exist")
Example o/p:
Murali Krishna Senapaty
Date: 18-04-2022
exist [staring position: ending position:incrementation]
So, [: : -1 ] means here by default starting postion is -1 as decrementation is present.
to add items: add() method is used So next position is -1+-1=-2 and so on.
ex: s1.add(“orange”) So reading the elements will be in order of positions -1, -2, -3…
So output will be reverse.
to add multiple items update() method is used
ex: s1.update([“mango”,”grapes”]) If we write [: : 1] then the starting position will be from 0 to last index , so the items will
be displayed serially.
to get the length of a set: len() method
ex: print(len(s1))
++++++++++++++++++++++++++++++++++++++++++++++
to remove an item from a set: remove() or discard()
ex:
s1.remove(“banana”)
or
Dictionary:
s1.discard(“banana”)
* if the item not found then remove() method produces error but discard() will not Dictionaries are used to store data values in key:value pairs.
produce.
A dictionary is a collection which is ordered*, changeable and do not allow
for pop operation: pop() method used duplicates.
ex:
x=s1.pop()
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
to delete the set completely: del() method dictionaries are unordered.
ex:
del(s1) Dictionaries are written with curly brackets, and have keys and values:
to join two sets: union() method or update() method used
Syntax:
ex:
Dictionary name={ key1: item1, key2:item2..}
s1={'a','b','c'}
s2={1,2,3}
s3=s1.union(s2) Example
print(s1)
print(s2) Create and print a dictionary:
print(s3)
thisdict = {
using update() method:
ex:
"brand": "Ford",
s1={'a','b','c'} "model": "Mustang",
s2={1,2,3} "year": 1964
s1.update(s2) }
print(s1) print(thisdict)
print(s2)

*why [::-1] gives a reverse list of elements: Dictionary Items


Answer:
Syntax of list is Dictionary items are ordered, changeable, and does not allow duplicates.
Murali Krishna Senapaty
Date: 18-04-2022
Dictionary items are presented in key:value pairs, and can be referred to by Print the number of items in the dictionary:
using the key name. print(len(thisdict))

Example o/p:
3
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford", Dictionary Items - Data Types
"model": "Mustang",
"year": 1964 The values in dictionary items can be of any data type:
}
print(thisdict["brand"]) Example
O/P:
Ford String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
Duplicates Not Allowed "electric": False,
"year": 1964,
Dictionaries cannot have two items with the same key: "colors": ["red", "white", "blue"]
}
Example o/p:
Duplicate values will overwrite existing values: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
thisdict = {
"brand": "Ford",
"model": "Mustang", Accessing Items
"year": 1964,
"year": 2020 You can access the items of a dictionary by referring to its key name, inside
} square brackets:
print(thisdict)
Example
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020} Get the value of the "model" key:
thisdict = {
"brand": "Ford",
Dictionary Length "model": "Mustang",
"year": 1964
To determine how many items a dictionary has, use the len() function: }
x = thisdict["model"]
Example o/p:
Murali Krishna Senapaty
Date: 18-04-2022
Mustang
Get Values
Get Keys The values() method will return a list of all the values in the dictionary.

Example
The keys() method will return a list of all the keys in the dictionary.
Get a list of the values:
Example x = thisdict.values()

Get a list of the keys: o/p:


x = thisdict.keys() dict_values(['Ford', 'Mustang', 1964])

o/p: Example
dict_keys(['brand', 'model', 'year'])
Make a change in the original dictionary, and see that the values list gets
updated as well:
Example car = {
"brand": "Ford",
Add a new item to the original dictionary, and see that the keys list gets "model": "Mustang",
updated as well: "year": 1964
car = { }
"brand": "Ford",
"model": "Mustang", x = car.values()
"year": 1964
} print(x) #before the change

x = car.keys() car["year"] = 2020

print(x) #before the change print(x) #after the change

car["color"] = "white" o/p:


dict_values(['Ford', 'Mustang', 1964])
print(x) #after the change dict_values(['Ford', 'Mustang', 2020])

o/p:
dict_keys(['brand', 'model', 'year']) Example
dict_keys(['brand', 'model', 'year', 'color'])
Add a new item to the original dictionary, and see that the values list gets
updated as well:
Murali Krishna Senapaty
Date: 18-04-2022
car = { "model": "Mustang",
"brand": "Ford", "year": 1964
"model": "Mustang", }
"year": 1964
} x = car.items()

x = car.values() print(x) #before the change

print(x) #before the change car["year"] = 2020

car["color"] = "red" print(x) #after the change

print(x) #after the change o/p:


dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
o/p: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])
Check if Key Exists
Get Items To determine if a specified key is present in a dictionary use the in keyword:

The items() method will return each item in a dictionary, as tuples in a list. Example
Check if "model" is present in the dictionary:
Example thisdict = {
"brand": "Ford",
Get a list of the key:value pairs
"model": "Mustang",
"year": 1964
x = thisdict.items()
}
o/p: if "model" in thisdict:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) print("Yes, 'model' is one of the keys in the thisdict dictionary")

o/p:
Yes, 'model' is one of the keys in the thisdict dictionary
Example
Make a change in the original dictionary, and see that the items list gets
updated as well: Change Values
car = { You can change the value of a specific item by referring to its key name:
"brand": "Ford",
Murali Krishna Senapaty
Date: 18-04-2022
The pop() method removes the item with the specified key name:
Example thisdict = {
"brand": "Ford",
Change the "year" to 2018:
"model": "Mustang",
thisdict = {
"year": 1964
"brand": "Ford",
}
"model": "Mustang",
thisdict.pop("model")
"year": 1964
print(thisdict)
}
thisdict["year"] = 2018 o/p:
o/p: {'brand': 'Ford', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Example
Update Dictionary
The popitem() method removes the last inserted item (in versions before
The update() method will update the dictionary with the items from the given 3.7, a random item is removed instead):
argument. thisdict = {
"brand": "Ford",
The argument must be a dictionary, or an iterable object with key:value "model": "Mustang",
pairs. "year": 1964
}
Example thisdict.popitem()
print(thisdict)
Update the "year" of the car by using the update() method:
o/p:
thisdict = { {'brand': 'Ford', 'model': 'Mustang'}
"brand": "Ford",
"model": "Mustang",
"year": 1964 Example
}
thisdict.update({"year": 2020}) The del keyword removes the item with the specified key name:
o/p: thisdict = {
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020} "brand": "Ford",
"model": "Mustang",
"year": 1964
Removing Items }
del thisdict["model"]
print(thisdict)
There are several methods to remove items from a dictionary:
o/p:
Example
Murali Krishna Senapaty
Date: 18-04-2022
{'brand': 'Ford', 'year': 1964}
Example
Print all values in the dictionary, one by one:
Example for x in thisdict:
print(thisdict[x])
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford", Example
"model": "Mustang",
"year": 1964
You can also use the values() method to return values of a dictionary:
}
for x in thisdict.values():
del thisdict
print(x)
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Example xample
The clear() method empties the dictionary: You can use the keys() method to return the keys of a dictionary:
thisdict = { for x in thisdict.keys():
"brand": "Ford", print(x)
"model": "Mustang",
"year": 1964
} Example
thisdict.clear()
print(thisdict) Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well. because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
Example
There are ways to make a copy, one way is to use the built-in Dictionary
Print all key names in the dictionary, one by one: method copy().
for x in thisdict:
print(x) Example
Murali Krishna Senapaty
Date: 18-04-2022
Make a copy of a dictionary with the copy() method: "year" : 2011
thisdict = { }
"brand": "Ford", }
"model": "Mustang",
"year": 1964 Example
}
mydict = thisdict.copy() Create three dictionaries, then create one dictionary that will contain the
print(mydict) other three dictionaries:
child1 = {
Another way to make a copy is to use the built-in function dict(). "name" : "Emil",
"year" : 2004
Example }
child2 = {
Make a copy of a dictionary with the dict() function: "name" : "Tobias",
thisdict = { "year" : 2007
"brand": "Ford", }
"model": "Mustang", child3 = {
"year": 1964 "name" : "Linus",
} "year" : 2011
mydict = dict(thisdict) }
print(mydict)
myfamily = {
Nested Dictionaries "child1" : child1,
"child2" : child2,
"child3" : child3
A dictionary can contain dictionaries, this is called nested dictionaries.
}
Example
Create a dictionary that contain three dictionaries: Dictionary Methods
myfamily = {
"child1" : { Python has a set of built-in methods that you can use on dictionaries.
"name" : "Emil", Method Description
"year" : 2004
}, clear() Removes all the elements from the dictionary
"child2" : {
"name" : "Tobias", copy() Returns a copy of the dictionary
"year" : 2007
}, fromkeys() Returns a dictionary with the specified keys and
"child3" : { value
"name" : "Linus",
Murali Krishna Senapaty
Date: 18-04-2022
get() Returns the value of the specified key Type conversion in python:
items() Returns a list containing a tuple for each key value =============================
pair python defines type conversion functions to convert from one datatype to another type.
int(): to convert into int datatype.
ex1:
keys() Returns a list containing the dictionary's keys
x=int(10)
y=int(2.5)
pop() Removes the element with the specified key z=int(“12”)
print(x)
popitem() Removes the last inserted key-value pair print(y)
print(z)
setdefault() Returns the value of the specified key. If the key int along with base: int(a,base)
does not exist: insert the key, with the specified here the base represents the base for the digits in given string.
value Ex:
s1=’10010’
Updates the dictionary with the specified key-value c=int(s1,2)
update()
print(c)
pairs d=int(s1,10)
print(d)
values() Returns a list of all the values in the dictionary o/p:
18
10010
Examples using different datatypes: float(): it converts into float type.
------------------------------------------------ Ex:
Python can be used as a calculator: x=float(12)
+, - *, / , ( , ) etc directly on prompt similar to the simple calculator y=float(2.5)
Here the operator / gives by default float result when we apply even on integers. z=float(“3”)
Ex: r=float(“3.6”)
>>> 12/5 print(x)
2.4 print(y)
To get a floor division we can use // operator print(z)
Ex: print(r)
>>> 12//5
2 o/p:
12.0
*when we use python prompt as a calculator then the recent calculation result is 2.5
maintained in a variable _ (underscore) 3.0
3.6
>>>x=20
>>>y=30 Str(): used to convert into string type
>>>x+y Ex:
50 x=str(‘s1’)
>>>_+70 y=str(25)
120 z=str(3.5)
Murali Krishna Senapaty
Date: 18-04-2022
print(x) c=list(str1)
print(y) print(c)
print(z) o/p:
o/p: ['h', 'e', 'l', 'l', 'o', ' ', 'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u']
s1
25 dict() : to convert a tuple into a dictionary where provide (value,key)
3.5 ex:
t1=((‘a’,1), (‘b’,2), (‘c’,3))
Ord(): used to convert a character to integer to get Unicode d1=dict(t1)
Ex: print(d1)
s=’a’; o/p:
c=ord(s) {'a': 1, 'b': 2, 'c': 3}
print(c)
o/p:
97
Hex() : to convert integer to hexa decimal.
Oct(): to convert integer to octal number. Python operators:
Tuple(): to convert into tuple type
Ex: Python divides the operators in the following groups:
s="hello world"
x=tuple(s)
print(x)  Arithmetic operators
o/p:  Assignment operators
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')  Comparison operators
 Logical operators
str(): it is used to convert an integer into string
ex:  Identity operators
a=123  Membership operators
b=str(a)  Bitwise operators
print(b)
o/p: ‘123’
complex() : it is to convert integer to complex number.
Ex:
Python Arithmetic Operators
x=complex(12,5)
print(x) Arithmetic operators are used with numeric values to perform
type(x) common mathematical operations:
set() : it is used to convert into set type Operator Name Example
ex:
s=”hello”;
c=set(s) + Addition x+y
print(c)
o/p: { ‘h’, ‘e’, ‘l’, ‘o’} - Subtraction x-y
list() : it is to convert into list type.
Ex: * Multiplication x*y
str1=”hello how are you”;
Murali Krishna Senapaty
Date: 18-04-2022
/ Division x/y &= x &= 3 x=x&3

% Modulus x%y |= x |= 3 x=x|3

** Exponentiation x ** y ^= x ^= 3 x=x^3

// Floor division x // y >>= x >>= 3 x = x >> 3

Example: <<= x <<= 3 x = x << 3


5/2 = 2.5

Python Comparison Operators


5//2 = 2
5**2 = 25

Comparison operators are used to compare two values:


Python Assignment Operators
Assignment operators are used to assign values to variables: Operator Name Example

== Equal x == y
Operator Example Same As
!= Not equal x != y
= x=5 x=5
> Greater than x>y
+= x += 3 x=x+3
< Less than x<y
-= x -= 3 x=x-3
>= Greater than or equal to x >= y
*= x *= 3 x=x*3
<= Less than or equal to x <= y
/= x /= 3 x=x/3

%= x %= 3 x=x%3 Python Logical Operators


Logical operators are used to combine conditional statements:
//= x //= 3 x = x // 3
Operator Description Example
**= x **= 3 x = x ** 3
and Returns True if both statements x < 5 and x < 10

Murali Krishna Senapaty


Date: 18-04-2022
are true specified value is present in the object

or Returns True if one of the x < 5 or x < 4 not in Returns True if a sequence with the x not in
statements is true specified value is not present in the object y

not Reverse the result, returns False not(x < 5 and x < 10) Example:
if the result is true Ex:
a=10
list1=[1,2,3,4,5]
Python Identity Operators if(a in list1):
print("present")
Identity operators are used to compare the objects, not if they are else:
equal, but if they are actually the same object, with the same print("not present")
memory location:
Operator Description Example Python Bitwise Operators
is Returns True if both variables are x is y
the same object Bitwise operators are used to compare (binary) numbers:
Operator Name Description
is not Returns True if both variables are x is not y
not the same object & AND Sets each bit to 1 if both bits are 1
Example:
ex: | OR Sets each bit to 1 if one of two bits is 1
a=20
b=25 ^ XOR Sets each bit to 1 if only one of two bits is 1
if(a is b):
print("true") ~ NOT Inverts all the bits
else:
print("false")
<< Zero fill Shift left by pushing zeros in from the right

Python Membership Operators left shift and let the leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost


Membership operators are used to test if a sequence is presented right shift bit in from the left, and let the rightmost
in an object: bits fall off

Operator Description Example


operators precedence:
in Returns True if a sequence with the x in y
====================
Murali Krishna Senapaty
Date: 18-04-2022
Level operators enter 2nd number456
1 () 123456
2 ** >>>
3 ~, +, - (unary)
4 *, /, %, //
5 +, - (binary)
6 <<, >>
Python i/o statements:
7 & (bitwise) print() : it is an output statement to print data or message.
8 ^, | (bitwise) Syntax:
9 <, <=, >, >= print(*object, sep=’ ‘, end=’\n’, file=sys.stdout, flush=false)
10 <>, ==, !=
11 =, +=, -=, *=, %=, //=, **= object: here object are the arguments or values to print
12 is, is not
sep: is the separator between the values
13 in, not in
14 and, or, not end: executes by default after printing all the content.
----------------------------------------------------------
File: it represents where the data to be printed

PYTHON COMMENTS: sys.stdout is standard output device


Comments can be written using # or ’’’ flush : by default it is false so that printed data shall not be cleared.
Single line comment: it can be written using #
Ex: #it is question of a program
example1:
Multi line comment : it can be written using ‘’’ at the beginning and ‘’’ at the end. x = ("apple", "banana", "cherry")
Ex: print(x)
‘’’ about the program the comment can be written in multiple lines’’’
example2:
Simple programs for practice: print("Hello", "how are you?", sep="---")
Q1)
#a simple program to find sum
example3:
'''this is a multiline comment i am writing question,
name of the programmer and date, last update date,
formula used ''' # Three objects are passed
print('a =', a, '= b')
a=20
b=34 example4:
c=a+b
#it is 2nd comment line
print(c) a = 5
print("a =", a, sep='00000', end='\n\n\n')
ex2: print("a =", a, sep='0', end='')
#2nd program
a=input("enter 1st number")
b=input("enter 2nd number") o/p:
c=a+b
print(c)
o/p: a =000005
enter 1st number123
Murali Krishna Senapaty
Date: 18-04-2022
Syntax:
a =05 Variable=input([prompt])

Example1:
Ask for the user's name and print it:
.format() method: print('Enter your name:')
this method takes the pass arguments, formats and then places them in the string x = input()
where place holders {} are present. print('Hello, ' + x)

Syntax:
{}.format(value) Example2:
Here (value) can be integer/string/float etc Num=input(“enter a number”)

Ex1: Example3:
print(“{} , how are you”.format(“alok”)) Print(“enter a number”)
Num=input()
#print("{} , how are you".format("alok"))
#o/p: alok , how are you By default the input statement accepts the data in string form, so we need type
conversion as per the user’s requirement.
#.format can be used with string
s="how are you" Multiple Input :
print("alok {} , i am fine".format(s)) We can input multiple data in one line using two methods:
1. split()
a=15; b=25 2. List comprehension
print("the 1st value is {0} and 2nd value is {1}".format(a,b))
print("the 1st value is {1} and 2nd value is {0}".format(a,b)) split(): This method helps to input multiple data.
Syntax:
x="apple"; y="orange";xcost=120;ycost=60 input().split(separator)
print("i like {} and i need {}".format(x,y))
print("i like {} and its cost is {}".format(x,xcost)) example1:
# taking two inputs at a time
#we can even use keyword arguments to format the string
x, y = input("Enter a two value: ").split()
print("hello {name}, {greetings}".format(greetings="good morning",name="sam"))
print("Number of boys: ", x)
print("Number of girls: ", y)
we can also use the format specifiers of c language here:
ex: print()
x=12.3456
print(“the value is %f”%x) # taking three inputs at a time
x, y, z = input("Enter a three value: ").split()
x=12.3456 print("Total number of students: ", x)
print("the value is %f"%x) print("Number of boys is : ", y)
y="hello" print("Number of girls is : ", z)
print("string is %s"%y) print()

standard input statement: # The default separator is space.


input() : This method allows to input data to the variables.
Murali Krishna Senapaty
Date: 18-04-2022
#using separator sep with split() replace() : It is a method for searching a string and replacing with alternate string.
x, y, z = input("Enter a three value: ").split(sep=',') Ex:
a=”hello world”
print(a.replace(“he”,”me”)
List Comprehension: List comprehension is an elegant way to define and create list
in Python. We can create lists just like mathematical statements in one line only. It is ex:
also used in getting multiple inputs from a user. a="hello world hello friends"
print(a.replace("llo","yllow"))
# taking two input at a time
x, y = [int(x) for x in input("Enter two value: ").split()] Writing multiple statements per line:
print("First Number is: ", x) In python we can write multiple statements in a line separated by ;
print("Second Number is: ", y) a=10;b=30;c=50
print() print(a);print(b+c)
# taking three input at a time
When we write statement which is larger than a line then python
x, y, z = [int(x) for x in input("Enter three value: ").split()]
allows to write a single statement in multiple lines.
print("First Number is: ", x)
print("Second Number is: ", y)
Example1: When we write statement within [] or () or {} then we can write in multiple
print("Third Number is: ", z)
lines
print()
a=[ [1,2], [2,3],
[3,4], [4,5],
# taking multiple inputs at a time [5,6]]
#it creates a list of elements by default
x = [int(x) for x in input("Enter multiple value: ").split()] '''a=[ [1,2], [2,3],
print("Number of list is: ", x) [3,4], [4,5],
[5,6]]
# taking multiple inputs at a time print(a)
#it creates a tuple of elements '''
x = tuple([int(x) for x in input("Enter multiple value: ").split()])
print("Number of list is: ", x) '''a=['hello \
naveen \
# taking multiple inputs at a time how \
#it creates a set of elements are \
x = set([int(x) for x in input("Enter multiple value: ").split()]) you ']
print("Number of list is: ", x) print(a)
'''
========================================================= x=10/20-35+\
strip() : It is used along with strings for removing the 12**5\
white space characters from beginning and end of a string. -34
Ex: print(x)
s1=" hello world ";
s2=s1.strip() general syntax of python compared to ‘C’:
print(s2) 1) Variables can be declared as and when required.
o/p: In python the variable can contain any type of data.
“hello world” Ex: x=25; x=5.345; x=”hello”
2) In python semicolon(;) is used when we write multiple statements
Murali Krishna Senapaty
Date: 18-04-2022
in a single line
3) Python have built in dynamic memory allocation process,
so separate DMA functions are not required(like in c malloc(), free(),
new, delete)
4) In python to write a code no structure or layout is required like in C
5) In python to represent a block we do not require {} rather we need
indenting
6) In python a function can accept any type of arguments and can return
any datatype. (not like in c language ex: float div(int, int);)

Ex1:find area of a triangle


import cmath
a,b,c=input("enter 3 sides").split()
a=int(a);b=int(b);c=int(c);
s=(a+b+c)/2
print(s)
area=cmath.sqrt(s*(s-a)*(s-b)*(s-c))
print("area of a triangle is",area)

ex2:#find the distance between two points


import cmath
point1=[4,0] #x1,y1
point2=[6,6] #x2,y2
distance=cmath.sqrt((point2[0]-point1[0])**2 + (point2[1]-point1[1])**2)
print("the distance is",distance)

# This prints out "Hello, John!"


name = "John"
print("Hello, %s!" % name)

To use two or more argument specifiers, use a tuple (parentheses):


# This prints out "John is 23 years old."
name https://www.learnpython.org/en/String_Formatting=
https://www.learnpython.org/en/String_Formatting"John"
age = 23
print("%s is %d years old." % (name, age))

Murali Krishna Senapaty


Date: 18-04-2022

You might also like