0% found this document useful (0 votes)
8 views89 pages

Python Syntax, Keywords, Variables, Data Types, Operators

The document provides an overview of Python syntax, keywords, variables, and data types. It covers essential topics such as statement endings, indentation rules, comments, naming conventions, and built-in data types like integers, floats, and strings. Additionally, it explains the mutable and immutable types, as well as how to display output and get user input.

Uploaded by

arnavkumar90063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views89 pages

Python Syntax, Keywords, Variables, Data Types, Operators

The document provides an overview of Python syntax, keywords, variables, and data types. It covers essential topics such as statement endings, indentation rules, comments, naming conventions, and built-in data types like integers, floats, and strings. Additionally, it explains the mutable and immutable types, as well as how to display output and get user input.

Uploaded by

arnavkumar90063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Python Syntax,

Keywords, Variables,
Data Types
Presented by
Mohd Shuaib
Assistant Professor
Python Syntax
• Statement ends with the token NEWLINE character ( i.e. carriage return).
• It means each line is a statement in python Script.

Example: 4 statements in 4 separate lines

print('SNo: ', 1)
print('First Name: ', 'Aditya')
print('Last Name: ', 'Joshi')
print('Age: ', 19)
• One statement is joined by backslash character \ if it is spanned over multiple
lines
Example:
if 1000 > 10 and \
20 <= 30 and \
True != False and \
False == False :
print('correct conditions')
• Two different statements can not be joined with \ in single line.
print('Hello \
BCA class!') # a multi-line statement
print('Hello') \
print(' BCA class!') # two statement in one logical line give SyntaxError: invalid
syntax
• the semicolon ; is used to separate multiple statements in a single line.
Example:
print('Hello');print('BCA class!');print('how are you’)

• Expressions in parentheses (), square brackets [ ], or curly braces { } can be


spread over multiple lines without using \.

Example:

list = [10, 20, 30, 40,


50, 60, 70, 80,
90, 100, 110, 120]
Indentation in Python
Leading space or tab at the beginning of the line is considered as indentation
level of the line, which is used to determine the group of statements.
Statements with the same level of indentation considered as a group or block.

For example, functions, classes, or loops in Python contains a block of


statements to be executed.

C# or Java use curly braces { } to denote a block of code. Python uses


indentation (a space or a tab) to denote a block of statements.
Indentation Rules

Use the colon : to start a block and press Enter.

All the lines in a block must use the same indentation, either space or a tab.

Python recommends four spaces as indentation to make the code more


readable. Do not mix space and tab in the same block.

A block can have inner blocks with next level indentation.


Example: demonstration of if else blocks

if 10 > 5: # 1st block starts


print("10 is greater than 5") # 1st block
print("Now checking 20 > 10") # 1st block
if 20 > 10: # 1st block
print("20 is greater than 10") # inner block
else: # 2nd block starts
print("10 is less than 5") # 2nd block
print("This will never print") # 2nd block
Function contains a block with 2 statements

def welcomemsg(msg):
print("Hello ", msg)
print("Welcome to Python class BCA Stuents")

You may use either interactive shell or IDLE or any GUI based IDE

Error will be
IndentationError: expected an indented block if you not use indentation or
IndentationError: unexpected indent
Comments

• In a Python script, the symbol # indicates the start of a


comment line. It is effective till the end of the line in the
editor.

# this is a comment
print("Hello students")
# print("Welcome to Python class")
print("with interesting matplotlib library") #comment after a statement.
Multiline comments
• There is no provision for making multi line comments but you can make multi line string
Python multi-line comment is a piece of text enclosed in a delimiter
(“””) on each end of the comment. Again there should be no white
space between delimiters (“””). Single or double quotes both may be
used
# Write Python code here

""" Multi-line comment used


print("Python Comments") """

print("Hello Class")
• However, if these multiline comments are placed directly after a
function or class signature, then these turn into docstrings.
• Docstring is an in-built feature of Python, which is used to associate
documentation that has been written with Python modules,
functions, classes and methods. It is added right below the
functions, modules, or classes to describe what they do. In Python,
the docstring is then made available via the __doc__ attribute.

def add(a, b):


"""adds the value of a and b"""
return a+b
# Print the docstring of add function
print(add.__doc__)

print(add(2, 10))
Python Naming Conventions
Identifiers
Script may contain variables, functions, classes, packages etc.
• Identifier is the name given to these programming elements.
• An identifier should start with either an alphabet letter (lower or
upper case) or an underscore (_).
• After that, more than one alphabet letter (a-z or A-Z), digits (0-9), or
underscores may be used to form an identifier.
• No other characters are allowed.
• Identifiers in Python are case sensitive, which means variables named age
and Age are different.
• Class names should use the TitleCase convention. It should begin with an
uppercase alphabet letter e.g. MyClass, Student, Employee.
• Function names should be in lowercase. Multiple words should be separated
by underscores, e.g. add(num), calculate_tax(amount).
• Variable names in the function should be in lowercase e.g., x, num, salary.
• Module and package names should be in lowercase e.g., mymodule,
tax_calculation. Use underscores to improve readability.
• Constant variable names should be in uppercase e.g., RATE, TAX_RATE.
• Use of one or two underscore characters when naming the instance attributes
of a class.
• Two leading and trailing underscores are used in Python itself for a special
purpose, e.g. __add__, __init__, etc.
Display Output
• The print() serves as an output statement in Python. It echoes the value of any
Python expression on the Python shell.
• Multiple values can be displayed by the single print() function separated by comma.
The following example displays values of name and age variables using the single
print() function.
name="Aditya"
print(name) # display single variable
age=19
print(name, age)# display multiple variables
print("Name:", name, ", Age:",age) # display formatted output

By default, a single space ' ' acts as a separator between values. However, any other
character can be used by providing a sep parameter.
Getting User's Input
• The input() function is a part of the core library of standard Python
distribution. It reads the key strokes as a string object which can be referred to
by a variable having a suitable name.

• The blinking cursor waits for the user's input. The user enters his input and
then hits Enter. This will be captured as a string.

• The input() function has an optional string parameter that acts as a prompt for
the user.

• The input() function always reads the input as a string, even if comprises of
digits. The type() function used earlier confirms this behaviour.
name=input("Enter your name: ")
print(type(name))
age=input("Enter your age: ")
print(type(age))
Keywords
• These are predefined words having special purpose and cannot be used for other things
• Except for the first three (False, None and True), the other keywords are entirely in lowercase.
Get it by
help("keywords") 35 keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Variables in Python
• Variable is the name given to a value.
• We can refer this value later on with the name of the variable
• Variable points to an object.
• A literal value is assigned to a variable using = operator
• Left side should be the name of a variable and right side should be the
value.

>>> n=20
>>> n
20
• print() is also used to display the value of variable

>>> print(n) #display value


20
>>> print(n + 2) # add and display the result
22

• Variables in Python are objects. Use the type() function to get the class name
of an object.
>>> type(n)
<class 'int’>
The type of n is int. An object of int class contains a integer literal 20
• Depending upon the value they are all class
>>> msg='Hello World'
>>> type(msg)
<class 'string'>
>>> isPythonInterpreted = True
>>> type(isPythonInterpreted)
<class 'bool’>

• Python is a dynamically-typed language, which means you don't need to


declare a type of a variable. The type will be assigned dynamically based
on the assigned value.
• Different operations can be performed on variables using various operators
based on the type of variables.
• the + operator adds up two int variables.
• It concatenates two string type variables.

>>> a=10
>>> b=10
>>> a+b
20
>>> a='Hello '
>>> b='Class'
>>> a+b
'Hello Class'
Identity of Object
• Each object in Python has an id.
• It is the object's address in memory represented by an integer value. The
id() function returns the id of the specified object where it is stored.
>>> a=100
>>> id(a)
140723188454144
>>> msg="hello class"
>>> id(msg)
3125284964016
• An id will be changed if a variable changed to different value.
>>> msg="hello class"
>>> id(msg)
3125284964016
>>> msg="BCA Class is good"
>>> id(msg)
3125283818352
• Multiple variables assigned to the same literal value will have the same id
>>> a=100
>>> id(a)
140723188454144
>>> z=100
>>> id(z)
140723188454144
>>> b=a
>>> id(b)
140723188454144
• Python optimize memory usage by not creating separate objects if they point to same
value.

Multiple Variables Assignment

• you can assign it in a single statement like this


>>> x, y, z = 10, 20, 30
>>> x
10
>>> y
20
>>> z
30
• You can also declare different types of values to variables in a single
statement
>>> x, y, z = 310, 'Hello Class', False
>>> x
310
>>> y
'Hello Class'
>>> z
False

• Assign a value to each individual variable separated by a comma will throw a


syntax error
>>> x = 310, y = 'Hello class', z = False
File "<stdin>", line 1
SyntaxError: cannot assign to literal
Python Data Types
• Python supports the following built-in data types.
Scalar Data Types
int: Positive or negative whole numbers (without a fractional part) e.g. -20, 20,
286, 286765.
float: Any real number with a floating-point representation in which a
fractional component is denoted by a decimal symbol or scientific notation e.g.
1.5, 3.4556789e2.
complex: A number with a real and imaginary component represented as 2 +
3j.
bool: Data with one of two built-in values True or False in Title Case. true and
false are not valid booleans and Python will throw an error for them.
None: The None represents the null object in Python. A None is returned by
functions that don't explicitly return a value.
Sequence Data Types
A sequence is an ordered collection of similar or different data types. Python has
the following built-in sequence data types:

String: A string value is a collection of one or more characters put in single,


double or triple quotes.

List: A list object is an ordered collection of one or more data items, not
necessarily of the same type, put in square brackets.

Tuple: A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses.
Mapping Data Type
Dictionary: A dictionary Dict() object is an unordered collection of data in a
key:value pair form. A collection of such pairs is enclosed in curly brackets. For
example: {1:“Aditya", 2:“Joshi", 3:"Ram", 4: “Shree"}

Set Data Types


set: Set is mutable, unordered collection of distinct hashable objects. The set is
a Python implementation of the set in Mathematics. A set object has suitable
methods to perform mathematical set operations like union, intersection,
difference, etc.

frozenset: Frozenset is immutable version of set whose elements are added


from other iterables.
Mutable and Immutable Types

Data objects of the above types are stored in a computer's memory for
processing. Some of these values can be modified during processing, but
contents of others can't be altered once they are created in the memory.

Numbers, strings, and Tuples are immutable, which means their contents can't
be altered after creation.

On the other hand, items in a List or Dictionary object can be modified. It is


possible to add, delete, insert, and rearrange items in a list or dictionary. Hence,
they are mutable objects.
Number, String, List, Tuple, Set, Dictionary
Three numeric types is used to represent numbers:
integers, float, and complex number.
Int
In Python, integers are zero, positive or negative whole numbers without a fractional part and having unlimited
precision, e.g. 0, 200, -20. The followings are valid integer literals in Python.
0
>>> 0
0
>>> 200
200
>>> -20
-20
>>>
y=1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000
>>> y
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000
• Integers can be binary, octal, and hexadecimal values.
>>> 0b11011
27
>>> 0o12
10
>>> 0x14
20

• Leading zeros in non-zero integers are not allowed e.g. 02345 is invalid number, 0000 is 0.

>>> 0000
0
>>> 02345
File "<stdin>", line 1
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal
integers
• Python does not allow comma as number delimiter. Use underscore _ as a
delimiter instead.
>>> a=1_2_3_56
>>> a
12356

• integers must be without a fractional part (decimal point). It includes a


fractional then it becomes a float.
>>> a=10.0
>>> type(a)
<class 'float'>
• The int() function converts a string or float to int.
>>> int('200')
200
>>> int(10.5)
10

Float
In Python, floating point numbers (float) are positive and negative real numbers
with a fractional part denoted by the decimal symbol . or the scientific notation
E or e, e.g. 1234.56, 3.142, -1.55, 0.23.
>>> x=1.5
>>> type(x)
<class 'float'>
>>> f=2e400
>>> f
Inf
Floats has the maximum size depends on your system. The float beyond its maximum size referred
as "inf", "Inf", "INFINITY", or "infinity". Float 2e400 will be considered as infinity for most systems.
Scientific notation is used as a short representation to express floats having many digits. For
example: 345.56789 is represented as 3.4556789e2 or 3.4556789E2
>>> f=1e3
>>> f
1000.0
>>> f=1e5
>>> f
100000.0
>>> f=3.4556789e2
>>> f
345.56789
• Use the float() function to convert string, int to float.

>>> float('5.5')
5.5
>>> float('5')
5.0
>>> float(' -5')
-5.0
>>> float('1e3')
1000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf
Complex Number
A complex number is a number with real and imaginary components. For
example, 5 + 8j is a complex number where 5 is the real component and 8
multiplied by j is an imaginary component.
>>> a=5+9j
>>> a
(5+9j)
>>> type(a)
<class 'complex’>

You must use j or J as imaginary component. Using other character will throw
syntax error.
Arithmetic Operators

Operator Description Example


+ (Addition) Adds operands on either side of the >>> a=10; b=20
operator. >>> a+b
30
- (Subtraction) Subtracts the right-hand operand from >>> a=10; b=20
the left-hand operand. >>> b-a
10
>>> a-b
-10
* (Multiplication) Multiplies values on either side of the >>> a=10; b=20
operator. >>> a*b
200
/ (Division) Divides the left-hand operand by the >>> a=10; b=20
right-hand operand. >>> b/a
2
% (Modulus) Returns the remainder of the division of the >>> a=10; b=22
left-hand operand by right-hand operand. >>> b%a
2

** (Exponent) Calculates the value of the left-operand raised >>> a=3


to the right-operand. >>> a**2
9
>>> a**3
27
// (Floor Division) The division of operands where the result is >>> a=9; b=2
the quotient in which the digits after the >>> a//b
decimal point are removed. But if one of the 4
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative
infinity):
Arithmetic Operations on complex numbers
>>> a=6+4j
>>> a+2
(8+4j)
>>> a*2
(12+8j)
>>> a/2
(3+2j)
>>> a**2
(20+48j)
>>> b=3+2j
>>> a+b
(9+6j)
>>> a-b
(3+2j)
The arithmetic operators can also be used with two complex numbers, as
shown below.
>>> a=6+4j
>>> b=3+2j
>>> a+b
(9+6j)
>>> a-b
(3+2j)
>>> a*b
(10+24j)
The process of multiplying these two complex numbers is very similar to
multiplying two binomials. Multiply each term in the first number by each term
in the second number.
a=6+4j
b=3+2j
c=a*b
c=(6+4j)*(3+2j)
c=(18+12j+12j+8*-1)
c=10+24j
Python String
• string is an immutable sequence data type. It is the sequence of Unicode
characters wrapped inside single, double, or triple quotes.

str1="This is Python Class of BCA 4"


print(str1)

str1='''This is
the first
Multi-line string.
'''
print(str1)
• If a string literal required to embed double quotes as part of a string then, it
should be put in single quotes. Likewise, if a string includes a single quote as a
part of a string then, it should be written in double quotes.

str1='Welcome to "Python Class" BCA Students'


print(str1)
str2="Welcome to 'Python Class' BCA Students"
print(str2)

• len() function to retrieve the length of a string


>>> str1="welcome to python Class"
>>> len(str1)
23
• A sequence is defined as an ordered collection of items. Hence, a string is an ordered collection of characters. The
sequence uses an index, starting with zero to fetch a certain item (a character in case of a string) from it.
>>> str1="Python"
>>> str1[0]
'P'
>>> str1[1]
'y'
>>> str1[2]
't'
>>> str1[3]
'h'
>>> str1[4]
'o'
>>> str1[5]
'n'
>>> str1[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
• Python supports negative indexing too, starting with -(length of string) till -1.
>>> str1[-6]
'P'
>>> str1[-5]
'y'
>>> str1[-4]
't'
>>> str1[-3]
'h'
>>> str1[-2]
'o'
>>> str1[-1]
'n'
• The string is an immutable object. Hence, it is not possible to modify it. The
attempt to assign different characters at a certain index results in errors.
>>> str1="Python"
>>> str1[0]="C"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ‘str1' object does not support item assignment

• All strings are objects of the str class in Python.


>>> type(str1)
<class 'str'>
• Use the str() function to convert a number to a string.
>>> str(300)
'300'
>>> str(-20)
'-20'
>>> str(True)
'True'
Escape Sequences
backslash \ is used as an escape character. Use a backslash character followed
by the character you want to insert in a string e.g. \' to include a quote, or \" to
include a double quotes in a string
str1='Welcome to \'Python Class\' BCA Students'
print(str1)

str2="Welcome to \"Python Class\" BCA Students"


print(str2)

Use r or R to ignore escape sequences in a string.


str2=R"Welcome to \"Python Class\" BCA Students"
print(str2)
Escape sequence Description Example
\\ Backslash >>> "Hello\\Hi"
Hello\Hi

\b Backspace >>> "ab\bc"


ac

\n Newline >>> "hello\nworld"


Hello
world

\t Tab >>> 'Hello\tPython'


Hello Python
Operator Description Example
+ Appends the second string to the first >>> a='hello'
>>> b='world'
>>> a+b
'helloworld'

* Concatenates multiple copies of the same string >>> a='hello'


>>> a*3
'hellohellohello'

[] Returns the character at the given index >>> a = 'Python'


>>> a[2]
t
[:] Fetches the characters in the range specified by two index operands separated >>> a = 'Python'
by the : symbol >>> a[0:2]
'Py'

in Returns true if a character exists in the given string >>> a = 'Python'


>>> 'x' in a
False
>>> 'y' in a
True
>>> 'p' in a
False

not in Returns true if a character does not exist in the given string >>> a = 'Python'
>>> 'x' not in a
True
>>> 'y' not in a
False
Python - List

• list is a mutable sequence data type. A list object contains one or more items
of different data types in the square brackets [] separated by a comma.
Declaration of lists variable:
>>> list1=[] # empty list
>>> print(list1)
[]
>>> stunames=["Aditya", "Joshi", "Yogesh", "kanishk", "Deepa"] #string list
>>> print(stunames)
['Aditya', 'Joshi', 'Yogesh', 'kanishk', 'Deepa']
>>> glevel=[1, "Aditya", 24, 94.5, True] #list with different data types
>>> print(glevel)
[1, 'Aditya', 24, 94.5, True]
Accessing List
• accessed using a zero-based index in the square brackets []. start from zero and
increment by one for each item
names=["Aditya", "Joshi", "Mohit", "Rohit"]
print(names[0])
print(names[1])
print(names[2])
print(names[3])

runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
Aditya
Joshi
Mohit
Rohit
A list can contain multiple inner lists as items that can be accessed using
indexes.
data=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10]
print(data[0]) # returns 1
print(data[1]) # returns 2
print(data[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(data[4]) # returns 10
print(data[3][0]) # returns 4
print(data[3][3]) # returns [7, 8, [9]]
print(data[3][3][0]) # returns 7
print(data[3][3][2]) # returns [9]
List class
All the list objects are the objects of the list class in Python. Use the list()
constructor to convert from other sequence types to list
num=[1,2,3,4] runfile('C:/Users/Aditya/
print(type(num)) Desktop/untitled13.py',
mylist=list('BCA4') wdir='C:/Users/Aditya/Desktop'
print(mylist) )
num=list({1:'one',2:'two'}) <class 'list'>
print(num) ['B', 'C', 'A', '4']
num=list((40, 50, 60)) [1, 2]
print(num) [40, 50, 60]
num=list({400, 500, 600}) [400, 600, 500]
print(num)
Iterate through List

A list items can be iterate using the for loop.

for var in list:


print(var)

num=[1,2,3,4]
for var in num:
print(var)

Output:
1
2
3
4
Update list
The list is mutable. You can add new items in the list using the append() or
insert() methods, and update items using indexes.
Course=["BCA", "MCA", "BSC IT"]
print(Course)
Course[0]="MSC IT"
Course[1]="BCA"
Course.append("BSC CS")
print(Course)
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
['BCA', 'MCA', 'BSC IT']
['MSC IT', 'BCA', 'BSC IT', 'BSC CS']
Remove Items
• Use the remove(), pop() methods, or del keyword to delete the list item or the whole list.
print(Course)
del Course[0]# removes item at index 0 ['MSC IT', 'BCA', 'BSC IT', 'BSC CS']
print("After del Course[0]: ", Course) After del Course[0]: ['BCA', 'BSC IT', 'BSC CS']
After Course.remove("BCA"): ['BSC IT', 'BSC CS']
BSC IT
Course.remove("BCA") # removes "BCA" After Course.pop(0): ['BSC CS']
After Course.pop(): []
print('After Course.remove("BCA"): ', Course)
NameError: name 'Course' is not defined

print(Course.pop(0)) # return and removes item at index 0


print("After Course.pop(0): ", Course)

Course.pop() # return removes item at last index


print("After Course.pop(): ", Course)

del Course
print(Course)
Tuples
• Tuple is an immutable collection of elements of different data types. It is
an ordered collection, so it preserves the order of elements in which
they were defined.
• Tuples are defined by enclosing elements in parentheses (), separated
by a comma. tpl=() # empty tuple runfile('C:/Users/Aditya/Desktop/
Declaration: print(tpl) untitled13.py',
names = ('Aditya', 'Neha', 'Shree', wdir='C:/Users/Aditya/Desktop’)
'GEU') # string tuple
print(names) ()
nums = (1, 2, 3, 4, 5) # int tuple ('Aditya', 'Neha', 'Shree', 'GEU')
print(nums) (1, 2, 3, 4, 5)
emp=(1, 'Aditya', True, 30, 240000) (1, 'Aditya', True, 30, 240000)
# heterogeneous data tuple
print(emp)
it is not necessary to enclose the tuple elements in parentheses.

It automatically include elements separated commas without


parentheses
runfile('C:/Users/Aditya/Desktop/
names = 'Aditya', 'Neha', 'Shree', 'GEU' #
string tuple untitled13.py',
print(names) wdir='C:/Users/Aditya/Desktop')
('Aditya', 'Neha', 'Shree', 'GEU')
nums = 1, 2, 3, 4, 5 # int tuple (1, 2, 3, 4, 5)
print(nums) (1, 'Aditya', True, 30, 240000)
emp=1, 'Aditya', True, 30, 240000 #
heterogeneous data tuple
print(emp)
Tuples cannot be declared with a single element unless followed
by a comma.
names = ('Aditya') # considered as string runfile('C:/Users/Aditya/Desktop/
type untitled13.py',
print(names) wdir='C:/Users/Aditya/Desktop')
print(type(names))
Aditya
names = ('Aditya',) # tuple with single <class 'str'>
element ('Aditya',)
print(names) <class 'tuple'>
print(type(names))
Accessing Tuple
Each element in the tuple is accessed by the index in the square
brackets []. An index starts with zero and ends with (number of
elements - 1), as shown below.
names = ('Aditya', 'Neha', 'Shree', 'GEU') runfile('C:/Users/Aditya/Desktop/
print(names[0]) untitled13.py',
print(names[1]) wdir='C:/Users/Aditya/Desktop')
print(names[2]) Aditya
print(names[3]) Neha
Shree
nums = (1, 2, 3, 4, 5) GEU
print(nums[1]) 2
print(nums[3]) 4
• Negative index is also supported for starting element -number of elements to -
1 for last elements
• If the element at the specified index does not exist, then the error “Index Error:
tuple index out of range" will be thrown.
Tuple elements can be unpacked and assigned to variables, as shown below.
However, the number of variables must match with the number of elements in a
tuple; otherwise, an error will be thrown.
names = ('Aditya', 'Neha', runfile('C:/Users/Aditya/
'Shree', 'GEU') Desktop/untitled13.py',
w,x,y,z=names #unpacking wdir='C:/Users/Aditya/Desktop'
tuples )
print(w,x,y,z) Aditya Neha Shree GEU
Update or Delete Tuple Elements
Tuple is Immutable so we cannot modify or delete any elements in tuple trying
to do will result to
TypeError: 'tuple' object does not support item assignment
TypeError: 'tuple' object doesn't support item deletion

Entire tuple is deleted using del keyword


del names

Tuple Class
The underlying type of a tuple is the tuple class. Check the type of a variable
using the type() function.
The tuple() constructor is used to convert any iterable to tuple type.

tpl = tuple('Hello') # converts string to tuple runfile('C:/Users/Aditya/Desktop/


print(tpl) untitled13.py',
tpl = tuple([1,2,3,4,5]) # converts list to tuple wdir='C:/Users/Aditya/Desktop')
print(tpl)
tpl = tuple({1,2,3,4,5}) # converts set to tuple ('H', 'e', 'l', 'l', 'o')
print(tpl) (1, 2, 3, 4, 5)
tpl = tuple({1:"One",2:"Two"}) # converts (1, 2, 3, 4, 5)
dictionary to tuple (1, 2)
print(tpl)
Tuple Operations
• Like string, tuple objects are also a sequence. Hence, the operators used with
strings are also available for the tuple.
Operator Example
The + operator returns a tuple >>> t1=(1,2,3)
containing all the elements of the >>> t2=(4,5,6)
first and the second tuple object. >>> t1+t2 (1, 2, 3, 4, 5, 6)
>>> t2+(7,) (4, 5, 6, 7)

The * operator Concatenates >>> t1=(1,2,3)


multiple copies of the same tuple. >>> t1*4 (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

The [] operator Returns the item at >>> t1=(1,2,3,4,5,6)


the given index. A negative index >>> t1[3] 4
counts the position from the right >>> t1[-2] 5
side.
The [:] operator returns the items in >>> t1=(1,2,3,4,5,6)
the range specified by two index >>> t1[1:3] (2, 3)
operands separated by the : symbol. >>> t1[3:] (4, 5, 6)
If the first operand is omitted, the >>> t1[:3] (1, 2, 3)
range starts from zero. If the second
operand is omitted, the range goes up
to the end of the tuple.

The in operator returns true if an item >>> t1=(1,2,3,4,5,6)


exists in the given tuple. >>> 5 in t1 True
>>> 10 in t1 False
The not in operator returns true if an >>> t1=(1,2,3,4,5,6)
item does not exist in the given tuple. >>> 4 not in t1 False
>>> 10 not in t1 True
Set
• A set is a mutable collection of distinct hashable objects, It is an unordered
collection of objects, meaning it does not record element position or order of
insertion and so cannot access elements using indexes.
• The set is a Python implementation of the set in Mathematics. A set object has
suitable methods to perform mathematical set operations like union,
intersection, difference, etc.
• A set object contains one or more items, not necessarily of the same type,
which are separated by a comma and enclosed in curly brackets {}.
Definition :
oddnums = {1, 3, 5, 7, 9} # set of odd numbers
stu = {1, 'aditya', 10.5, True} # set of different objects
print(oddnums)
print(stu)
A set doesn't store duplicate objects. Even if an object is added more
than once inside the curly brackets, only one copy is held in the set
object. Hence, indexing and slicing operations cannot be done on a
set object.

num={1,2,3,3,3,3,4,4,4,4,4,5,6,7,7,7,8}
print(num)

The order of elements in the set is not necessarily the same as the
order given at the time of assignment. Python optimizes the
structure of a set for performing operations over it, as defined in
mathematics.
Only immutable (and hashable) objects can be a part of a set object.
Numbers (integer, float, as well as complex), strings, and tuple
objects are accepted, but set, list, and dictionary objects are not.
>>> myset = {(10,10), 10, 20} # valid
>>> myset
{(10, 10), 10, 20}

>>> myset = {[10,10], 10, 20} # invalid


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list’

>>> myset = {{10,10}, 10, 20} # invalid


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
set() function is used to create an empty set. Empty curly braces will create an empty
dictionary instead of an empty set.
>>> emp={}
>>> emp
{}
>>> type(emp)
<class 'dict’>

>>> s=set()
>>> type(s)
<class 'set'>
>>> s
set()
set() function also use to convert string, tuple, or dictionary object to a set object
>>> s=set('Hello')
>>> s
{'o', 'l', 'e', 'H’}

>>> s = set((1,2,3,4,5))
>>> s
{1, 2, 3, 4, 5}

>>> d = {1:'One', 2: 'Two'}


>>> s=set(d)
>>> s
{1, 2}
Modify Set Elements
built-in set functions add(), remove() or update() methods is used to modify set
collection.

s = set() # creates an empty set


s.add(10) # add an element
s.add(20)
s.add(30)
print(s)
primeNums = {2, 3, 5, 7}
s.update(primeNums) # update set with another set
print(s)
s.remove(2) # remove an element
print(s)
Set Operations
As mentioned earlier, the set data type in Python implements as the set defined
in mathematics.
Operators |, &, - and ^ perform union, intersection, difference, and symmetric
difference operations, respectively. Each of these operators has a corresponding
method associated with the built-in set class.
Operation Example
Union: Returns a new set with >>> s1={1,2,3,4,5}
elements from both the sets. >>> s2={4,5,6,7,8}
>>> s1|s2 {1, 2, 3, 4, 5, 6, 7, 8}
Operator: | >>> s1={1,2,3,4,5}
Method: set.union() >>> s2={4,5,6,7,8}
>>> s1.union(s2) {1, 2, 3, 4, 5, 6, 7, 8}
>>> s2.union(s1) {1, 2, 3, 4, 5, 6, 7, 8}

Intersection: Returns a new set >>> s1={1,2,3,4,5}


containing elements common to >>> s2={4,5,6,7,8}
both sets. >>> s1&s2 {4, 5}
>>> s2&s1 {4, 5}
Operator: & >>> s1={1,2,3,4,5}
Method: set.intersection() >>> s2={4,5,6,7,8}
>>> s1.intersection(s2) {4, 5}
>>> s2.intersection(s1) {4, 5}
Difference: Returns a set containing elements >>> s1={1,2,3,4,5}
only in the first set, but not in the second set. >>> s2={4,5,6,7,8}
>>> s1-s2 {1, 2, 3}
>>> s2-s1 {8, 6, 7}
Operator: - >>> s1={1,2,3,4,5}
Method: set.difference() >>> s2={4,5,6,7,8}
>>> s1.difference(s2) {1, 2, 3}
>>> s2.difference(s1) {8, 6, 7}

Symmetric Difference: Returns a set >>> s1={1,2,3,4,5}


consisting of elements in both sets, excluding >>> s2={4,5,6,7,8}
>>> s1^s2 {1, 2, 3, 6, 7, 8}
the common elements. >>> s2^s1 {1, 2, 3, 6, 7, 8}
Operator: ^ >>> s1={1,2,3,4,5}
Method: set.symmetric_difference() >>> s2={4,5,6,7,8}
>>> s1.symmetric_difference(s2) {1, 2, 3, 6, 7, 8}
>>> s2.symmetric_difference(s1) {1, 2, 3, 6, 7, 8}
Dictionary

The dictionary is an unordered collection that contains key:value pairs


separated by commas inside curly brackets. Dictionaries are optimized to
retrieve values when the key is known.

Declaration:
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}

Above, roll is a dictionary object which contains key-value pairs inside { }. The
left side of : is a key, and the right side is a value. The key should be unique and
an immutable object. A number, string or tuple can be used as key.
d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} #


tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value

print(d)
print(numNames)
print(decNames)
print(items)
print(romanNums)
a dictionary with a list as a key is not valid, as the list is mutable

dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

Leads to error
But list can be used as value

The dict is the class of all dictionaries, as shown below.


numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
print(type(numNames))
A dictionary can also be created using the dict() constructor method.

num_dict = dict(I='one', II='two', III='three')


print(num_dict)

emptydict = dict()
Print(emptydict)
Accessing Dictionary:
Dictionary is an unordered collection, so a value cannot be
accessed using an index; instead, a key must be specified in
the square brackets
capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals["USA"])
print(capitals["France"])
print(capitals["usa"]) # Error: Key is case-sensitive
print(capitals["Japan"]) # Error: key must exist

Using get() method


capitals.get("USA")
Accessing with for loop

roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}


