Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3 Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Exercise

 Q: WAP in python for following scenario :


1) Accept user requirements for the tent, such as
a) height
b) radius
c) slant height of the conical part
2) Calculate the area of the canvas used
3) Calculate the cost of the canvas used for making
the tent
4) Calculate the net payable amount by the customer that is
inclusive of the 18% tax
FUNCTIONS
● Function can be defined as a named group of instructions that accomplish a
specific task when it is invoked.
● The syntax for creating a user defined function is as follows:
 Q: Write a user defined function to add 2 numbers and display their sum.
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
Arguments and Parameters
● An argument is a value passed to the function during the function call
which is received in corresponding parameter defined in function
header.
● Q: Write a program using a user defined function that displays sum of first
n natural numbers, where n is passed as an argument.
 Q : Write a program using a user defined function myMean() to calculate the mean of
floating values stored in a list.
 Q : Write a program using a user defined function calcFact() to calculate and display the
factorial of a number num passed as an argument.
A) String as Parameters
 Write a program using a user defined function that accepts the first name and
lastname as arguments, concatenate them to get full name and displays the output
as:
Hello full name
B) Default Parameter
 Python allows assigning a default value to the parameter.
 A default value is a value that is pre-decided and assigned to the parameter
when the function call does not have its corresponding argument.
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
Functions Returning Value
 A function may or may not return a value when called.
 The return statement returns the values from the function.
 The return statement does the following:
• returns the control to the calling function
• return value(s) or None.
Q : Write a program using user defined function calcPow() that accepts base and
exponent as arguments and returns the value Baseexponent where Base and
exponent are integers. The requirements are listed below:
#1. Base and exponent are to be accepted as arguments.
#2. Calculate Base ^exponent
#3. Return the result (use return statement )
#4. Display the returned value.
Flow of Execution
 Flow of execution can be defined as the order in which the statements in a program are
executed.
 When the interpreter encounters a function definition, the statements inside the function
are not executed until the function is called
 It is also important to note that a function must be defined before its call within a program
Q : Program to understand the flow of execution using functions
SCOPE OF A VARIABLE
 The part of the program where a variable is accessible can be defined as the scope of
that variable
(A) Global Variable that is defined outside any function or any block is known as a global
variable. It can be accessed in any functions defined onwards.
(B) Local Variable that is defined inside any function or a block is known as a local variable.
It can be accessed only in the function or a block where it is defined.
Q : Write a program that simulates a traffic light . The program should consist of the
following:
1. A user defined function trafficLight( ) that accepts input from the user, displays an error
message if the user enters anything other than RED, YELLOW, and GREEN. Function light() is
called and following is displayed depending upon return value from light().
a) “STOP, your life is precious” if the value returned by light() is 0.
b) “Please WAIT, till the light is Green “ if the value returned by light() is 1
c) “GO! Thank you for being patient” if the value returned by light() is 2.
2. A user defined function light() that accepts a string as input and returns 0 when the
input is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The input should
be passed as an argument.
3. Display “ SPEED THRILLS BUT KILLS” after the function trafficLight( ) is executed
PYTHON STANDARD LIBRARY
 Python has a very extensive standard library.
 It is a collection of many built in functions that can be called in the program as and
when required
Built-in functions
 Built-in functions are the ready-made functions in Python that are frequently used in
programs
 E.g : input(), int() and print()
Commonly used built-in functions
Module
 Python standard library also consists of a number of modules.
 While a function is a grouping of instructions, a module is a grouping of functions.
 For a complex problem, it may not be feasible to manage the code in one single file.
 Then, the program is divided into different parts under different levels, called modules
 A module is created as a python (.py) file containing a collection of function definitions
 Once we import a module, we can directly use all the functions of that module.
 The syntax of import statement is as follows:
import modulename1 [,modulename2, …]
To call a function of a module, the function name should be preceded with the name of
the module with a dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()
A) Built-in Modules
 commonly used modules :
• math
• random
• statistics
Module name : math
 It contains different types of mathematical functions.
 Most of the functions in this module return a float value.
 In order to use the math module we need to import it using the following statement:
import math
Module name : random
 This module contains functions that are used for generating random numbers.
 For using this module, we can import it using the following statement:
import random
Module name : statistics
 This module provides functions for calculating statistics of numeric (Real-valued) data.
 It can be included in the program by using the following statements:
import statistics
 import statement can be written anywhere in the program
 Module must be imported only once
 In order to get a list of modules available in Python, we can use the following
statement:
help("module")
 To view the content of a module say math, type the following:
help("math")
(B) From Statement
 Instead of loading all the functions into memory by importing a module, from statement
