0% found this document useful (0 votes)
4 views

AY2022_Python4_Gr8 (2)

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

AY2022_Python4_Gr8 (2)

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

PYTHON - Dictionaries, Tuples, and Functions

In grades 5, 6 and 7, we have learned the basics of python- sequential, conditional, loops and builtin
functions. In grade 7 we learned Python Iterations, Lists, Searching and Sorting. In this unit, you will
revisit - Lists, Searching and Sorting and you will get introduced to Tuples, Dictionaries, Functions,
Parameters, and Arguments in Python.

Collections in python are basically container data types, namely lists, tuples, dictionaries. Each of these
have different characteristics. We will learn the usage of these collections in this unit.

A. Quick Recap- LISTS


Lists are the simplest data structure in Python and are used to store a list of values. Lists are a
collection of items (strings, integers or even other lists). Each item in a list has an assigned index value,
the first index in a Python list is always 0. Lists are enclosed in square brackets [ ], each item is
separated by a comma. Unlike strings, lists are mutable, which means they can be changed.
A.1 Creating Lists
(a) Lists are created using a comma-separated list of values surrounded by [ ].

(b) Using list() and range() function.

(c) Accepting user-defined list using for loop and eval().

A.2 Accessing Lists


We use square brackets to input the index of the element that we want to see. To access the
5th element we use position 6 off the list.

1
A.3 Replace List Elements
We can use square brackets along with the index number ro replace a certain value in list.
In order to replace one element with another, we can directly assign the new element to that
index.

A.4 Summary of List functions

Function Description Program

append() Add new elements to a


list.

insert() Insert a value in the


specified position.

pop() Delete an item at an index.

remove() Remove an element


without knowing the
position it is at.

sort() To sort the items of a list.

reverse() Reverse the items of a list.

len(s) Gives the length of the list.


(This is a builtin
function)

2
A.5 Operators used in List manipulation
(a) + operator is known as the concatenation operator instead of addition when used with lists.

(b) * operator is known as a replication operator instead of multiplication when used with lists.

B. DICTIONARIES
A dictionary also stores data, like a list. In a list, an element is stored at an index. Unlike a list, in a
dictionary, the equivalent of an index is a key. There is no sequence or order to the keys.
A dictionary can store any number of Python objects. Dictionaries consist of pairs of data: the key and
its corresponding value. These pairs are also known as Items. We can refer to a dictionary as a
mapping between a set of indices (which are called keys) and a set of values. Each key maps a value.
The association of key and a value is called a key-value pair.

The general syntax of a dictionary is as follows:

dict_name={key1:value1, key2:value2, key3:value3….}

B.1 Creating a Dictionary


Each key is separated from its value by a colon(:), the items are separated by commas and the whole
thing is enclosed in curly braces({ }). An empty dictionary without any items is written like this { }.
Keys are unique in a dictionary while the values need not be.

Program Ex 1 - Write a python program to create a dictionary that maps from numbers to number
names, keys are integer data type and values are strings.

We can also create a dictionary with keyword arguments and type constructor, as long as keys are all
strings.

3
Program Ex 2: Write a python program to create a dictionary that has details (name, age, pay, job) of
two employees.
Note - The keys are all strings

We can also fill the dictionary one pair at a time.


Program Ex 3: Write a python program to create an empty dictionary for an employee and add
employee details (name, age, pay, job)

Output:

B.2 Characteristics of Python Dictionaries


1. Dictionaries are Unordered
2. Dictionary keys are Case Sensitive
3. A Duplicate key cannot exist, if we try to add another value to an already existing key, then the
value gets overwritten
4. Keys must be strings or numbers

Dictionaries are Unordered


Dictionary elements(key-value pairs) will stay unordered even when displayed in Python 3. It is possible
that the key-value pairs are displayed in different orders every time we open Python and run the code
snippet.

Output -

Dictionary Keys are Case Sensitive


Keys with the same name but different cases are treated as different keys in python.

4
Output

A duplicate key cannot exist


When duplicate keys are encountered in a dictionary while running the python program, the last value
assigned to the key will be taken up as the final value.

