Question 1:
Observe the following programs carefully, and identify the error:
a) def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call
b) from math import sqrt,ceil
def calc():
print cos(0)
calc() #function call
c) mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9()
d) def findValue(vall = 1.0, val2, val3):
final = (val2 + val3)/ vall
print(final)
findvalue() #function call
e) def greet():
return(“Good morning”)
greet() = message #function call
ANSWER:
a) There are two errors in the given program.
- The function “create” is defined using two arguments, ‘text’ and ‘freq’, but when the function is called in line number 4, only one argument is passed as a parameter. It should be written ‘create(5, 4)’ i.e with two parameters.
- The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(text)’
b) There are two errors in the given program.
- Only square root (sqrt) and ceiling (ceil) functions have been imported from the Math module, but here cosine function (cos) is used. ‘from math import cos’ should be written in the first line for the ‘cos’ function to work properly.
- The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(cos(0))’.
c) There are two errors in the given program.
- In line 1, ‘mynum’ variable is defined which is a global variable. However, in line 3, a variable with the same name is defined again. Therefore, ‘mynum’ is treated as a new local variable. As no value has been assigned to it before the operation, hence, it will give an error. The local variable can either be changed to a different name or a value should be assigned to the local ‘mynum’ variable before line 3.
- The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(mynum)’.
d) There are three errors in the given program:
- The ‘function call’ in line 4 is calling an invalid function. ‘findValue()’ is different from ‘findvalue()’ as Python is case sensitive.
- ‘findValue()’ function needs the value of at least 2 arguments val2 and val3 to work, which is not provided in the function call.
- As ‘vall’ is already initialized as ‘vall = 1.0’, it is called ‘Default parameter’ and it should be always after the mandatory parameters in the function definition. i.e. def findValue(val2, val3, vall = 1.0) is the correct statement.
- The function ‘greet()’ returns value “Good Morning” and this value is assigned to the variable “message”. Therefore, it should follow the rule of assignment where the value to be assigned should be on RHS and the variable ‘message’ should be on LHS. The correct statement in line 3 will be ‘message = greet()’.
e) There is one error in the given program.
Page No 170:
Question 2:
How is math.ceil(89.7) different from math.floor(89.7)?
ANSWER:
Floor: The function ‘floor(x)’ in Python returns the largest integer not greater than x. i.e. the integer part from the variable.
Ceil: The function ‘ceil(x)’ in Python returns the smallest integer not less than x i.e., the next integer on the RHS of the number line.
Hence, ‘math.ceil(89.7)’ will return 90 whereas ‘math.floor(89.7)’ will return 89.
Page No 170:
Question 3:
Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.
ANSWER:
‘randint(a,b)’ function will return a random integer within the given range as parameters.
‘random()’ function generates a random floating-point value in the range (0,1)
Therefore, to generate a random number between 1 and 5 we have to use the randint(1,5) function.
Note: ‘randint()’ is a part of ‘random’ module so, before using the same in the program, it has to be imported using the statement ‘from random import randint’
Page No 170:
Question 4:
How is built-in function pow() function different from function math.pow()? Explain with an example.
ANSWER:
There are two main differences between built-in pow() function and math.pow() functions.
- The built-in pow(x,y [,z]) function has an optional third parameter as modulo to compute x raised to the power of y and optionally do a modulo (% z) on the result. It is same as the mathematical operation: (x ^ y) % z. Whereas, math.pow() function does not have modulo functionality.
- In math.pow(x,y) both ‘x’ and ‘y’ are first converted into ‘float’ data type and then the power is calculated. Therefore, it always returns a value of ‘float’ data type. This does not happen in the case of built-in pow function, however, if the result is a float data type, the output will be float else it will return integer data type.
Example:
import math
print()
#it will return 25.0 i.e float
print(math.pow(5,2))
print()
#it will return 25 i.e int
print(pow(5,2))
Page No 170:
Question 5:
Using an example, show how a function in Python can return multiple values.
ANSWER:
Program:
def myfun():
return 1, 2, 3
a, b, c = myfun()
print(a)
print(b)
print(c)
OUTPUT:
1
2
3
NOTE: Although it looks like ‘myfun()‘ returns multiple values, but actually a tuple is being created here. It is the comma that forms a tuple, not the parentheses, unless it is absolutely required there, such as in the case of a blank tuple.
Page No 170:
Question 6:
Differentiate between the following with the help of an example:
a) Argument and Parameter
b) Global and Local variable
ANSWER:
a) Argument and Parameter:
The parameter is variable in the declaration of a function. The argument is the actual value of this variable that gets passed to function when the function is called.
Program:
def create (text, freq):
for i in range (1, freq):
print text
create(5, 4) #function call
Here, in line 1, ‘text’ and ‘freq’ are the parameters whereas, in line 4 the values ‘5‘and‘4‘ are the arguments.
b) Global and Local variable:
In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any function defined in the program. Any change made to the global variable will impact all the functions in the program where that variable is being accessed.
A 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. It exists only till the function executes.
Program:
# Global Variable
a = “Hi Everyone!!”
def func():
# Local variable
b = “Welcome”
# Global variable accessed
print(a)
# Local variable accessed
print(b)
func()
# Global variable accessed, return Hi! Everyone
print(a)
# Local variable accessed, will give error: b is not defined
print(b)
Page No 170:
Question 7:
Does a function always return a value? Explain with an example.
ANSWER:
A function does not always return a value. In a user-defined function, a return statement is used to return a value.
Example:
Program:
# This function will not return any value
def func1():
a = 5
b = 6
# This function will return the value of ‘a’ i.e. 5
def func2():
a = 5
return a
# The return type of the functions are stored in the variables
message1 = func1()
message2 = func2()
print(“Return from function 1–>”, message1)
print(“Return from function 2–>”, message2)
OUTPUT:
Return from function 1–> None
Return from function 2–> 5
Page No 171:
Question 1:
To secure your account, whether it be an email, online bank account or any other account, it is important that we use authentication. Use your programming expertise to create a program using user defined function named login that accepts userid and password as parameters (login(uid,pwd)) that displays a message “account blocked” in case of three wrong attempts. The login is successful if the user enters user ID as “ADMIN” and password as “St0rE@1”. On successful login, display a message “login successful”.
ANSWER:
Points to consider:
i) As per the question, user-defined function login(uid,pwd)needs to be created which should display either “Login Successful” or “Account Blocked” after 3 wrong attempts. Therefore, a global variable should be used and its value should increase by 1 after every unsuccessful attempt.
ii) If the username and password are correct, the program should display “Login Successful” and terminate.
iii) Once the check for the username/password is complete and if the credentials are incorrect, the program should check for the counter value, and if ‘counter’ is more than 2, the program should display “Account Blocked” and exit, otherwise it should give the option to enter the username and password again.
The flow chart for the program can be drawn as follows:
Program:counter = 0
def logintry():
##This function will ask for username and password from the user and then pass the entered value to the login function
username = input(“Enter username: “)
password = input(“Enter password: “)
login(username, password);
def login(uid,pwd):
global counter
if(uid==”ADMIN” and pwd ==”St0rE@1″):
print(“Login Successful”)
return
#If username and password is correct the program will exit
else:
counter += 1
print(“The username or password is incorrect”)
if(counter>2):
# check counter value to see
# the no.of incorrect attempts
print(“Account blocked”)
return
else:
# Calling logintry() function to # start the process again
print(“Try again”)
logintry()
# Start the program by calling the function
logintry()
OUTPUT:
When Incorrect values are entered:
Enter username: user
Enter password: pwd
The username or password is incorrect
Try again
Enter username: uname
Enter password: password
The username or password is incorrect
Try again
Enter username: user
Enter password: password
The username or password is incorrect
Account blocked
When the correct values are entered:
Enter username: ADMIN
Enter password: St0rE@1
Login Successful
Page No 171:
Question 2:
XYZ store plans to give a festival discount to its customers. The store management has decided to give discount on the following criteria:
Shopping Amount | Discount Offered |
>=500 and <1000 | 5% |
>=1000 and <2000 | 8% |
>=2000 | 10% |
An additional discount of 5% is given to customers who are the members of the store. Create a program using user defined function that accepts the shopping amount as a parameter and calculates discount and net amount payable on the basis of the following conditions:
Net Payable Amount = Total Shopping Amount – Discount.
ANSWER:
In this program, the shopping amount needs to be compared multiple times, hence ‘elif’ function will be used after first ‘if’.
If the comparison is started from the highest amount, each subsequent comparison will eliminate the need to compare maximum value.
Program:
# function definition,
def discount(amount, member):
disc = 0
if amount >= 2000:
disc = round((10 + member) * amount/100, 2)
elif amount>= 1000:
disc = round((8 + member) * amount/100, 2)
elif amount >= 500:
disc = round((5 + member) * amount/100, 2)
payable = amount – disc
print(“Discount Amount: “,disc)
print(“Net Payable Amount: “, payable)
amount = float(input(“Enter the shopping amount: “))
member = input(“Is the Customer a member?(Y/N) “)
if(member == “y” or member == “Y”):
#Calling the function with member value 5
discount(amount,5)
else:
#if customer is not a member, the value of member is passed as 0
discount(amount, 0)
OUTPUT:
Enter the shopping amount: 2500
Is the Customer a member?(Y/N) Y
Discount Amount: 375.0
Net Payable Amount: 2125.0
Enter the shopping amount: 2500
Is the Customer a member?(Y/N) N
Discount Amount: 250.0
Net Payable Amount: 2250.0
Page No 171:
Question 3:
‘Play and learn’ strategy helps toddlers understand concepts in a fun way. Being a senior student you have taken responsibility to develop a program using user defined functions to help children master two and three-letter words using English alphabets and addition of single digit numbers. Make sure that you perform a careful analysis of the type of questions that can be included as per the age and curriculum.
ANSWER:
This program can be implemented in many ways. The structure will depend on the type of questions and options provided. A basic structure to start the program is given below. It can be built into a more complex program as per the options and type of questions to be included.
Program:
import random
#defining options to take input from the user
def options():
print(“\n\nWhat would you like to practice today?”)
print(“1. Addition”)
print(“2. Two(2) letters words”)
print(“3. Three(3) letter words”)
print(“4. Word Substitution”)
print(“5. Exit”)
inp=int(input(“Enter your choice(1-5)”))
#calling the functions as per the input
if inp == 1:
sumOfDigit()
elif inp == 2:
twoLetterWords()
elif inp == 3:
threeLetterWords()
elif inp == 4:
wordSubstitution()
elif inp == 5:
return
else:
print(“Invalid Input. Please try again\n”)
options()
#Defining a function to provide single digit addition with random numbers
def sumOfDigit():
x = random.randint(1,9)
y = random.randint(1,9)
print(“What will be the sum of”,x,”and”,y,”? “)
z = int(input())
if(z == (x+y)):
print(“Congratulation…Correct Answer…\n”)
a = input(“Do you want to try again(Y/N)? “)
if a == “n” or a == “N”:
options()
else:
sumOfDigit()
else:
print(“Oops!!! Wrong Answer…\n”)
a = input(“Do you want to try again(Y/N)? “)
if a == “n” or a == “N”:
options()
else:
sumOfDigit()
#This function will display the two letter words
def twoLetterWords():
words = [“up”,”if”,”is”,”my”,”no”]
i = 0
while i < len(words):
print(“\n\nNew Word: “,words[i])
i += 1
inp = input(“\n\nContinue(Y/N):”)
if(inp == “n” or inp == “N”):
break;
options()
#This function will display the three letter words
def threeLetterWords():
words = [“bad”,”cup”,”hat”,”cub”,”rat”]
i = 0
while i < len(words):
print(“\n\nNew Word: “,words[i])
i += 1
inp = input(“Continue(Y/N):”)
if(inp == “n” or inp == “N”):
break;
options()
#This function will display the word with missing character
def wordSubstitution():
words = [“b_d”,”c_p”,”_at”,”c_b”,”_at”]
ans = [“a”,”u”,”h”,”u”,”r”]
i = 0
while i < len(words):
print(“\n\nWhat is the missing letter: “,words[i])
x = input()
if(x == ans[i]):
print(“Congratulation…Correct Answer…\n”)
else:
print(“Oops!!!Wrong Answer…\n”)
i += 1
inp = input(“Continue(Y/N):”)
if(inp == “n” or inp == “N”):
break;
options()
#This function call will print the options and start the program
options()
Page No 172:
Question 4:
Take a look at the series below:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1 + 2 = 3. Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: previous two numbers are added to get the immediate new number.
ANSWER:
The number of terms of the Fibonacci series can be returned using the program by getting the input from the user about the number of terms to be displayed.
The first two terms will be printed as 1 and 1 and then using ‘for’ loop (n – 2) times, the rest of the values will be printed.
Here, ‘fib’ is the user-defined function which will print the next term by adding the two terms passed to it and then it will return the current term and previous term. The return values are assigned to the variables such that the next two values are now the input terms.
Program:
def fib(x, y):
z = x + y
print(z, end=”,”)
return y, z
n = int(input(“How many numbers in the Fibonacci series do you want to display? “))
x = 1
y = 1
if(n <= 0):
print(“Please enter positive numbers only”)
elif (n == 1):
print(“Fibonacci series up to”,n,”terms:”)
print(x)
else:
print(“Fibonacci series up to”,n,”terms:”)
print(x, end =”,”)
print(y, end =”,”)
for a in range(0, n – 2):
x,y = fib(x, y)
print()
OUTPUT:
How many numbers in the Fibonacci series do you want to display? 5
Fibonacci series up to 5 terms:
1,1,2,3,5,
Page No 172:
Question 5:
Create a menu driven program using user defined functions to implement a calculator that performs the following:
a) Basic arithmetic operations(+,-,*,/)
b) log10(x), sin(x), cos(x)
ANSWER:
a) Basic arithmetic operations
Program:
#Asking for the user input
x = int(input(“Enter the first number: “))
y = int(input(“Enter the second number: “))
#printing the Menu
print(“What would you like to do?”)
print(“1. Addition”)
print(“2. Subtraction”)
print(“3. Multiplication”)
print(“4. Division”)
#Asking user about the arithmetic operation choice
n = int(input(“Enter your choice:(1-4) “))
#Calculation as per input from the user
if n == 1:
print(“The result of addition:”,(x + y))
elif n == 2:
print(“The result of subtraction:”,(x – y))
elif n == 3:
print(“The result of multiplication:”,(x * y))
elif n == 4:
print(“The result of division:”,(x / y))
else:
print(“Invalid Choice”)
b) log10(x), sin(x), cos(x)
Program:
import math
#Providing the Menu to Choose
print(“What would you like to do?”)
print(“1. Log10(x)”)
print(“2. Sin(x)”)
print(“3. Cos(x)”)
#Asking user about the choice
n = int(input(“Enter your choice(1-3): “))
#Asking the number on which the operation should be performed
x = int(input(“Enter value of x : “))
#Calculation as per input from the user
if n == 1:
print(“Log of”,(x),”with base 10 is”,math.log10(x))
elif n == 2:
print(“Sin(x) is “,math.sin(math.radians(x)))
elif n == 3:
print(“Cos(x) is “,math.cos(math.radians(x)))
else:
print(“Invalid Choice”)
Discover more from EduGrown School
Subscribe to get the latest posts sent to your email.