100% found this document useful (1 vote)
125 views

Chapter 1 Python Revision Tour

The document provides an introduction and overview of Python programming concepts including tokens, data types, statements, and control flow. It discusses that Python is an interpreted, general purpose programming language invented by Guido Van Rossum in 1991. The smallest unit in a Python program is called a token, which can be keywords, identifiers, literals, operators, punctuators, or inbuilt functions. Python code is organized using blocks and indentation. Control flow in Python includes sequence, selection (if/elif/else), and iteration (for loops).

Uploaded by

ytmoksh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
125 views

Chapter 1 Python Revision Tour

The document provides an introduction and overview of Python programming concepts including tokens, data types, statements, and control flow. It discusses that Python is an interpreted, general purpose programming language invented by Guido Van Rossum in 1991. The smallest unit in a Python program is called a token, which can be keywords, identifiers, literals, operators, punctuators, or inbuilt functions. Python code is organized using blocks and indentation. Control flow in Python includes sequence, selection (if/elif/else), and iteration (for loops).

Uploaded by

ytmoksh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit 1 – Computational Thinking and Programming

Chapter 1 – Python Revision Tour


Introduction
✔ Python is a general purpose programming language.
✔ It can be used for application development, machine learning, artificial
intelligence (AI), data visualization, automation, web development etc.
✔ It was developed by Guido Van Rossum in 1991.
✔ It supports procedural (functional) and OOPs features
✔ It is large number of libraries like Pygame, Matplotlib, Tkinter, Numpy, Scipy
etc.
✔ It is an interpreted language.
✔ Python files have extension .py.
✔ We are currently using 3rd version of Python i.e. 3.x

Python Character Set


It is a set of all the characters/symbols that can be recognized or used by python
Interpreter. It includes
Alphabets – A to Z and a to z
Digits/Number – 0 to 9
Symbols - +, -, *, %, #, ! etc
White spaces – Space bar, Enter Key, Tab etc.
Note – It supports all ASCII and Unicode symbols.

Tokens (Lexical Unit)


It is the smallest unit that can be uniquely identified by python Interpreter.
These are Keywords, Identifier,
Punctuates, Literals, Operators and Inbuilt.

Structure of Python Program

# This is comment
a=10
def hello():
pass
for x in range(1,6):
print(x)
In the above program
➢ a, x, and hello are Identifier (Variable)
➢ = and in are Operators
➢ 10, 1 and 6 are Literals
➢ def, for and pass are Keywords
➢ : and ( ) are Punctuaters
➢ print and range are python Inbuilt functions

Questions
➔ Who invented Python and when?
➔ Smallest unit in a python program is known as _______
➔ What is the role of interpreter.
➔ Python files ends with ______ extension.
➔ What is the use of comments in python.

Tokens – (Lexical Units)


Token - Smallest Unit in a Program.
It has 6 main parts i.e. Keywords, Identifiers, Literals,
Operators, Punctuaters and Inbuilts.

Keywords
Also known as Reserved words.
These are pre-defined words in python programming reserved for specific
work or task.
Example – if, else, for, while, continue, break, import, def, True, False,
None etc.

Identifies
These are the names given by the programmer.
Identifier can be names of variables, functions, classes etc.
Rules for Declaring Identifiers
✔ Keywords are not allowed.
✔ We can only use letters, digits or underscore.
✔ It cannot start with a digit.
✔ No spaces are allowed.
✔ Identifiers are case sensitive.

Punctuators
Also known as Separators.
These are special symbols used for organizing python code.
Example - “ , #, \, [ ], { }, = etc
Questions
➔What is the smallest unit in Python?
➔Find the valid Identifier
1) while
2) 12hello
3) _today
4) for
➔what are seperators?
➔What is “true” Identifier or Keyword?

Literals
These are constant values.
Types
Numeric Literals
Integer
Decimal (34) Octal (0o17) Binary (0b101)
Hexadecimal (0x45)
Float
(14.2), (-18.34)
Complex
(a+bj) –
a = (5+4j) (a.real)(a.imge)

Boolean Literals
This constant only includes True and False.

Sequences
Sequences supports indexing this includes String, list and Tuple.

String Literals
Single line literals
It is enclosed within single quotes. ‘Hello 123’
Multi line literals
It is enclosed within triple quotes.
‘ ‘ ‘ hello world 123
we are learning python’ ’ ’
or
“hello ------\
today”
Escape Sequence - \n, \t and \a