Output:
In the example above the value for the key - ”Sony” is replaced by the new one.

Keys Must be Strings or Numbers


Values can be any type of object, but keys must be Strings or Numbers (immutable 1). This means keys
could be integers, strings, or tuples, but not lists because lists are mutable. Look at the simple example
below.

Output

B.3 Accessing Values in a Dictionary


To access dictionary elements, square brackets along with the keys are used to obtain its value.
Program Ex 4: Write a program to create a dictionary with the following key-value pairs 1=One, 2= Two,
3=Three, 4=Four, 5=Five. Then print the value for keys 4 and 5.

1 Mutability concept in Python will not be dealt with at this grade level.
5
Output:

Note : When you attempt to access the value of a key that is not a part of the dictionary, we will get an
error. Look at the example below.

Output

B.4 Updating a dictionary


A dictionary can be updated in these ways:
(i) When an existing value needs to be changed
(ii) When a new key-value pair needs to be added to the dictionary
(iii) When a key-value pair needs to be removed from the dictionary

Program Ex 5.1: Write a python program to update an existing phonebook dictionary. The user enters
the name whose number is to be modified, if the name is present then the number is updated, else a
message “Name not found “ is displayed.

Output 1: Name exists in dictionary

6
Output 2: Name doesn’t exist in dictionary

Program Ex 5.2: Write a python program to update an existing phonebook dictionary. The user adds a
new name and phone number to the existing dictionary.

Output

Program Ex 5.3: Write a python program to delete an item in an existing dictionary.

Output: If the name exists in dictionary

Output: If the name doesn’t exist dictionary

Program Ex 5.4: Write a program to delete the entire dictionary

7
Output:

B.5 BUILT-IN DICTIONARY FUNCTIONS


Python includes the following dictionary functions. For all these examples, let’s use the dictionary
below:
employeeId1={"Ria":3478, "Tom":8962, "Megha":2576, "Samuel":4231}
employeeId2={“Kevin”:5678, “Asim”:4126, “Hera”:7632}

General Built-in Python Functions

Sl.No Function Description Example


.

1 len(dict) Gives the total length of


the dictionary. This
would be equal to the
number of items in the
dictionary.

2 str(dict) Produces a printable


string representation of a
dictionary

3 type(variable) Returns the type of the


passed variable. If
passed variable is a
dictionary, then it would
return a dictionary type.

Python Dictionary Methods

8
Sl.No Method Description Example

1 dict.clear() Removes all elements of


dictionary dict

2 Returns list of dictionary


dict.keys() dict's keys

3 Adds dictionary dict2's key-


dict.update(dict2) values pairs to dict

4 Returns list of dictionary


dict.values() dict's values

Practice Programs
Program 1 - Write a python program to input ‘n’ names and phone numbers to store it in a dictionary
and to input any name and to print the phone number of that particular name.

Output

9
Program 2 - Write a program to input ‘n’ employee numbers and names and store them in a dictionary.
Display dictionaries employee’s names(key) and numbers(values) together.

Output:

B.6 EXERCISES:
1. What is a dictionary? Give the syntax of a dictionary in python.
2. Differentiate between a python list and a dictionary.
3. Write a python program to input any 5 years and population records of a city and print it on the
screen.
4. Write a python program to input ‘n’ number of subjects and name of head of department and
display all information.
5. Predict the output for the following codes.
A={10:1000, 20:2000, 30:3000, 40:4000, 50:5000}
print(A.items())
print(A.keys())
print(A.values())
6. Write a program to create a customer list with their name and phone number and delete any
customer using his/her phone number.
7. Find the errors from the following code:
#program to create a dictionary with employee name and number
#number of employees are entered by the user
c=dict()
n=input("Enter the total number of employees")

10
i=1
while i<n
a=input("Enterthe name of the employee")
b=input("Enter employee number")
c[a]=b
i=i+1
print(c)
8. Write the output of the following codes
A = {10:1000,20:2000,30:3000,40:4000,50:5000}

Code Output