for key in roll:
print("Key = " + key + ", Value = " + roll[key])
Update dictionary and add new key value pair
roll = {"1":"Aditya", runfile('C:/Users/Aditya/
"2":"Mukul", "3":"Sneha"} Desktop/untitled13.py',
print(roll) wdir='C:/Users/Aditya/Desktop'
roll["1"]="Joshi" )
roll["2"]="Aditya" {'1': 'Aditya', '2': 'Mukul', '3':
roll["3"]="Neha" 'Sneha'}
print(roll) {'1': 'Joshi', '2': 'Aditya', '3':
roll["4"]="Shree" 'Neha'}
print(roll) {'1': 'Joshi', '2': 'Aditya', '3':
'Neha', '4': 'Shree'}
Deleting Values from a Dictionary
Use the del keyword, pop(), or popitem() methods to delete a pair from a
dictionary or the dictionary object itself. To delete a pair, use its key as a
parameter. To delete a dictionary object, use its name.

roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}


print(roll)
del roll["1"]
print(roll)

runfile('C:/Users/Aditya/Desktop/untitled13.py',
wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
{'2': 'Mukul', '3': 'Sneha'}
dict.pop(): The dict.pop() method removes the key and returns its value. If a key
does not exist in the dictionary, then returns the default value if specified, else
throws a KeyError.

roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}