List – [2,4,5,6, “Hello”]


Tuple – (5, “Hello”, 13.45)
Dictionary – {1: “Karan”, 5: “Raj”}
Special Literals – None

Sets – {34,45,12,44}

Inbuilt
Python inbuilt basically includes python built in functions like print(),
input(), int(), float() etc. These are used to create python statements.
Basic Inbuilt Functions
print() - Print data on screen.
input() - Takes input from user in string form.
id () - It returns unique id (physical address of an object)
identifier.
type () - Return type of data value.
int () - Converts data to integer form.
float() - Converts data to floating point form.
str() - Converts data to string sequence.
list() - Converts data to list sequence.
tuple() - Converts data to tuple sequence.
eval() - It evaluates and expression and gives a specific result.

Questions
✔ Literals are also known as ______ values.
✔ Name the literal (3).
✔ What type of argument is “end”
✔ What is the default data type returned by input().

Operators
A Symbol or word that operates on operands and perform specific task.
These can be operated in Binary or Unary form.

Unary
(-, ~ and not)
Binary

Assignment - (= and shorthand with arithmetic like +=)


Arithmetic - (+ - / * // % **)
Relational/Comparison - (< <= > >= != ==)
Logical – (not and or)
Membership – (in, not in)
Identity – (is, is not)
Shift - (<< left shift) and (>> right shift)
Bitwise - (& | ^)

Operator Precedence (priority)


Top to Bottom
()
**
~x
+x, -x
* / // %
+-
&
^
|
< <= > >= != == is is not
not
and
or

Questions
✔ What is difference between is and == operator
✔ What are operands?
✔ What is the use of memebership operator.
✔ Find the odd one from the following
==
<
>
and

Basic Python Structure


#This is comment
‘ ‘ ‘ This is multi line
comment in python’ ’ ’
def today():
print(“Hello”)
print(“Python”)
a=10
b=3+45+a
print(a,b)
if a==b:
print(“Python”)
else:
print(“Bye”)
today()

Function (Sub – Program)


Group of statements that can be reused again and again by calling its
name.
Types – Inbuilt, Inside module and user defined.

Variable in Python
These are named memory location used to store data values.
Creating Variable
Variable in python is declared when we first assign value to it.
Examples
a= 10 #integer
b=78.45 #Floating point
c=23+56j #Complex
p= “Hello” #String
c=[“hello”, 34, 56.65] #list
d= (45,67,78) or 45,67,78 #Tuple
e= {1: “hello” ,2: “Today”}#Dictionary
s={45,56,78,80} #Sets

Expressions
These are the combination of constant variable and operators.
Comments
These are non executable additional statements in python programming
used for clarifying python source code.
Types – Single line or Inline or multi line.

Questions
✔ What is None in Python?
✔ What is the use of comments?
✔ Write expression for declaring multiple variables in python.
✔ Justify the statement python is implicit langauge.

Data Types
Datatype is type of Data. It can be numeric, string, float, boolean
etc.
Types of Data Types in Python
1. Numeric
1.1. Integer
a) Decimal (67)
b) Binary (0b1010)
c) Octal (0o357)
d) Hexadecimal (0x 2A)
1.2. Floating Point (45.565)
1.3. Complex (45+44b)
2. String – Single line, Multi line and Escape sequence.
3. Python Collection – List and Tuple
4. Mapping – Dictionary
5. Sets
6. Special Type – None (or non type)

Ordered Type (Sequencing Type)


String, list and Tuple (uses Indexing)
Unordered Type
Dictionary(Mapping) and Sets

Mutable and Immutable Data Types


Mutable Types
In the same address new value can be stored. List and Dictionary.
Example
a=5
print(id(a)) #id or address
a=9
print(id(a)) #Different id or address

Immutable Types
In same address new value cannot be saved. (Value change will also
change address or id). Integer, float, boolean, string and tuple.
Example
a=5
print(id(a)) #id or address
a=9
print(id(a)) #Same id or address

Typing Casting (Conversion)


Implicit Type Casting/Conversion
It is done by Python Interpreter itself like 2.4+3
Explicit Type Casting/Conversion
It is done by programmer by using inbuilt functions like
int(), float(), str(), list(), tuple() etc.