print(A.items())

print(A.keys())

print(A.values())

print(len(A))

C. TUPLES
A tuple is a sequence of values, which can be of any type and they are indexed by an integer. Tuples
are similar to a list, but, unlike a list, we cannot change the elements of a tuple. Even if one element
has to be changed, we need to create the tuple again, with the changed element. The index value of
tuple starts from 0.
Another difference between a list and a tuple is that lists are declared using square brackets while
tuples are declared using parentheses.

C.1 TUPLE CREATION


A tuple consists of a number of elements separated by commas. For example:

11
Output -

But in the output, all tuples are printed with parentheses.


1. To create a tuple with a single element, we have to use a final comma. Just the value within the
parentheses is not a tuple. The element of the tuple can be of any data type.

2. The empty tuple is written as two parentheses containing nothing. () represents an empty tuple
whereas (,) will give an error.
Look at the example program below:

Program Output

Creating tuple using built-in function:


Another way of creating a tuple is using the built-in function tuple().
A tuple() takes a sequence such as a list as an argument and then makes this sequence into a tuple.
So, in terms of use, it is not effective. Look at the example below:

Program Ex 1: Write a python program to create an empty tuple using the built-in function.

12
C.2 TUPLE INSERTION
1.Using “+” operator
We can add new elements to a tuple using + operator, look at the example below.

Output -
Program Ex 2: Write a python program to input ‘n’ numbers and store it in a tuple.

Output -

2. Add tuple elements by converting it into a list


We can add new elements to a tuple using a list. For that, we have to convert the tuple into a list first
and then use append() function to add new elements to the list. After completing the append, convert
the list back into a tuple.
Program Ex - 3: Write a python program to add new elements to an existing tuple.

Output -

13
3. Using the * operator
We can duplicate tuple elements using the * operator. Look at the examples below.

C.3 TUPLE SWAPPING


Swapping two variables refers to mutually exchanging the values of the variables.

Generally this is done using a temporary or third variable.

But in python we do not need a third variable to swap in python. Look at the example below:

Similarly with tuple assignment in python, we can interchange(swap) the values of two tuples without
using a temporary tuple. Look at the example below.

Output

Packing and Unpacking a Tuple : In Python there is a very powerful tuple assignment feature that
assigns the right hand side of values into the left hand side. In other ways it is called unpacking of a
tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract
those values into a single variable.

14
NOTE: In unpacking the tuple, number of variables on the left hand side should be equal to the number
of values in the given tuple a.
The number of variables on the left side must be the same as that on the right.
In the example below, two tuples are on the left side and three tuples on the right side, hence this
assignment will result in an error as shown in the example below.

C.4 UPDATING TUPLES


Unlike lists and dictionaries, tuples elements cannot be changed in place.
Look at the example below.

But we can merge existing tuples to create a new tuple as follows:

15
C.5 DELETE TUPLE ELEMENTS
It is not possible to delete or remove individual tuple elements. In order to delete an element from a
tuple, we either need to unpack the tuple or convert it into a list and then delete the element. But there
is a way to delete the entire Tuple, just using the del statement.

C.6 BASIC TUPLE OPERATIONS


Tuples respond to the + and * operators just like lists, + operator concatenates two tuples and *
operator multiplies tuple elements both result in creation of new tuple.

Description Python Expression Output

Concatenation - +

Repetition - *

Membership

Iteration

C.7 GENERAL BUILT-IN FUNCTIONS USED WITH TUPLES


Similar to use with lists, the following builtin functions can be used with tuples too:

16
Sl.No Function Description Example

1 len(tuple)
Gives the total length of the tuple.

2 max(tuple)
Returns item from the tuple with
max value.

3 min(tuple)
Returns item from the tuple with
min value.

4 tuple(seq)
Converts a list into tuple

5 type(variable)
Returns the type of the passed
variable. If the passed variable
is tuple, then it would return a
tuple type.

Program Ex1: Write a python program to input 5 subject names and put in a tuple and display that
tuple information on the output screen.

Output

