AY2022_Python4_Gr8 (2)
AY2022_Python4_Gr8 (2)
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.
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.
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.
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
Output:
Output -
4
Output
Output:
In the example above the value for the key - ”Sony” is replaced by the new one.
Output
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
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.
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
7
Output:
8
Sl.No Method Description Example
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.
11
Output -
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
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 -
Output -
13
3. Using the * operator
We can duplicate tuple elements using the * operator. Look at the examples below.
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.
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.
Concatenation - +
Repetition - *
Membership
Iteration
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
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)
len([1,2,3,4,5])
5
max("India","China","Japan")
'Japan'
max("India","China","Japan")
‘China’
for i in range(1,10):
print(i)
123456789
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'>
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
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.
● 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
23
NOTE - The order of parameters matter in this case. The function takes the parameter in the order that
it has been called.
Example
The following function takes a string as an input parameter and prints it on IDLE.
def add(a,b ):
"This function adds 2 numbers"
c=a+b
return c
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
a=side*sid
e
return a Function call
argument
Parameters
(formal arguments)
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