0% found this document useful (0 votes)
24 views18 pages

GE3151_UNIT4_PRINT

GE3151_UNIT

Uploaded by

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

GE3151_UNIT4_PRINT

GE3151_UNIT

Uploaded by

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

UNIT IV

COMPOUND DATA: LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: simple
sorting, histogram, Students marks statement, Retail bill preparation.

LISTS
● List is an ordered sequence of elements. Value`s in the list are called elements / items.
● It can be written as a list of comma-separated elements (values) between square brackets [ ].
● Operations on lists:
1. Create a list
2. Indexing
3. Slicing
4. Concatenation
5. Repetitions
6. Updating
7. Membership
8. Comparison

operations examples description


1.create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
2.Indexing >>> print(a[0]) Accessing the item in the position 0
2
>>> print(a[8]) Accessing the item in the position 8
10
>>> print(a[-1]) Accessing a last element using –indexing
10
3.Slicing >>> a=[2,3,4,5,6,7,8,9,10] Printing a part of the list.
>>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
4 .Concatenation >>>b=[20,30] Adding and printing the items of two
>>> print(a+b) lists
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30
5. Repetition >>>b=[20,30] Create multiple copies of the same list.
>>> print(b*3)
[20, 30, 20, 30, 20, 30]

6 . Updating >>> a=[2,3,4,5,6,7,8,9,10] Updating the list using index value.


>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]

[Type text]
7. Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element is present in
>>> 5 in a list. Otherwise returns false.
True
>>> 100 in a
False
>>> 2 not in a
False
8 .Comparison >>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elements in both
>>>b=[2,3,4] elements are same. Otherwise returns
>>> a==b false
False
>>> a!=b
True

LIST SLICES
List slicing is an operation that extracts a subset of elements from a list and packages them as
another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
● default start value is 0
● default stop value is n-1
● [:] this will print the entire list
● [2:2] this will create a empty slice

3 LIST METHODS
❖ Methods used in lists are used to manipulate the data quickly.
❖ These methods work only on lists.
❖ They do not work on the other sequence types that are not mutable, that is,
the values they contain cannot be changed, added, or deleted.

[Type text]
Syntax: listname.method name( element/index/list)

syntax example description


1 a.append(element) >>> a=[1,2,3,4,5] Add an element to the end of
>>> a.append(6) the list
>>> print(a)
[1, 2, 3, 4, 5, 6]
2 a.insert(index,element) >>> a.insert(0,0) Insert an item at the defined
>>> print(a) index
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> b=[7,8,9] Add all elements of a list to
>>> a.extend(b) the another list
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
4 a.index(element) >>> a.index(8) Returns the index of the first
8 matched item
5 a.sort() >>> a.sort() Sort items in a list in
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
6 a.reverse() >>> a.reverse() Reverse the order of items in
>>> print(a) the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>> a.pop() Removes and returns an
0 element at the last element

8 a.pop(index) >>> a.pop(0) Remove the particular


8 element and return it.

9 a.remove(element) >>> a.remove(1) Removes an item


>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
10 a.count(element) >>> a.count(6) Returns the count of number
1 of items passed as an
argument
11 a.copy() >>> b=a.copy() Returns a shallow copy of
>>> print(b) the list
[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length

13 min(list) >>> min(a) return the minimum


2 element in a list
14 max(list) >>> max(a) return the maximum
7 element in a list.

[Type text]
15 a.clear() >>> a.clear() Removes all items from the
>>> print(a) list.
[]
16 del(a) >>> del(a) Delete the entire list.
>>> print(a)
Error: name 'a' is not
defined

LIST LOOPS
i. For loop
ii. While loop
iii. Infinite Loop
i) For Loop

❖ The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iteratable objects.
❖ Iterating over a sequence is called traversal.
❖ Loop continues until we reach the last item in the sequence.
❖ The body of for loop is separated from the rest of the code using indentation.
Syntax: for val in sequence

ii) List using While loop

● The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
● When the condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.

Syntax:
while (condition):
body of while
[Type text]
Example:
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum) output 15

iii) Infinite Loop


A loop becomes infinite loop if the condition given never becomes false. It keeps on running.
Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

MUTABILITY
● Lists are mutable. (can be changed)
● Mutability is the ability for certain types of data to be changed without entirely
recreating it.
● An element can be changed in a list by accessing it directly as part of the assignment
statement.
● Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list elements can be updated.
Example description

>>> a=[1,2,3,4,5] changing single element


>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

[Type text]
ALIASING

● Creating a copy of a list is called aliasing. When you create a copy both list will be having
same memory location. Changes in one list will affect another list.
● Aliasing refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5] [1, 2, 3, 4, 5]
b=a True
print (b) [100,2,3,4,5]
a is b [100,2,3,4,5]
a[0]=100
print(a)
print(b)

● In this a single list object is created and modified using the subscript operator.
● When the first element of the list named “a” is replaced, the first element of the list
● named “b” is also replaced.
● This type of change is what is known as a side effect. This happens because
after the assignment b=a, the variables a and b refer to the exact same list
object.
● They are aliases for the same object. This phenomenon is known as aliasing.
● To prevent aliasing, a new object can be created and the contents of the
original can be copied which is called cloning.

CLONING
● To avoid the disadvantages of copying we are using cloning. Creating a copy of
a same list of elements with two different memory locations is called cloning.
● Changes in one list will not affect locations of another list.
● Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method

[Type text]
LIST AS PARAMETERS
● In python, arguments are passed by reference.
● If any changes are done in the parameter which refers within the function, then the
changes also reflect back in the calling function.
● When a list to a function is passed, the function gets a reference to the list.
● Passing a list as an argument actually passes a reference to the list, not a copy of the list.
● Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)

TUPLE
A tuple is same as list, except that the set of elements is enclosed in parentheses instead of
square brackets.
❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to
a tuple or remove elements from the tuple.
❖ But tuple can be converted into list and list can be converted in to tuple.
methods Example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
❖ Operations of tuples
1. Creating a tuple
2. Indexing
3. Slicing
4. Concatenation
5. Repetitions
6. Membership
7. Comparison

[Type text]
Operations Examples Description
1. Creating a tuple >>>a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of
Different data types.
2. Indexing >>>print(a[0]) Accessing the item in the position 0
20 Accessing the item in the position 2
>>> a[2]
60
3. Slicing >>>print(a[1:3]) Displaying items from 1st till 2nd
(40,60)

4. Concatenation >>> b=(2,4) Adding tuple elements at


>>>print(a+b) the end of another tuple elements
>>>(20,40,60,”apple”,”ball”,2,4)
5. Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times

>>> a=(2,3,4,5,6,7,8,9,10) Returns True if element is present in


>>> 5 in a tuple. Otherwise returns false.
6. Membership True
>>> 100 in a
False
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10) Returns True if all elements in both
7. Comparison >>>b=(2,3,4) elements are same. Otherwise returns
>>> a==b false
False
>>> a!=b
True
Tuple Methods
● Tuple is immutable so changes cannot be done on the elements of a tuple once it is assigned.

Methods Example Description


a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the first matched
>>> a.index(5) item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given element.
>>> a.count(3)
1
len(tuple) >>> len(a) return the length of the tuple
5
min(tuple) >>>min(a) Return minimum element in a tuple
1
max(tuple) >>>max(a) Return maximum element in a tuple
5
del(tuple) >>>del(a) Delete the entire tuple

[Type text]
TUPLE ASSIGNMENT
❖ Tuple assignment allows variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.
❖ Multiple assignment works by creating a tuple of expressions from the right hand side,
and a tuple of targets from the left, and then matching each expression to a target.
❖ Because multiple assignments use tuples to work, it is often termed
tuple assignment.
❖ It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments: Multiple values can be assigned to multiple variables using tuple
assignment. Example
>>>(a,b,c)=(1,2,3) -packing
>>>print(a) -unpacking
1
>>>print(b)
2
>>>print(c)
3

TUPLE AS RETURN VALUE


● A Tuple is a comma separated sequence of elements.
● It is created with or without ( ).
● A function can return one value. if you want to return more than one value from a function.
we can use tuple as return value.

9 PANIMALAR ENGINEERING COLLEGE CHENNAI CITY CAMPUS – Py


Tuple as argument
❖ The parameter name that begins with * gathers argument into a tuple.

Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')

DICTIONARIES
❖ Dictionary is an unordered collection of elements. An element in dictionary has
a key: value pair.
❖ All elements in dictionary are placed inside the curly braces i.e. { }
❖ Elements in Dictionaries are accessed via keys and not by their position.
❖ The values of a dictionary can be any data type.
❖ Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary
1. Creating a dictionary
2. Accessing an element
3. Update
4. Add element
5. Membership
Operations Example Description

1 Creating a >>> a={1:"one",2:"two"} Creating the dictionary


dictionary >>> print(a) with elements of different data
{1: 'one', 2: 'two'} types.
2 Accessing an >>> a[1] Accessing the elements by using
element 'one' keys.
>>> a[0]
KeyError: 0
3 Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}
4 Add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
5 Membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False
Methods in dictionary

Method Example Description


a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the dictionary.
>>> b=a.copy() here copy of dictionary ’a’ get
>>> print(b) stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
a.items() >>> a.items() Return a new view of the
dict_items([(1, 'ONE'), (2, 'two'), dictionary's items. It displays a
(3, 'three')]) list of
dictionary’s (key, value)
tuple pairs.

a.keys() >>> a.keys() It displays list of keys in


dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
a.pop(key) >>> Remove the element with key
a.pop(3) and return its value from the
'three' dictionary.
>>> print(a)
{1: 'ONE', 2: 'two'}

setdefault(key,value) >>> a.setdefault(3,"three") If key is in the dictionary, return


'three' its value. If key is not present,
>>> print(a) insert key with a value of
{1: 'ONE', 2: 'two', 3: 'three'} dictionary and
>>> a.setdefault(2) return dictionary.
'two'
a.update(dictionary) >>> b={4:"four"} It will add the dictionary with the
>>> a.update(b) existing
>>> print(a) dictionary
{1: 'ONE', 2: 'two', 3: 'three', 4:
'four'}
fromkeys() >>> key={"apple","ball"} It creates a dictionary from key
>>> value="for kids" and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}

len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of the list.
>>>lena(a)
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements from the
>>>a.clear() dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.
Difference between List, Tuples and dictionary

List Tuples Dictionary


list is mutable Tuple is immutable dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any data
type and can repeat, keys must
be of immutable type
List are enclosed in Tuples are enclosed in parenthesis Tuples are enclosed in curly
brackets[ ] and their ( ) and cannot be updated braces { } and consist of key:
elements and size value
can be changed
Example: Example: Example:
List = [10, 12, 15] words = ("hello", "hai") Dict = {"ram": 26, "abi": 24}
or
words = "hello", "hai"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])
Can contain duplicate Can contain duplicate elements. Cannot contain duplicate keys,
elements but can contain duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Use: List is used when Use: Tuple is used in combination Use: Dictionary is used when
data can be modified with a dictionary i.e. a tuple might data is being constantly
frequently represent a key modified

ADVANCED LIST PROCESSING-LIST COMPREHENSION


❖ List comprehensions provide a concise way to apply operations on a list.
❖ It creates a new list in which each element is the result of applying a
given operation in a list.
❖ It consists of brackets containing an expression followed by a “for” clause, then a
list.
❖ The list comprehension always returns a result list.
Syntax : List=[expression for element in list if conditional]

List Comprehension Output

>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]


>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]
>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]
>>> [x for x in num if x>=0]
>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']
>>> element=[word[0] for word in str]
>>> print(element)
Nested list: List inside another list is called nested list
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
Programs on matrix
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)

Matrix subtraction Output


a=[[1,1],[1,1]] [-1, -1]
b=[[2,2],[2,2]] [-1, -1]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]-b[i][j]
for i in c:
Matrix multiplication Output
a=[[1,1],[1,1]] [4, 4]
b=[[2,2],[2,2]] [4, 4]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=c[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)
ILLUSTRATIVE PROGRAMS

Selection sort

● The selection sort selects the smallest element in the list. When the element is found, it is
swapped with the first element in the list
● Then the second smallest element in the list is then searched. When the element is found, it
is swapped with the second element in the list
● This process of selection and exchange continues, until all the element in the list has been
sorted in ascending order.

Steps in selection sort with Eg:

1. Set the first element as minimum.


2. Compare minimum with the second element. If the second element is smaller than minimum,
assign the second element as minimum.
Compare minimum with the third element. Again, if the third element is smaller, then
assign minimum to the third element otherwise do nothing. The process goes on until the last
element

3. Swap the first number with minimum. After each iteration, minimum is placed in the front of the
unsorted list.

For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all
the elements are placed at their correct position

Program:

A = [20,12,10,15,2]
for i in range(len(A)-1):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i],A[min_idx] = A[min_idx], A[i]
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i],end=" ")

Output

Sorted array
2 10 12 15 20

Bubble Sort

● Bubble Sort is a simple sorting algorithm. This sorting algorithm repeatedly compares two
adjacent elements and swaps them if they are in the wrong order.
● It is also known as the sinking sort.
● It has a time complexity of O(n2) in the average and worst cases scenarios and O(n) in the
best-case scenario.
● Bubble sort can be visualized as a queue where people arrange themselves by swapping
with each other so that they all can stand in ascending order of their heights.
● Or in other words, we compare two adjacent elements and see if their order is wrong, if the
order is wrong we swap them.
● i.e arr[i] > arr[j] for 1 <= i < j <= s; where s is the size of the array, if array is to be in
ascending order, and vice-versa).
● Here we sort the following sequence using bubble sort

Let Sequence: 2, 23, 10, 1


● First Iteration
o (2, 23, 10, 1) –> (2, 23, 10, 1), Here the first 2 elements are compared and remain the
same because they are already in ascending order.
o (2, 23, 10, 1) –> (2, 10, 23, 1), Here 2nd and 3rd elements are compared and
swapped(10 is less than 23) according to ascending order.
o (2, 10, 23, 1) –> (2, 10, 1, 23), Here 3rd and 4th elements are compared and
swapped(1 is less than 23) according to ascending order
o At the end of the first iteration, the largest element is at the rightmost position which
is sorted correctly.
● Second Iteration
o (2, 10, 1, 23) –> (2, 10, 1, 23), Here again, the first 2 elements are compared and
remain the same because they are already in ascending order.
o (2, 10, 1, 23) –> (2, 1, 10, 23), Here 2nd and 3rd elements are compared and
swapped(1 is less than 10) in ascending order.
o At the end of the second iteration, the second largest element is at the adjacent
position to the largest element.
● Third Iteration
o (2, 1, 10, 23) –> (1, 2, 10, 23), Here the first 2 elements are compared and swap
according to ascending order.
o The remaining elements are already sorted in the first and second Iterations. After the
three iterations, the given array is sorted in ascending order. So the final result is 1, 2,
10, 23.
Coding
# Creating a bubble sort function
def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(0,len(list1)-1):
if(list1[j]>list1[j+1]):
list1[j],list1[j+1]=list1[j+1],list1[j]
# swap
return list1

list1 = [2,23,10,1]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))

Output:
The unsorted list is: [2,23,10,1]
The sorted list is: [1,2,10,23]

INSERTION SORT
● Insertion sort is a sorting algorithm that places an unsorted element at its suitable
place in each iterations
● Insertion sort works similarly as we sort cards in our hand in a card game.
● We assume that the first card is already sorted then, we select an unsorted card. If the
unsorted card is greater than the card in hand, it is placed on the right otherwise, to
the left. In the same way, other unsorted cards are taken and put in their right place.

Coding
a = [ 8,5,7,1,9,3 ]
for i in a :
j = a.index ( i )
while j > 0 :
if a[ j -1 ] > a[j] :
a[j-1],a[j]=a[j],a[j-1]
j=j-1
else:
break
print ( a )

Output
[1, 3, 5, 7, 8, 9]

Explanation
3. Students marks statement

Coding

mark=[]
tot=0
students=[]
grade=[]
num1=int(input('Enter no of students'))
for num in range(num1):
x=input('Enter name of students')
students.append(x)
print('Enter marks obtained in 5 subjects')
for i in range(5):
mark.append(input())
for i in range(5):
tot=tot+int(mark[i])
avg=tot/5
print('Name=',x)
if avg>=91 and avg<=100:
print('Grade=A')
elif avg>=71 and avg<91:
print('Grade=B')
elif avg>=50 and avg<71:
print('Grade=C')
else:
print('Result: Fail')

Output:
Enter no of students: 2
Enter name of students: Anand
Enter marks obtained in 5 subjects
98
97
96
91
95
Name=Anand
Grade=A
Enter no of students: 2
Enter name of students: Raj
Enter marks obtained in 5 subjects
20
30
35
25
35
Name=Raj
Result:Fail
4. Retail bill preparation

tax=0.18
rate={'pencil':10, 'pen':20, 'scale':7, 'A4paper':165,'writingpad':10}
print('Retail Bill calculator\n')
print('Enter the quantity of ordered item:\n')
pencil=int(input('Pencil:'))
pen=int(input('Pen:'))
scale=int(input('Scale:'))
A4paper=int(input('A4 Paper:'))
writingpad=int(input('Writing pad:'))
cost=pencil*rate['pencil']+pen*rate['pen']+
scale*rate['scale']+A4paper*rate['A4paper']+writingpad*rate['writingpad']
bill=cost+cost*tax
print('Please pay Rs. %f'%bill)

Output
Retail bill calculator
Enter the quality of ordered item:
Pencil: 5
Pen: 7
Scale: 4
A4paper: 3
Writingpad:2
Please pay Rs. 876.740000

You might also like