17
Program Ex2: Write a python program to input any two tuples and interchange the tuple values.

Output

C.8 EXERCISES:
1. What are tuples? How are tuples different from lists?
2. Can tuple values be deleted? Explain why.
3. Differentiate between + and * tuple operators. Give one example for each.
4. Write a python program to input two sets values and store it in tuples and also find the length of
each using the built in function.
5. Write a python program to input ‘n’ employee salaries and find the minimum and maximum
salary amongst ‘n’ employees.
6. Predict the output of the following program code

18
D. FUNCTIONS

A function is a block of organized, reusable code that is used to perform a single, related action.
Functions allow us to organize blocks of code better and allow for reuse of the same code.

As you already know, Python gives many built-in functions like print(), len(), type() etc. but you can also
create your own functions. These functions are called user-defined functions.

Functions can be classified as follows :

Functions

Built-in Modules User-defined


D.1 BUILT IN FUNCTIONS
Built-in functions are functions that are already existing in python and can be accessed by a
[programmer to perform a specific task. There are 69 builtin Python functions. Of these, the ones that
we frequently use are listed below:

IMPORTANT BUILT-IN FUNCTIONS


bool() float() str() int() list()

tuple() dict() eval() input() min()

max() divmod() sum() range() round()

pow() type() id() print() sorted()

D.2 Use of Important built-in functions:

Sl. No. Function Description Example

1 divmod(a,b) Takes two numbers as divmod(8,8)

19
arguments and return a pair of (1,0)
numbers consisting of their
quotient (a/b) and remainder (a divmod(6,4)
%b) when using integer division. (1,2)

2 len(<a python Returns the length (the number len(“Python”)


sequence>) of items) of an object. The 6
argument may be a sequence
(such as a string, bytes, tuple, len({1:"one",2:"two"})
list, or range) or a dictionary. 2

len([1,2,3,4,5])
5

3 max(arg1, arg2, Returns the largest of two or max(8,56,234)


etc) more arguments. 234

max("India","China","Japan")
'Japan'

4 min(arg1, arg2, etc) Returns the smallest of two or max(8,56,234)


more arguments. 8

max("India","China","Japan")
‘China’

5 range(stop) It is most often used in “for” for i in range(0,20,2):


loops. The arguments must be print(i)
range(start, stop[, plain integers. If the step
step]) argument is omitted, it defaults
to 1. 0 2 4 6 8 10 12 14 16 18

for i in range(1,10):
print(i)

123456789

6 round(number[, Return the floating point value >>> round(0.5)


ndigits]) number rounded to n digits after 0
the decimal point. >>> round(0.4)
0
>>> round(-2.0)
-2
>>> round(0.6)
1
>>> round(3.14127,2)
3.14

20
7 type(<any python With one argument, return the str="Python"
object>) type of an object. The return type(str)
value is a type object. <class 'str'>

a=5
type(a)
<class 'int'>

8 id(<any python Return the “identity” of an


object>) object. This is a unique constant
associated with that
variable.You can consider
identity to refer to a memory
location. Every value in Python
has a memory location. If a
variable is assigned the same
value as another variable, then
the identity of both remain the
same.

D.3 MODULES:
A module is a file containing Python definitions and statements. We need to import modules to use any
of its functions or variables in our code.
Syntax:
import modulename1[,modulename2,..]
Example:
import math
value=math.sqrt(25)
Note: It's a good programming practice to put all the import statements at the beginning of the python
file. Some important modules are:
❖ math
❖ random
❖ string
❖ time
❖ date
D.3.1 MATH MODULE
Some important functions in math module are listed in the table below:

21
Function / Constant Description Example

ceil(x) Return the ceiling of x, the smallest integer


greater than or equal to x.
(Rounds up to the closest integer value)

floor(x) Return the floor of x, the largest integer less


than or equal to x.
(Rounds down to the closest integer value)

pow(x,y) Return x raised to the power y.

sqrt(x) Return the square root of x.

degrees(x) Converts angle x from radians to degrees.

radians(x) Converts angle x from degrees to radians.

pi Returns the value of the mathematical


constant pi.

D.3.2 Random Module:


Some important functions of the random module are listed in the table below:

Function Description Example

random.randrange(start, Return a randomly selected element


stop[, step]) from range(start, stop, step).

Default step is 1, just like range()


Stop value is not included in the
range.

random.randint(a,b) Return a random integer N such


that a<=N<=b.

randint() is the only function where


both the upper and lower limits (that
is a and b in the example) are
included in the range.

22
D.3.3 USER-DEFINED FUNCTIONS

As you already know, Python gives you many built-in functions like print(), etc. but you can also create
your own functions. These functions are called user-defined functions.

All the functions that are written by any user come under the category of user defined functions. Below
are the steps for writing user defined functions in Python.

● In Python, def keyword is used to declare user defined functions.


● An indented block of statements follows the function name and arguments which contains
the body of the function.

D.3.4 Defining a Function


You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.

● Function blocks begin with the keyword def followed by the function name and parentheses.
● Any input parameters or arguments should be placed within these parentheses.
● The code block within every function starts with a colon (:) and is indented.
● A function may or may not have a return statement. A return statement causes a value to be
returned when the function is run. When a return statement is encountered in a function during
function call, the function execution is terminated and control goes to the statement after the
function call.

Syntax

def functionname( parameters):


<Body of the function>
return <value>

Program Ex 1: Write a function definition to subtract 2 numbers

23
NOTE - The order of parameters matter in this case. The function takes the parameter in the order that
it has been called.

Program Ex 2: Write a python program to define a function to multiply 2 numbers


#Using a return statement #print statement

Example

The following function takes a string as an input parameter and prints it on IDLE.

def printme( str ):


"This prints a passed string into this function"
print(str)
return

def add(a,b ):
"This function adds 2 numbers"
c=a+b
return c

D.3.5 Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from a
Python program or another function or directly from the Python prompt. Following is the
example to call printme() and add() function −

24
D.4 Parameters and Arguments
Parameter is the value provided in parentheses in the function header when we define the function
whereas an Argument is the value provided in function call/invoke statement.
Functions arguments/parameters

parameter

def Function header


area(side):

a=side*sid
e
return a Function call

argument

D.4.1 Types of parameters

Parameters
(formal arguments)

Required Default Keyword Variable length

1. Required arguments: are the arguments passed to a function in correct positional order.
Ex1 -
25
NOTE- As demonstrated in the example above, the argument names can be different from parameter
names. Ex: Multiply(a,b) can be used during definition and during function call, Multiply(x, y) is being
used where ‘x’ gives its value for ‘a’ and ‘y’ is the gives its value for b.
2. Keyword Argument: We will not be exploring Keyword arguments in grade 8.
3. Default argument: We will not be exploring Default arguments in grade 8.
4. Variable length arguments: These arguments are not named in the function definition. The *
symbol is used to indicate that there will be an unknown number of arguments entered during
function run.

Program Ex 1: Write a python program to define a function getLargest(x,y) to take 2 numbers and
return larger of them.

Program Ex 2: Write a python program to define a function getSum(numbers) to find the sum of the
first n numbers.
26
Program Ex 3: Write a python program to print the pattern below using functions.
*
**
***
****
*****

Program Ex 4: Write a python program to find the factors of a number using functions.

27
Output -

D.5 EXERCISES:
1. Define functions in python. What are three kinds of functions ?
2. Explain the following builtin functions below with valid python examples
a. divmod (b) min (c) range
3. What is a module? Give 3 examples of modules in python
4. Explain the following math functions with an example.
a. sqrt (b) pi (c) pow
5. Differentiate between ceil(x) and floor(x) math functions with an example.State the rules to
define your own function in python.
6. Differentiate between arguments and parameters using an example.
7. What are the four types of parameters?
8. Write a program to demonstrate max( ) and min( ) functions in python.
9. Write a python program to define a function to generate numbers in the Fibonnaci series.
10. Write a python program to define functions to: add, subtract, multiply, divide, minimum,
maximum of two numbers and return the results.

28

You might also like