Question
✔ Name any two ordered data types in Python?
✔ What is null data type?
✔ What is difference between Mutable and Immutable data type?
✔ What is use of int()?
✔ State true or false (Python is Implicitly typed)

Python Statements
These are the set of instructions which are written using python
programming rules and executed on python interpreter.
Programming Statements
Set of instructions that are written according programming rules.

Block and Indentation


Group of statements depends upon another statement to execute. We use
colon(:) to create a block.
Types of Statements
Empty Statements
Also known as null statement.
It is given by Pass keyword.

Simple/Single line Statements


These are simple statements like
a=10
print(“Hello”,a)

Compound Statement
These are group of statements that acts as a single unit.
It includes a header part followed by a colon (:).
Syntax
header :
statement
if condition :
statement(s)
for variable in sequence:
statement(s)

Flow of Control
It defines order of execution.
Sequence
Executed line by line.
Selection/Conditional/Branching
Executed based on a condition test. (if elif else)
Iterative/Looping
Executed until a condition is True. (for and while)
Jumping
When we jump at different position within a program.

Questions
✔ What is Empty Statement.
✔ What are compound statements. Give two example?
✔ What is use of colon(:)?
✔ What is flow of execution, give an example of conditional statement.
Selection/Conditional/Branching
Executed based on a condition test. (if elif else)

Simple if If else If elif else Nested if


if condition: if condition: if condition 1: if condition:
statement(s) Statement(s) statement(s) if condition:
else: elif condition 2: if condition
Statement(s) statement(s) else:
elif condition n:
statement(s)
else:
statement(s)

Simple if
if True:
print("Hi") Output
if 10:
print("Hi")
Hi
a=90 Hi
if a>10: Hi
print("Hi")
if else
if False:
print("Hi")
else:
print("Bye")

a=100
if a!=100:
print("It is 100")
else: Output
print("It is not 100") Bye
a=100 It is not 100
if a==100: It is 100
print("It is 100")
else:
print("It is not 100")

if elif else
a=int(input("Enter a Number : "))
if a==10:
print("Number is exactly 10")
elif a>10 and a<=40:
print("Number is between 10 and 40")
elif a>40 and a<100:
print("Number is between 50 and 100")
else:
print(" Number is greator than 99 ")
Output
Enter a Number : 90
Number is between 50 and 100

Nested if
a=9
if True: Output
if a<10:
if False:
Hello
print("Hi")
else:
print("Hello")
else:
print("Outer else")

Questions
✔ What is difference between if and else?
✔ What is difference between nested if and if else.
✔ Find the output
a=3
if a:
print(print("Hello"))

Iterative Statements(Loops)
These statements are used to repeat statement(s) until a condition is True.
Types for and while
There are four mandatory parts of Iterative/Looping Statements.
1. Start/Initialization
2. End/Destination
3. Steps (Increment or Decrement)
4. Body of the loop/Statements to be repeated.

For loop
Syntax of for loop
for variable in range(values)/Sequence:
statement(s)
Sequence can be – String list tuple and dictionary.
range() - It is used to create a sequence.
Examples
String
for x in “Hello”:
print(x,end= “-”)
Output – H-e-l-l-o

List
for y in [2,4,45]:
print(y)
Output
2
4
45

range(1,10,2) – 1 3 5 7
range(5,1,-1) – 5 4 3 2
range(5,-3,-1) – 5, 4, 3, 2, 1, 0, -1, -2

While loop
Syntax of while loop
a=1 #Initialization (Start)
while a<=5: #Conditional test (end)
print(a) #Body of loop statement
a=a+1 #update (Increment or decrement)

Questions
✔ What is the default starting value of range()?
✔ Why steps are mandatory part of while loop.
✔ Find the output
for x in [3,4,5]:
print(x**2)
✔ Print all two digits number using while loop.

Nesting of Looping
When one is inside the body of another loop it is known as nesting of loop.
Example: Output
for x in range(1,6):
for y in range(1,6):
12345
print(y, end= “ ”) 12345
print() 12345
12345
12345
x=1
while x<=5:
y=1
while y<=5:
print(y, end= “ ”)
y=y+1
print()
x=x+1

Jumping Statements
Break Statement
It terminates the current loop and transfers the controls to the next python
statement.
Example
for x in range(10):
print(x, end = “ ”)
if x==5:
break
Output: 0 1 2 3 4

