0% found this document useful (0 votes)
31 views16 pages

XII - CS - Revision Tour

The document covers the basics of Python programming, focusing on functions, modules, and their usage. It explains the types of functions (built-in, module, and user-defined), the concept of modularity, and how to import modules. Additionally, it includes examples and short answer questions related to function definitions, arguments, and variable scopes.
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)
31 views16 pages

XII - CS - Revision Tour

The document covers the basics of Python programming, focusing on functions, modules, and their usage. It explains the types of functions (built-in, module, and user-defined), the concept of modularity, and how to import modules. Additionally, it includes examples and short answer questions related to function definitions, arguments, and variable scopes.
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/ 16

for i in range(p-1):

t=t*b
print(t)
10 Write a program to print of fibonnaci series upto n. 3

for example if n is 50 then output will be :


0
1
1
2
3
5
8
13
21
34
Answer n=int(input("Enter any nubmer"))
a=0
b=0
c=1
while a<=n:
print(a)
b=c
c=a
a=b+c

FUNCTIONS
Notes

• The act of partitioning a program into individual components is called "Modularity".


• A module is a separately saved unit whose functionality can be reused.
• A Python module has the .py extension.
• A Python module can contain objects like docstrings, variables, constants, classes,
objects, statements, functions etc.
• The Python modules that come preloaded with Python are called "standard library
modules".
• A function is a named block of statements that can be invoked by its name.
• Python can have three types of functions i.e., built-in functions, functions in
modules and user-defined functions
• The docstrings are useful for documentation purpose.
• Python module can be imported in a program using import statement.
• There are two forms of import statements:
(i) import <module name>
(ii) from <module name> import <object>
• The built-in functions of Python are always available, one needs not import any
module for them.
• The math module of Python provides mathematical functionality.
• sys.stdin is the most widely used method to read input from the command line or
terminal.
• The command line sys.argv arguments is another way that we can grab input, and
environment be used from within our programs.
• The basic I/O (Input/Output) functions are input() and print() respectively.
43
• One of the most useful tools available in Python is the print() function. This simply
allows the program to display or print data for the user to read. For example:
red='Hi, how are you?"
print (red)
Output : Hi, how are you?
• Python has an input function which lets you ask a user for some text input. In
Python 2, you have a built-in function raw_input(), whereas in Python 3, you have
input() for inputting by user. The syntax is:
mydata = ninput("Prompt:')
print(mydata)
Output: Prompt:
• In Python, a number mathematical operations can be performed with ease by
importing a module named "math" which defines various functions which makes
our task easier.
o ceil(x): Returns the ceiling of x as a float, the smallest integer value greater
than or equal to x.
o floor(x): Returns floor of x as a float, the largest integer value less than or
equal to x.
o fabs(x): Returns the floating point absolute value of x.
• exp(x): Return e**x
• log(x,(base)): With one argument, returns the natural logarithm of x (to base e).

With two arguments, returns the logarithm of x to the given base calculate as
log(x)log(base)
• log10(x): Returns the base-10 logarithm of x. This is usually more accurate than
log(x,10).
• pow(x, y): Returns x raised to the power y. In particular, pow(10, x) and pow(x,
0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite,
x is negative, and y is not an integer then pow(x, y) is undefined, and raises
ValueError.
• sqrt(x): Returns the square root of x.
• cos(x): Returns the cosine of x radians.
• sin(x): Returns the sine of x radians.
• tan(x): Returns the tangent of x radians.
• degrees(x): Converts angle x from radians to degrees.
• radians(x): Converts angle x from degrees to radians.
• A function is a block of organized and reusable code that is used to perform a
single, related action. Functions provide better modularity for your application and
a high degree of code reusability.
• 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.
You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement-the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exit a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
• Defining a function only gives a name, specifies the parameters that are to be
included in the function, a structure the blocks of code.
• The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python :
44
1. Global variables
2. Local variables
• Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.

• Built-in These are the functions that are always available in Python and can be
accessed by a programmer without importing any module.
• Examples of Some Built-in Functions
(i) print(): It prints objects to the text stream file.
(ii) input(): It reads the input, converts it to a string and returns that.
(iii) sorted(): Returns a new sorted list from the items in iterable..
(iv) bool(): Returns a boolean value i.e., True or False..
(v) min(): Returns the smallest of two or more arguments.
(vi) any(): Returns True if any element of the iterable is True.

• String Functions
(i) partition(): It splits the string at the first occurrence of the given argument
and returns a tuple containing three parts.
(ii) join(): It takes a list of string and joins them as a regular string.
(iii) split(): It splits the whole string into the items with separator as a delimeter.
• Modules: It is a file containing Python definitions and statements. We need to
import modules use any containing part before separator, separator parameter
and part after the separator if the separator parameter is found in the string of its
function or variable in our code.
• Examples of Some Module Functions
(i) fabs(): It returns the absolute value of a number.
(ii) factorial(): This method finds the factorial of a positive integer.
(iii) random(): It produces an integer between the limit arguments.
(iv) today(): This method returns the current date and time.
(v) search(): This function searches the pattern inside the string.
(vi) capitalize(): It returns the copy of string in capital letters.

• User-Defined Functions: User defined functions are those that we define ourselves
in our program and then call them wherever we want.
• Parameters: These are the values provided in the parentheses in the function
header when we define the function
• Arguments: These are the values provided in function call/invoke statement.
• Function Arguments: You can call a function by using the following types of formal
arguments:
o Required arguments/Positional arguments
o Keyword arguments
o Default arguments
o Variable-length arguments

• Required arguments are the arguments passed to a function in correct positional


order.
• Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
• A default argument is an argument that assumes a default value, if a value is not
provided in the function call for that argument.
• All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable or the scope of variable.
45
Passing different objects as an arguments :
You can send any data types of argument to a function as string, number, list,
dictionary etc., and it will be treated as the same data type inside a function.

e.g. List as an argument


def fun(Fruit):
for i in Fruit:
print(i)

Food ["Mango", "Cherry", "Grapes", "Banana"]


fun(Food)

Output:-
Mango
Cherry
Grapes
Banana

Short Answer Type Questions – (1 mark for correct answer)


Q.1 Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Q.2. What do you mean by modularity?
Q.3. What is a function call?
Q.4. Name the three categories of functions.
Q.5. What is the role of an argument of a function?
Q.6. What are docstrings?
Q.7. What are docstring conventions?
Q.8. What is the use of following functions?
Q.9. Name the constant available in math module.
Q.10. Write two ways in which you are able to use constant pi in your programs.
Q.11. What is dot notation?
Q.12. What is a function?
Q.13. What is an argument?
Q.14. What is the general syntax for defining a function in Python?
Q.15. What is function header?
Q.16. What are parameters?
Q.17. The convention for indentation within a block is four spaces. Is it true?
Q.18. Find the error in the following codes.
def minus(total_decrement)
output= total_decrement
Q. 19. What is _main_?
Q. 20. What is _name_?
Q. 21. What is the difference between arguments and parameters?
Q. 22. Name two types of function in Python.
Q. 23. Trace the flow of execution for following program.
1 def power (b,p):
2 r = b**p
46
3 return r
4
5 def calcsquare(a):
6 a= power(a,2)
7 return a
8
9 n=5
10 result = calcsquare(n)
11 print(result)
Q. 24. What will be the output of the following code?
def addEm(x,y,z):
print(x+y+z)

def prod(x,y,z):
return x*y*z

a= addEm(6,16,26)
b= prod(2,3,6)
print(a,b)
Q.25. What is the use of return statement?

Short Long Answer Type Questions - (2 mark for correct answer)


Q. 1. Find and write the output of the following Python code:
def fun(s):
k= len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
Q. 2. What do you understand by local and global scope of variables? How can you
access a global variable inside the function, if function has a variable with same
name.
Q. 3. What are the differences between parameters and arguments?
Q. 4. What are default arguments?

Q. 5. What are keyword arguments?


Q. 6. What are the advantages of keyword arguments?
Q. 7. Write a generator function generatesq () that displays the square roots of
numbers from 100 to n where n is passed as an argument.
Q. 8. What are the advantages of dividing a program into modules.
Q. 9. Differentiate between Built-in functions and user defined functions.
Q. 10. Differentiate between Built-in functions and functions defined in modules.

Long Answer Type Questions - (3 mark for correct answer)


Q. 1. List a type of arguments and explain any 2 type of arguments.
Q. 2. Write a method in Python to find and display the prime number between 2 to
N. Pass N as argument to the method.
47
Q. 3. Write a program that uses a function which take two string arguments and
returns the string comparison result of the two passed strings.
Q. 4. Write definition of a function
1. OddSum(Numbers) to add Odd values in the list Numbers.
2. EvenSum(Numbers) to add Even values in the list Numbers.
Q.5. Define a function overlapping () that takes two lists and returns true if they have
at least one member in common, False otherwise.
Q.6. Write a program for nth multiple of Fibonacci Series. Also show proper
documentation.
Q. 7. Write a Python program to reverse a string.
Q.8. A function checkMain() defined in module Allchecks.py is being used in two
different programs
In program 1 as
Allchecks.checkMain(3,'A')
and in program 2 as
checkMain(4,'Z').
Why are the functions call statements different in each program?
Q. 9. Write a python program to find simple interest using a user defined function
with parameters and with return value.
Q. 10. Explain any three string functions with example?

Case Base Questions - (5 mark for correct answer)

Q. 1. Kids Elementary is a playway school that focuses on 'Play and learn' strategy
that helps toddlers understand concepts in a fun way. Being a senior programmer,
you have taken responsibility to develop a program using user-defined functions to
help children differentiate between upper case and lower case letters/English
alphabet in a given sentence. Make sure that you perform a careful analysis of the
type of alphabets and sentences that can be included as per age and curriculum.

Write a Python program that accepts a string and calculates the number of upper
case letters and lower case letters.

Q. 2. Traffic accidents occur due to various reasons. While problems with roads or
inadequate safety facilities lead to some accidents, majority of the accidents are
caused by drivers' carelessness and their failure to abide by traffic rules.
ITS Roadwork is a company that deals with manufacturing and installation of traffic
lights so as to minimize the risk of accidents. Keeping in view the requirements,
traffic simulation is to be done. Write a program in Python that simulates a traffic
light. The program should perform the following:
(a) 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 the following is displayed depending upon return value
from light():
(i) "STOP, Life is more important than speed" if the value returned by light() is
0.
(ii) "PLEASE GO SLOW." if the value returned by light() is 1.
(iii) "You may go now." if the value returned by light() is 2.
(b) Auser-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.
(c) Display "BETTER LATE THAN NEVER" after the function trafficLight() is executed.

48
Summary

➢ A module is a separately saved unit whose functionality can be reused at will.


➢ A function is a named block of statements that can be invoked by its name.
➢ Python can have three types of functions:
• Built-in functions,
• Functions in modules, and
• User-defined functions.
➢ A Python module can contain objects like docstrings, variables, constants, classes,
objects, statements, functions
➢ A Python module has the py extension.
➢ A Python module can be imported in a program using import statement.
➢ There are two forms of Importing Python module statements:
(i) import <modulename>
(ii) from <module> import <object>
➢ The built-in functions of Python are always available; one need not import any
module for them.
➢ The math module of Python provides math functionality.
➢ Functions make program handling easier as only a small part of the program is
dealt with at a time, thereby avoiding ambiguity.
➢ The values being passed through a function-call statement are called arguments
(or actual parameters or actual arguments).
➢ The values received in the function definition/header are called parameters (or
formal parameters or formal arguments).
➢ Keyword arguments are the named arguments with assigned values being passed
in the function-call statement. A function may or may not return a value.
➢ A void function internally returns legal empty value None. The program part(s) in
which a particular piece of code or a data value (e.g., variable) can be accessed
is known as Variable Scope.
➢ In Python, broadly, scopes can either be global scope or local scope.
➢ A local variable having the same name as that of a global variable hides the global
variable in its function.
➢ A file that contains a collection of related functions grouped together and other
definitions is called module.
➢ A search path is the list of directories that the interpreter searches before
importing a module.
➢ A library is just a module that contains some useful definitions.
➢ The random() function generates a floating point random value from 0 to <1.
➢ A function is said to be recursive if it calls itself.
➢ There are two cases in each recursive function-the recursive case and the base
case. An infinite recursion is when a recursive function calls itself endlessly.
➢ if there is no base case or if the base case is never executed, infinite recursion
occurs.
➢ Iteration uses the same memory space for each pass contrary to recursion where
fresh memory is allocated for each successive call.
➢ Recursive functions are relatively slower than their iterative counterparts. Some
commonly used recursive algorithms are factorial, gcd, fibonacci series printing,
binary search, etc.
➢ String can be passed to a function as argument but it is used as pass by value.
➢ Tuple value cannot be modified in a function.
➢ In Python, everything is an object, so the dictionary can be passed as an
argument to a function like other variables are passed.

49
Short Answer Type Questions – (1 mark for correct answer)
Q.1 Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Ans. 15

Q.2. What do you mean by modularity?


Ans. The act of partitioning a program into individual components (modules) is called
modularity.

Q.3. What is a function call?


Ans. To use a function that has been defined earlier, a function call statement is
written in Python.
Its syntax is <function name> (<value to be passed to argument>)
e.g. print ()

Q.4. Name the three categories of functions.


Ans. 1. Built-in-Functions
2. Functions defined in modules
3. User defined Functions.

Q.5. What is the role of an argument of a function?


Ans. An argument passes the value to the function to work upon.

Q.6. What are docstrings?


Ans. The docstrings are triple quoted strings in a Python module program which are
displayed as document when help (<module or program name>) command is
issued. (1 mark for correct answer) 1

Q.7. What are docstring conventions?


Ans. General docstring conventions are:
(1) First Letter of the first line is a capital letter.
(2) Second line as blank line.
(3) Rest of the details begin from third line.

Q.8. What is the use of following functions?


(a) ceil (b) sqrt (c) exp (d) fabs
Ans (a) ceil() function returns smallest integer not less than the argument.
(b) sqrt() function returns square-root of the argument.
(c) exp() function returns natural logarithm e raised to the argument power.
(d) fabs() function returns the absolute value of the supplied argument.

Q.9. Name the constant available in math module.


Ans. math.pi (where pi(#)=3.1415....)
math.e (where e = 2.718281.....)

Q. 10. Write two ways in which you are able to use constant pi in your programs.
Ans. 1st method
import math m
50
print (math.pi)

2nd method
from math import pi
print (pi)
Q. 11. What is dot notation?
Ans. When a module is import, we can use its functions or constants by specifying
the .name of the module and of the function, separated by a dot.
e.g. <module name>. <function name>()
This is called dot notation.

Q.12. What is a function?


Ans. A function is a block of statements that is given a name. This name can be used
to invoke the function.

Q.13. What is an argument?


Ans. An argument is data passed to a function through function call statement.

Q. 14. What is the general syntax for defining a function in Python?


Ans. def<function name> ([parameters]):
["""<functions docstrings>"""]
<statement>
[<statement>]

Q. 15. What is function header?


Ans. The first line of function definition that specifies It begins name of the functions
and parameters. with keyword def and ends with a colon().
Syntax: def <function_name> ([parameters]);

Q.16. What are parameters?


Ans. Parameters are variables listed within parentheses of a function header.

Q.17. The convention for indentation within a block is four spaces. Is it true?
Ans. Yes.
Q. 18. Find the error in the following codes.
def minus(total_decrement)
output= total_decrement
Ans. Colon (:) is missing in function header. It should be
def minus(total_decrement):

Q. 19. What is _main_?


Ans. The segment with top level statements is named as_main_ by Python.

Q. 20. What is _name_?


Ans. _name_ is a built in variable that states the name of the top level statements
i.e. _main_.

Q. 21. What is the difference between arguments and parameters?


Ans. Value that are being passed are called arguments and values that are received
are called parameters.

Q. 22. Name two types of function in Python.


Ans. Non-void and void functions.
51
(½ mark for each function type) 1

Q. 23. Trace the flow of execution for following program.


1 def power (b,p):
2 r = b**p
3 return r
4
5 def calcsquare(a):
6 a= power(a,2)
7 return a
8
9 n=5
10 result = calcsquare(n)
11 print(result)
Ans. 1→5→9→10→6→2→3→7→11

Q. 24. What will be the output of the following code?


def addEm(x,y,z):
print(x+y+z)

def prod(x,y,z):
return x*y*z

a= addEm(6,16,26)
b= prod(2,3,6)
print(a,b)
Ans. 48
None 36.

Q.25. What is the use of return statement?


Ans. The return statement terminates the execution of a function and returns control
to the calling function.

Short Answer Type Questions - (2 mark for correct answer)

Q. 1. Find and write the output of the following Python code:


def fun(s):
k= len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
Ans. SCHOOLbbbbCOM

Q. 2. What do you understand by local and global scope of variables? How can you
access a global variable inside the function, if function has a variable with same
name.
52
Ans. A global variable is a variable that is accessible globally. A local variable is one
that is only accessible to the current scope, such as temporary variables used
in a single function definition. A variable declared outside of the function or in
global scope is known as global variable. This means, global variable can be
accessed inside or outside of the function where as local variable can be used
only inside the function. We can access by declaring variable as global A.

Q. 3. What are the differences between parameters and arguments?


Ans.
S.No. Parameters Arguments
Values provided in function Values provided in function
1
header call.
(eg) def area (r): (eg) def main()
→r is the parameter radius = 5.0
2
area (radius)
→ radius is the argument
Q. 4. What are default arguments?
Ans. Python allows function arguments to have default values; if the function is called
without the argument, the argument gets its default value.

Q. 5. What are keyword arguments?


Ans. If there is a function with many parameters and we want to specify only some
of them in function call, then value for such parameters can be provided by
using their names instead of the positions.
These are called keyword arguments.
(e.g.) def simpleinterest(p, n=2, r=0.6):
def simpleinterest(p, r=0.2, n=3):

Q.6. What are the advantages of keyword arguments?


Ans. It is easier to use since we need not to remember the order of the arguments.
We can specify the values for only those parameters which we want, and others
will have default values.
Q.7. Write a generator function generatesq () that displays the square roots of
numbers from 100 to n where n is passed as an argument.
Ans. import math
def generates(n):
for i in range(100,n):
print(math.sqrt(i))

Q. 8. What are the advantages of dividing a program into modules.


Ans. The advantages of dividing a program into modules :
• It reduces complexity of the program.
• It creates well-defined boundaries within the program.
• It increases the reusability of the module.

Q. 9. Differentiate between Built-in functions and user defined functions.


Ans. Built in functions are predefined functions that are already defined in Python
and can be used anytime.
e.g. len(), type(), int(), etc.
User defined functions are defined by the programmer.
Q. 10. Differentiate between Built-in functions and functions defined in modules.
Ans. Built-in functions are predefined functions that are already defined in Python
and can be used anytime e.g. len(), type(), int() etc. Functions int defined in
53
modules are predefined in modules and can be used only when the
corresponding module is imported e.g. to use predefined function sqrt() the
math module needs to be imported as import math.

Long Answer Type Questions - (3 mark for correct answer)

Q. 1. List a type of arguments and explain any 2 type of arguments.


Ans. Type of arguments:
• Positional arguments
• Default arguments
• Keyword arguments
• Variable length arguments
Keyword arguments :
If there is a function with many parameters and we want to specify only
some of them in function call, then value for such parameters can be provided
by using their names instead of the positions.

These are called keyword arguments.


e.g. def simpleinterest(p, n=2, r=0.6):
def simpleinterest(p, r=0.2, n=3):
Default arguments
Python allows function arguments to have default values; if the function
is called without the argument, the argument gets its default value.
e.g. def add(a,b=0)
def mul(a=1,b=1)
(Note:Student may explain any 2 type of argument)

Q. 2. Write a method in Python to find and display the prime number between 2 to
N. Pass N as argument to the method.
Ans. def prime(N):
for a in range (2, N):
prime = 1
for i in range (2, a):
if a%i ==0:
prime = 0
if prime == 1:
print (a)

OR
def prime(N):
for a in range (2, N):
for i in range (2, a):
if a%i == 0:
break
else:
print (a)
break

Q. 3. Write a program that uses a function which take two string arguments and
returns the string comparison result of the two passed strings.
Ans. def stringComp (str1, str2):
if str1.length()!=str2.length:
return(False)
54
else:
for i in range (str1.length()):
if str1[i]:= str2[i]:
return(False)
else:
return (True)

fstring=input ("Enter First string:")


sstring=input ("Enter Second string:")
if stringComp (fstring, sstring):
print ("Strings are same.")
else:
print ("Strings are different")

Q. 4. Write definition of a function


1. OddSum(Numbers) to add Odd values in the list Numbers.
2. EvenSum(Numbers) to add Even values in the list Numbers.

Ans. def OddSum(Numbers):


Sum=0
for i in range(len(Numbers)):
if(Numbers[i]%2!=0):
Sum+=Numbers[i]
print(Sum)

def EvenSum(Numbers):
Sum=0
for i in range(len(Numbers)):
if(Numbers[i]%2==0):
Sum+=Numbers[i]
print(Sum)

Q.5. Define a function overlapping () that takes two lists and returns true if they have
at least one member in common, False otherwise.
Ans. def overlapping (list1, list2):
l1= len(list1)
l2= len(list2)
flag=False
for i in range (11):
for j in range (12):
if list1[i]==list2[j]:
flag=True
return flag
Q. 6. Write a program for nth multiple of Fibonacci Series. Also show proper
documentation.
Ans. # Python Program to find position of nth multiple
# of a number k in Fibonacci Series
def findPosition(k, n):
f1 = 0
f2=1
i=2
while i!=0:
f3=f1+f2
55
f1 = f2
f2=f3
if f2%k == 0:
return n*i
i+=1
return
# Multiple no.
n=5
#Number of whose multiple we are finding
k=4

print("Position of nth multiple of k in")


print("Fibonacci series is", findPosition(k,n))

Q. 7. Write a Python program to reverse a string.


Ans. def string_reverse(str1):
rstr1= “”
index = len(str1)

while index > 0:


rstr1+= str1[index-1]
index = index-1
return rstr1
print(string_reverse("1234abcd'))

Q. 8. A function checkMain() defined in module Allchecks.py is being used in two


different programs
In program 1 as
Allchecks.checkMain(3,'A')
and in program 2 as
checkMain(4,'Z').
Why are the functions call statements different in each program?

Ans. In program 1, the complete module Allchecks.py must have been imported as
import Allchecks
So a SpaceName is created and we need to specify the module name.
In program 2, only the function checkMain() must have been imported as

From Allchecks import checkMain()


So the checkMain() function is imported into the namespace of the program2
and hence can be used independently.

Q. 9. Write a python program to find simple interest using a user defined function
with parameters and with return value.
Ans. #Python program to calculate simple interest using function
def simpleInterest(P, N, R):
SI = (P * N * R)/100
return SI
P = float(input("Enter the principal amount : "))
N = float(input("Enter the number of years : "))
R = float(input("Enter the rate of interest : "))
#calculate simple interest by using this formula
56
SI = simpleInterest(P, N, R)
#print
print("Simple interest : ",SI)

Q. 10. Explain any three string functions with example?


Ans. 1) isupper():The isupper() method returns True if all the characters are in
upper case, otherwise False.
txt = "THIS IS NOW!"
x = txt.isupper()
print(x)
2) upper() : The upper() method returns a string where all characters are in
upper case.
txt = "Hello my friends"
x = txt.upper()
print(x)
3) isdigit() : The isdigit() method returns True if all the characters are digits,
otherwise False.
txt = "50800"
x = txt.isdigit()
print(x)
(Note: Student may write any three string functions)

Case Base Questions - (5 mark for correct answer)

Q. 1. Kids Elementary is a playway school that focuses on 'Play and learn' strategy
that helps toddlers understand concepts in a fun way. Being a senior
programmer, you have taken responsibility to develop a program using user-
defined functions to help children differentiate between upper case and lower
case letters/English alphabet in a given sentence. Make sure that you perform
a careful analysis of the type of alphabets and sentences that can be included
as per age and curriculum.

Write a Python program that accepts a string and calculates the number of
upper case letters and lower case letters.

Ans. #A user-defined function that accepts a string


# and calculates the number of upper case letters and lower case letters
def string_test(s):
d= {"UPPER CASE": 0, "LOWER CASE":0}
for c in s:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower ():
d["LOWER CASE"]+=1
else:
pass
print ("Original String: ", s)
print ("No. of Upper case characters: ", d["UPPER CASE"])
print ("No. of Lower case characters: ", d["LOWER CASE"])
string_test("Play Learn and Grow")

Q. 2. Traffic accidents occur due to various reasons. While problems with roads or

57
inadequate safety facilities lead to some accidents, majority of the accidents are
caused by drivers' carelessness and their failure to abide by traffic rules.
ITS Roadwork is a company that deals with manufacturing and installation of traffic
lights so as to minimize the risk of accidents. Keeping in view the requirements,
traffic simulation is to be done. Write a program in Python that simulates a traffic
light. The program should perform the following:

(a) 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 the following is displayed depending upon return value
from light():
(i) "STOP, Life is more important than speed" if the value returned by light() is 0.
(ii) "PLEASE GO SLOW." if the value returned by light() is 1.
(iii) "You may go now." if the value returned by light() is 2.
(b) Auser-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.
(c) Display "BETTER LATE THAN NEVER" after the function trafficLight() is executed.

Ans. # Program to simulate a traffic light comprising of


# two user defined functions trafficLight() and light().

def trafficlight ():


signal input ("Enter the colour of the traffic light: ")
if (signal not in ("RED", "YELLOW", "GREEN")):
print("Please enter a valid Traffic Light colour in CAPITALS")
else:
value= light(signal)# function call to light()
` if(value==0):
print ("STOP, Life is more important than speed")
elif (value==1):
print ("PLEASE GO SLOW.")
else:
print ("You may go now.")
def light (colour):
if (colour "RED"):
return (0)
elif (colour "YELLOW"):
return (1)
else:
return (2) #function end a here
trafficlight ()
print ("BETTER LATE THAN NEVER")

Files – Text Files

A text file stores information in the form of a stream of ASCII or Unicode characters.
In text files, each line of text is terminated, (delimited) with a special character known
as EOL (End of Line) character. In Python, by default, this EOL character is the
newline character ('\n') or carriage-return, newline combination ('\r\n').
The text files can be of following types:

58

You might also like