print(roll)
delvalue=roll.pop("3")
print("deleted value is : ",delvalue)
print(roll)

runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
deleted value is : Sneha
{'1': 'Aditya', '2': 'Mukul'}
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}
print(roll)
delvalue=roll.pop("5","Key not found")
print("deleted value is : ",delvalue)
print(roll)

runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
deleted value is : Key not found
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
dict.popitem(): The dict.popitem() method removes and returns a tuple of (key, value) pair from
the dictionary. Pairs are returned in Last In First Out (LIFO) order.
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}
print(roll)
print(roll.popitem())
print(roll.popitem())
print(roll.popitem())
print(roll)
#print(roll.popitem()) #KeyError: 'popitem(): dictionary is empty'

runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
('3', 'Sneha')
('2', 'Mukul')
('1', 'Aditya')
{}
Retrieve Dictionary Keys and Values
The keys() and values() methods return a view objects
containing keys and values respectively.
d1 = {'name': 'Aditya', 'age': 21, 'marks': 80, 'course': 'BCA'}
print(d1.keys())
print(d1.values())

runfile('C:/Users/Aditya/Desktop/untitled13.py',
wdir='C:/Users/Aditya/Desktop')
dict_keys(['name', 'age', 'marks', 'course'])
dict_values(['Aditya', 21, 80, 'BCA'])
Check dictionary keys
You may check it with in and not in keywords

d1 = {'name': 'Aditya', 'age': 21, 'marks': 80, 'course': 'BCA'}


print('name' in d1) # returns True

if ('name' in d1):
print("Key found")
else:
print("Key not found")
Multi-dimensional Dictionary

d1={"name":"Aditya","age":25, "rollno":1}
d2={"name":"Vaibhav","age":23, "rollno":50}
d3={"name":"Shanku", "age":20, "rollno":30}
stu={1:d1,2:d2,3:d3}
print(stu)

The stu object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as
values to keys 1, 2, and 3, respectively. The stu[1] returns d1.
print(stu[1])
{'name': 'Aditya', 'age': 25, 'rollno': 1}
print(stu[1]["name"])
Aditya

You might also like