Continue Statement
It skips the statement(s) followed by continue keyword and transfers
control to the top of the loop.
Example
for x in range(10):
if x==3:
continue
print(“Hello”, x, end= “ ”)
Output
012456789

Questions
✔ What is the use of nesting?
✔ What is difference between break and continue
✔ __________ statement skips the upcoming code.
✔ Can we use break and continue within same loop.
String
It is a sequence of ASCII or Unicode characters enclosed within single
(‘hello’) or double (“hello world”) or triple (‘ ‘ ‘ hello world’ ’ ’).
It is Immutable (Non Changeable)
Note:- input() function is used to input string from user.

String Indexing
String supports both positive and negative indexing.
Example – “HELLO 123@”

Positive Indexing
0 1 2 3 4 5 6 7 8 9
H E L L 0 1 2 3 @
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Negative Indexing
Accessing elements of String (Hello)
1. Accessing Single element through index number
Example –
print(a[1]) or print(a[-4])
Output – e
2. Using loop
for x in “Hello”:
print(x, end= “ ”)
Output
Hello

String Slicing (Sub String) – Part of a string


String name [start : end : steps]
Examples – “Hello 123 Hi”
print(a[:]) or print(a[0:13]) – Hello 123 Hi
print(a[2:] - llo 123 Hi
print(a[2:8:2] – l o 1
String Operators
Membership Operator (in, not in)
Example – print(“T” in “Today”) – True
Concatenation Operator (+)
Example – print(“Today” + “Hello”) – TodayHello
Replication Operator (*)
Example – print(“Hi”*3) – HiHiHi
Relational Operators (<, <=, >, >=, !=, ==)
Example – print(‘abc’ > ‘Abc’) – True
Note - It compares ASCII value and index number.
Functions used for comparision
ord(‘A) – 65
char(97) – a

String Functions
str() - Converts from other sequence to string.
a=[1,4,6]
b=str(a)
len() - Returns length of string. (Elements in String)
a=”Hello”
print(len(a)) – 5
capitalize() - Capitalize a string.
a= “hello”
print(A.capitalize()) - Hello
upper() and lower() - Converts to uppercase and lowercase.
a= ‘hello WORLD’
print(a.upper()) = HELLO WORLD
print(a.lower()) - hello world
count() - Counts a sub string in a main string.
a= “Today is great”
print(a.count(‘a’)) – 2
replace() - Replace old string with new one.
a= “Hello we are learning’
print(a.replace(‘We’, ‘it’) – Hello it are learning.
Strip() - It strips out the unwanted spaces from a string.
a=“ Hello ”
print(a.strip()) - Hello
we can also use lstrip(), rstrip() for string from left or right.
Data Checking Functions
Syntax – String.function()
isalnum() - Checks for alphabets or number.
isdigit() - Checks digits.
isspace() - Checks for space.
isalpha() - Checks for alphabets.
islower() - Checks for lowercase letters.
isupper() - Check for uppercase letters.

Questions
✔ What is the role of Escape sequence \n
✔ Write a program to find total number of vowels in the following
string.
“This is python programming”
✔ Name the function used for converting other sequences to string.
✔ Find the output
a = “This is a sequence”
print(a[2:12:2])

List
It is a datatype (Inbuilt Data Structure) in which we can store different data
values in an ordered sequence. (Indexing)
It is mutable (Changeable).
Examples
a=[] #Empty List
a= [1,4,8] #Integer List
a = [2, 8, [14, “Hello”], 18] #Nested List
a= [4, 8, 6, 9, #Long List
16, 1, 17,
18, 13]
Note – list() is used to convert other sequence to list. It is also used to
create a copy (different address).
a = “Hello”
print(list(a)) = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
a={1:4, 8:14, 5:58}
print(list(a)) – [1, 8, 5]
print(list(a.values()) - [4, 14, 58]

List data can be changed


a = [2, 8, [14, “Hello”], 18]
a[1]=100
print(a) → a = [2, 100 , [14, “Hello”], 18]

List Indexing
Supports both positive and negative indexing.
Example
a=[14, 8, “Hello”, [2,4], 81, 41]

Positive Indexing
0 1 2 3 4 5
14 8 Hello [2,4] 81 41
-6 -5 -4 -3 -2 -1
Negative Indexing

Accessing List Elements


a=[14, 8, “Hello”, [2,4], 81, 41]
Input Output
print(a) [14, 8, “Hello”, [2,4], 81, 41]
print(a[1]) 8
print(a[2][1] H
print(a[-3][-2]) 2

List Slicing
a=[14, 8, “Hello”, [2,4], 81, 41]
Input Output
print(a[:]) [14, 8, “Hello”, [2,4], 81, 41]
print(a[2:]) [“Hello”, [2,4], 81, 41]
print(a[0:5:2]) [14, “Hello”, 81]

Accessing Elements using loop


a=[14, 8, “Hello”, [2,4], 81, 41]
for x in a:
print(x, end = “ ”)
Output: 14 8 “Hello” [2,4] 81 41

List Operators
1. Membership Operator (in, not in)
print(14 in [12, 14, 18]) → True
2. Concatenation/Addition ( + )
print([3,2,4] + [18, 19]) → [3, 2, 4, 18, 19]
3. Replication Operator ( * )
print([2,4,6]*2) → [2,4,6,2,4,6]
4. Relational/Comparison Operators (<, <=, >, >=, !=, ==)
print([2,4,6]==[4,8,6]) → False

List Functions
list()
Converts all other sequences to list. Also make a real copy.
print(list(“Hello”)) → [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
len()
Returns length of string (Elements of list)
print(len(14,2,8, ‘Hello’)) → 4
append()
It is used to add new element at the end of list.
a=[2,4,6]
a.append(“Hello”)
print(a) → [2,4,6, “Hello”]
insert()
It is used to add element at specific index.
a=[1,2,5]
a.insert(1,100)
print(a) → [1, 100, 2, 5]
extend()
It is used to add new list to existing list.
a=[2,8,7]
a.extend(2,4]) → [2, 8, 7, 2, 4]
pop()
It deletes (popes out) last element from list. It can also delete element
based on Index number.
a=[2,8,7,9]
a.pop()
print(a) → [2,8,7]
a.pop(1)
print(a) → [2,7]
clear()
It clear the list element and makes a empty list.
a=[4, 2, 7]
a.clear()
print(a) →[]
remove()
It removes given first element from the list.
a=[4,2,7,4,5]
a.remove(4)
print(a) → [2,7,4,5]
index()
It returns first index of an element.
a=[4,7,13]
print(a.index(7)) → 1
reverse()
It reverses list elements.
a=[4,13, “Hello”)
a.reverse()
print(a) → [“Hello”, 13, 4]
sort()
Sort a list and works only with same data types.
a=[4, 9, 1, 7 , 2]
a.sort()
print(a) → [1, 2, 4, 7, 9]
min(), max() and sum()
a=1, 2, 8, 7]
b=["Karan","Suraj", "Vijay","Riya"]
print(max(b)) → Vijay
print(min(a)) →1
print(sum(a)) → 23
Note: - del keyword can also be used for deleting data with variable. For
example del a, b, c

Questions
✔ What is list data type, what is difference between string and list.
✔ Find the output
a=[3,5,[5,6],6]
print(a[2][-1])
✔ Find the output
a=[3,5,9]
a.append(“Hello”)
a.pop(2)
a.append(90)
print(a)
✔ What is the difference between insert and extend.

Tuple
It is a datatype used to store different data values in an ordered sequence.
It is Immutable (Non Changeable).
Examples
a = 2, 4 #Tuple without ( )
a= (1,4,8) #Integer Tuple
a =(2, 8, [14, “Hello”], 18) #Nested Tuple
a= (4, 8, 6, 9, #Long Tuple
16, 1, 17,
18, 13)
Note – tuple() is used to convert other sequence to Tuple.
a = “Hello”
print(tuple(a)) = (‘H’, ‘e’, ‘l’, ‘l’, ‘o’])
a={1:4, 8:14, 5:58}
print(tuple(a)) – (1, 8, 5)
print(tuple(a.values()) - (4, 14, 58)

Tuple Indexing
Supports both positive and negative indexing.
Example
a=(4, 8, “Hello”, [2,4], 81, 41)

Positive Indexing
0 1 2 3 4 5
14 8 Hello [2,4] 81 41
-6 -5 -4 -3 -2 -1
Negative Indexing

Accessing Tuple Elements


a=(14, 8, “Hello”, [2,4], 81, 41)
Input Output
print(a) (14, 8, “Hello”, [2,4], 81, 41)
print(a[1]) 8
print(a[2][1] H
print(a[-3][-2]) 2

Tuple Slicing
a=(14, 8, “Hello”, [2,4], 81, 41)
Input Output
print(a[:]) (14, 8, “Hello”, [2,4], 81, 41)
print(a[2:]) (“Hello”, [2,4], 81, 41)
print(a[0:5:2]) (14, “Hello”, 81)

Accessing Elements using loop


a=(14, 8, “Hello”, [2,4], 81, 41)
for x in a:
print(x, end = “ ”)
Output: 14 8 “Hello” [2,4] 81 41

Tuple Operators
1. Membership Operator (in, not in)
print(14 in (12, 14, 18)) → True
2. Concatenation/Addition ( + )
print((3,2,4) + (18, 19)) → (3, 2, 4, 18, 19)
3. Replication Operator ( * )
print((2,4,6)*2) → (2,4,6,2,4,6)
4. Relational/Comparison Operators (<, <=, >, >=, !=, ==)
print((2,4,6)==(4,8,6)) → False

Packing and Unpacking in Tuple


a=4,6,7, “Hello” # Packing
p, q, r, s = a # Unpacking
print(a) → (4, 6, 7, “Hello”)
print(p, q, r, s) → 4, 6, 7, “Hello”
Note: len(), index(), min(), max(), sum(), count() and del keyword is same
like list in Tuples.

Questions
✔ What is tuple data type, what is difference between list and tuple.
✔ Find the output
a=(3,5,8,[5,6,4],6]
print(a[-2][-1])
✔ Give an example of unpacking in tuple
✔ What is the difference between mutable and immutable data types.
Dictionary
It is a data type that is used to store different data values in Key:Value
format.
It is mutable (Changeable).

Syntax
variable = {Key:Value, Key:value, _ _ _ _ _ }
Keys can be Immutable type only – Integer, Float, String and Tuple.
Values can be of any data type.

Example
a = {‘Hello’:14, 18:(8, ‘Today’)}

Accessing Keys and Values


a = {‘Hello’:14, 18:(8, ‘Today’)}
print(a) → {‘Hello’:14, 18:(8, ‘Today’)}
print(a.keys()) → dict_keys ([‘Hello’,18])
print(a.values()) → dict_values([14, (8, ‘Today’)])
print(a.items()) → dict_items ([(‘Hello’,14),(18, (8, ‘Today’))])

Using loop
for x in a or a.keys():
print(x)
Output
Hello
18

for x in a.values():
print(x)
Output
14
(8, ‘Today’)
for x in a.items():
print(x)
Output
(‘Hello’,14)
(18, (8, ‘Today’))

Dictionary Operator
Membership Operators
a = { 1:20, 2:80, 4: ‘Hello’ }
print(2 in a) → True
Note: It only checks for keys.
For values
a = { 1:20, 2:80, 4: ‘Hello’ }
print(80 in a.values()) → True

Dictionary Functions
len()
Returns total number of key:value pair in dictionary.
a={1:14, 2:18}
print(len(a)) →2

pop()
Pops out a pair, based on key.
a={1:14, 2:18}
a.pop(1)
print(a) → {2:18}

clear()
Clears the dictionary elements.
a={1:14, 2:18}
a.clear()
print(a) →{}

update()
It is used to add new dictionary to existing dictionary.
a={1:14, 2:18}
b={5:28}
a.update(b)
print(a) → {1:14, 2:18, 5:28}
Note:- To completely delete dictionary data with variable we can use
del keyword.

Converting other sequences to Dictionaries


zip() function/method
k=(2,3,4,5,6)
v=(20,30,40,50,60)
d=dict(zip(k,v))
print(d)
Output
{2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

enumerate() function/method
k=(2,3,4,5,6)
v=(20,30,40,50,60)
d=dict(enumerate(v))
print(d)
Output
{0: 20, 1: 30, 2: 40, 3: 50, 4: 60}

Using tuples
k=[(2,3),(4,5),(6,7)]
d=dict(k)
print(d)
Output
{2: 3, 4: 5, 6: 7}

Using loop
a=[2,3,4,5,6]
d={x:x**3 for x in a}
print(d)
Output
{2: 8, 3: 27, 4: 64, 5: 125, 6: 216}

Questions
✔ Write any two applications of Dictionary data type.
✔ Given two list [3,4,5] and [“Karan”, “Diya”, “Suraj”] create a new
dictionary in key value form.
✔ Explain the working of pop() function
✔ What is the use of items().

You might also like