can be used to access only the required functions from a module
 Its syntax is
>>> from modulename import functionname [, functionname,...]
Example 1 :
>>> from random import random
>>> random() #Function called without the module name
Example 2
>>> from math import ceil,sqrt
>>> value = ceil(624.7)
>>> print(sqrt(value))
Create a user defined module basic_ math that
contains the following user defined functions:
1. To add two numbers and return their sum.
2. To subtract two numbers and return their difference.
3. To multiply two numbers and return their product.
4. To divide two numbers and return their quotient and print “Division by Zero”
error if the denominator is zero.
5. Also add a docstring to describe the module. After creating module,
import and execute functions.

Note : """Docstrings""" is also called Python documentation strings. It is a


multiline comment that is added to describe the modules, functions, etc. They
are typically added as the first line, using 3 double quotes.
Strings
 A string can be created by enclosing one or more characters in single, double or triple
quote.
 E.g : str1 = 'Hello World!’
str2 = "Hello World!"
str3 = """Hello World!"""
str4 = '''Hello World!‘’
Note : Python does not have a character data type. String of length one is considered as
character
 Python allows an index value to be negative also.
 Negative indices are used when we want to access the characters of the string from right
to left.
 Starting from right hand side, the first character has the index as -1 and the last character
has the index –n where n is the length of the string
Accessing Characters in a String
 Each individual character in a string can be accessed using a technique called
indexing.
 The index of the first character (from left) in the string is 0 and the last character is n-1
where n is the length of the string
 E.g :
str1 = 'Hello World!’ #initializes a string str1
str1[0] #gives the first character of str1
str1[6] #gives seventh character of str1
str1[15] #gives error as index is out of range
 An inbuilt function len() in Python returns the length of the string that is passed as
parameter.
 E.g str1 = 'Hello World!’
print(len(str1))
 String is Immutable
str1 = "Hello World!" #if we try to replace character 'e' with 'a’
str1[1] = 'a’
STRING OPERATIONS
A) Concatenation : Python allows us to join two strings using concatenation operator plus
which is denoted by symbol +.
str1 = 'Hello’ #First string
str2 = 'World!’ #Second string
print(str1 + str2) #Concatenated strings
B) Repetition : Python allows us to repeat the given string using repetition operator which is
denoted by symbol *.
str1 = 'Hello’ #repeat the value of str1 2 times
print(str1 * 2)
C) Membership Python has two membership operators 'in' and 'not in’
 'in' operator takes two strings and returns True if the first string appears as a substring in
the second string, otherwise it returns False.
 E.g : str1 = 'Hello World!’
print('W' in str1)
D) Slicing In Python, to access some part of a string or substring, we use a method called
slicing
 This can be done by specifying an index range.
 str1[n:m] returns all the characters starting from str1[n] till str1[m-1].
E.g : str1 = 'Hello World!’ #gives substring starting from index 1 to 4
print(str1[1:5])
print(str1[:5])
print(str1[6:])
 The slice operation can also take a third index that specifies the ‘step size’.
 For example, str1[n:m:k], means every kth character has to be extracted from the
string str1 starting from n and ending at m-1
TRAVERSING A STRING
 A) String Traversal Using for Loop :
str1 = 'Hello World!’
for ch in str1:
print(ch,end = ‘’)
B) String Traversal Using while Loop :
str1 = 'Hello World!’
index = 0
while index < len(str1):
print(str1[index])
index += 1
STRING METHODS & BUILT-IN
FUNCTIONS
STRING METHODS & BUILT-IN
FUNCTIONS
Write a program with a user defined function to count the
number of times a character (passed as argument) occurs in
the given string
Lists
 list is an ordered sequence which is mutable and made up of one or more elements.
 Unlike a string which consists of only characters, a list can have elements of different data types, such
as integer, float, string, tuple or even another list.
 E.g : list1 = [2,4,6,8,10,12]
list2 = [100,23.5,'Hello’]
list4 =[['Physics',101],['Chemistry',202], ['Maths',303]]
print(list1)
 elements of a list are accessed in the same way as characters are accessed in a string
list1 = [2,4,6,8,10,12]
list1[0] #return first element of list1
 Lists are Mutable
list1 = [2,4,6,8,10,12]
print(list1)
list1[3] = 'Black’
print(list1)
LIST OPERATIONS
A) Concatenation
list1 = [1,3,5,7,9]
list2 = [2,4,6,8,10]
print(list1 + list2)

B) Repetition
list1 = ['Hello’]
print(list1 * 4)

C) Membership
list1 = ['Red','Green','Blue’]
Print('Green' in list1)
D) Slicing
list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black’]
print( list1[2:6])
print(list1[0:6:2])
print(list1[::2])
TRAVERSING A LIST
(A) List Traversal Using for Loop :
list1 = ['Red','Green','Blue','Yellow', 'Black’]
for item in list1:
print(item)
 Another way of accessing the elements of the list is using range() and len() functions:
for i in range(len(list1)):
print(list1[i])
(B) List Traversal Using while Loop:
list1 = ['Red','Green','Blue','Yellow', 'Black’]
i=0
while i < len(list1):
print(list1[i])
i += 1
LIST METHODS AND BUILT-IN FUNCTIONS
NESTED LISTS
 When a list appears as an element of another list, it is called a nested
list.
 E.g list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
print(list1[4])
print(list1[4][1])
 To access the element of the nested list of list1, we have to specify two
indices list1[i][j].
 The first index i will take us to the desired nested list and second index j
will take us to the desired element in that nested list.
Write a menu driven program to perform various list operations, such
as:
 Append an element
 Insert an element
 Append a list to the given list
 Modify an existing element
 Delete an existing element from its position
 Delete an existing element with a given value
 Sort the list in ascending order
 Display the list.
Tuples
 A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas
E.g : tuple1 = (1,2,3,4,5)
tuple2 =('Economics',87,'Accountancy',89.6)
tuple3 = (10,20,30,[40,50])
tuple4 = (1,2,3,4,5,(10,20))
 If there is only a single element in a tuple then the element should be followed by a
comma.
 If we assign the value without comma it is treated as integer.
• Tuple is an immutable data type
• However an element of a tuple may be of mutable type, e.g., a list.
tuple2 = (1,2,3,[8,9])
tuple2[3][1] = 10
print(tuple2 )
Accessing Elements in a Tuple
 Elements of a tuple can be accessed in the same way as a list or string
using indexing and slicing.
tuple1 = (2,4,6,8,10,12)
print(tuple1[0] )

 TUPLE OPERATIONS
1) Concatenation :
tuple1 = (1,3,5,7,9)
tuple2 = (2,4,6,8,10)
print(tuple1 + tuple2 )
 Concatenation operator can also be used for extending an existing tuple.
E.g : tuple6 = (1,2,3,4,5)
tuple6 = tuple6 + (6,)
print(tuple6)
tuple6 = tuple6 + (7,8,9)
print(tuple6)

2) Repetition
tuple1 = ('Hello','World’)
Print(tuple1 * 3)
3) Membership
tuple1 = ('Red','Green','Blue’)
print('Green' in tuple1)
print('Green' not in tuple1)
4) Slicing
tuple1 = (10,20,30,40,50,60,70,80)
print(tuple1[2:7])
Print(tuple1[0:len(tuple1)])
TUPLE METHODS AND BUILT-IN
FUNCTIONS
TUPLE ASSIGNMENT
 Assignment of tuple is a useful feature in Python.
 It allows a tuple of variables on the left side of the assignment operator to be assigned
respective values from a tuple on the right side.
 The number of variables on the left should be same as the number of elements in the
tuple.
(num1,num2) = (10,20)
print(num1)
record = ( "Pooja",40,"CS")
(name, rollNo, subject) = record
print(name)
NESTED TUPLES
Q : Write a program to input n numbers from the user. Store these
numbers in a tuple. Print the maximum and minimum number from this
tuple.
DICTIONARIES
 The data type dictionary fall under mapping.
 It is a mapping between a set of keys and a set of values.
 The key-value pair is called an item
E.g : dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
print(dict3)
print(dict3['Ram’])
 Dictionaries are Mutable
 Adding a new item :
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
dict1['Meena'] = 78
print(dict1)
 Modifying an Existing Item
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
dict1['Suhel'] = 93.5 #Marks of Suhel changed to93.5
print(dict1)
DICTIONARY OPERATIONS
 Membership :
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
print('Suhel' in dict1)
print('Suhel' not in dict1)
TRAVERSING A DICTIONARY
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
for key in dict1:
print(key,':',dict1[key])
or
for key,value in dict1.items():
print(key,':',value)
DICTIONARY METHODS AND BUILT-IN
FUNCTIONS
MANIPULATING DICTIONARIES
 WAP IN Python to create a dictionary ‘ODD’ of odd numbers between 1 and 10,
where the key is the decimal number and the value is the corresponding number in
words. Perform the following operations on this dictionary:
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
 Write a program IN PYTHON to enter names of employees and their
salaries as input and store them in a dictionary.

You might also like