NCERTCh 7Free

Functions

🎓 Class 11📖 Computer Science📖 10 notes🧠 15 Q&A⏱️ ~15 min
Flow of ControlChapter 7 of 11Strings

FunctionsStudy Notes

NCERT-aligned · 10 notes · 3 shown free

Introduction

Explanation

Introduction

In programming, as problems grow more complex, the number of lines in a program increases significantly. This makes the program bulky and difficult to manage or debug. To handle such complexity effectively, programs are divided into smaller, manageable parts known as functions. Functions help in breaking down a large program into smaller modules, each performing a specific task. This modular approach not only makes the program easier to understand but also facilitates code reuse and better organization. Consider a real-world example of a company manufacturing tents as per user requirements. The tent has a cylindrical shape with a conical top. To calculate the selling price, the company needs to perform several tasks such as accepting user inputs for height, radius, and slant height, calculating the canvas area, and then computing the cost based on the canvas area and unit price. Writing a single program to handle all these tasks without modularity would be cumbersome. Instead, dividing the program into functions for each task simplifies the process. This chapter introduces the concept of functions in Python programming. It explains how to define and call functions, the use of parameters and arguments, the scope of variables, and the return statement. It also covers types of functions, including built-in and user-defined functions, and how to use modules to extend Python's functionality. Understanding functions is fundamental to writing efficient, readable, and maintainable code.

  • Complex programs become bulky and hard to manage without modularity.
  • Functions divide programs into smaller, manageable parts.
  • Functions promote code reuse and better organization.
  • Example: Tent manufacturing program requiring multiple calculations.
  • Functions help in breaking down tasks like input, calculation, and output.
  • Python supports functions as fundamental building blocks.
  • 📌 Function: A named group of instructions that perform a specific task.
  • 📌 Modularity: Dividing a program into smaller parts for easier management.
  • 📌 Code Reuse: Using the same code multiple times to avoid redundancy.

Functions: Definition and Calling

Explanation

Functions: Definition and Calling

A function in Python is defined using the 'def' keyword followed by the function name and parentheses which may contain parameters. The function body contains the statements that perform the intended task. Once defined, a function can be called or invoked by its name followed by parentheses, optionally passing arguments. For example, to calculate the surface area of the conical part of a tent, a function can be defined that takes the radius and slant height as parameters and returns the calculated area. Calling this function with specific values will execute the code inside the function and return the result. Defining functions helps in organizing code logically and makes it reusable. Instead of writing the same code multiple times, the function can be called wherever needed. This reduces code redundancy and errors. Python functions can have zero or more parameters, and the number of arguments passed during the call should match the number of parameters unless default values are provided. The chapter also illustrates the use of functions with the tent example, where functions are defined to calculate areas of cylindrical and conical parts separately and then used to compute the total canvas area and cost.

  • Functions are defined using 'def' keyword followed by function name and parentheses.
  • Function body contains the code to perform the task.
  • Functions are called by their name with parentheses and optional arguments.
  • Functions help in code reuse and modularity.
  • Parameters are placeholders for values passed during function call.
  • Number of arguments should match the number of parameters unless defaults exist.
  • 📌 Function Definition: Using 'def' to create a function.
  • 📌 Function Call: Invoking a function by its name.
  • 📌 Parameter: Variable in function definition to accept values.

Parameters and Arguments

Explanation

Parameters and Arguments

Parameters are variables listed in the function definition that receive values when the function is called. Arguments are the actual values passed to these parameters during the function call. Python supports different types of arguments such as posi

Practice QuestionsFunctions

Includes NCERT exercise questions with answers

Q1.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:

Solution: We need to create a function named login(uid, pwd) which checks the userid and password. The function should allow three attempts. If the user enters the correct userid "ADMIN" and password "St0rE@1", display "login successful". If three wrong attempts are made, display "account blocked". Sample Python code: ```python attempts = 0 while attempts < 3: uid = input("Enter user ID: ") pwd = input("Enter password: ") if uid == "ADMIN" and pwd == "St0rE@1": print("login successful") break else: print("Wrong credentials") attempts += 1 else: print("account blocked") ``` Explanation: - The program uses a loop to allow up to three attempts. - If correct credentials are entered, it prints "login successful" and breaks the loop. - If three wrong attempts are made, it prints "account blocked".

Explanation:

The function login(uid, pwd) checks the credentials. The program allows three attempts. On correct credentials, it prints "login successful" and exits. After three failed attempts, it prints "account blocked".

MediumNCERT
Q2.2. XYZ store plans to give 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:

Solution: We need to write a function that accepts shopping amount and membership status, calculates the discount based on the criteria, and returns the net payable amount. Sample Python code: ```python def calculate_discount(amount, is_member): discount = 0 if amount >= 500 and amount < 1000: discount = 0.05 * amount elif amount >= 1000 and amount < 2000: discount = 0.08 * amount elif amount >= 2000: discount = 0.10 * amount if is_member: discount += 0.05 * amount net_payable = amount - discount return discount, net_payable # Example usage amount = float(input("Enter shopping amount: ")) member_input = input("Are you a member? (yes/no): ") is_member = member_input.lower() == 'yes' discount, net_amount = calculate_discount(amount, is_member) print(f"Discount: {discount}") print(f"Net amount payable: {net_amount}") ``` Explanation: - The function checks the amount range and applies the corresponding discount. - If the customer is a member, an additional 5% discount is added. - Finally, net payable amount is calculated by subtracting discount from total amount.

Explanation:

The function calculates discount based on amount slabs and membership. It returns discount and net payable amount. The program then displays these values.

MediumNCERT
Q3.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:

Solution: This is an open-ended question requiring the creation of a program with user defined functions to help toddlers learn two and three-letter words and addition of single digit numbers. Approach: - Create functions to display two and three-letter words. - Create functions to generate simple addition problems with single digit numbers. - Use loops and input to interact with children. Sample outline: ```python def display_two_letter_words(): words = ['an', 'at', 'in', 'on', 'up'] for word in words: print(word) def display_three_letter_words(): words = ['cat', 'dog', 'sun', 'hat', 'bat'] for word in words: print(word) def addition_quiz(): import random a = random.randint(0,9) b = random.randint(0,9) print(f"What is {a} + {b}?") answer = int(input()) if answer == a + b: print("Correct!") else: print(f"Incorrect. The answer is {a + b}") # Example usage print("Two letter words:") display_two_letter_words() print("Three letter words:") display_three_letter_words() addition_quiz() ``` Explanation: - The functions help children learn words and practice addition interactively. - The program can be extended with more words and questions as per curriculum.

Explanation:

The program uses user defined functions to display words and quiz addition. It is designed to be interactive and age-appropriate.

MediumNCERT
Q4.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:

Solution: This question explains the Fibonacci sequence and expects a program or explanation to generate the sequence. Sample Python code to generate first n Fibonacci numbers: ```python def fibonacci(n): fib_series = [1, 1] while len(fib_series) < n: next_num = fib_series[-1] + fib_series[-2] fib_series.append(next_num) return fib_series[:n] # Example usage n = 10 print(fibonacci(n)) ``` Explanation: - Start with 1 and 1. - Each next number is sum of previous two. - The function returns the first n numbers of the Fibonacci sequence.

Explanation:

The Fibonacci sequence is generated by adding the last two numbers to get the next. The program implements this logic to generate the sequence.

EasyNCERT
Q5.5. Create a menu driven program using user defined functions to implement a calculator that performs the following: a) Basic arithmetic operations(+,-,*,/) b) log (x), sin(x), cos(x)

Answer:

Solution: We need to create a menu driven calculator program with user defined functions for basic arithmetic and some trigonometric/logarithmic functions. Sample Python code: ```python import math def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y != 0: return x / y else: return 'Error: Division by zero' def logarithm(x): if x > 0: return math.log10(x) else: return 'Error: log undefined for non-positive numbers' def sine(x): return math.sin(math.radians(x)) def cosine(x): return math.cos(math.radians(x)) while True: print("Menu:") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. log(x)") print("6. sin(x)") print("7. cos(x)") print("8. Exit") choice = input("Enter choice: ") if choice == '8': break if choice in ['1','2','3','4']: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print("Result:", add(num1, num2)) elif choice == '2': print("Result:", subtract(num1, num2)) elif choice == '3': print("Result:", multiply(num1, num2)) elif choice == '4': print("Result:", divide(num1, num2)) elif choice in ['5','6','7']: num = float(input("Enter number: ")) if choice == '5': print("Result:", logarithm(num)) elif choice == '6': print("Result:", sine(num)) elif choice == '7': print("Result:", cosine(num)) else: print("Invalid choice") ``` Explanation: - The program uses functions for each operation. - It displays a menu and performs the selected operation. - For trigonometric functions, input is taken in degrees and converted to radians.

Explanation:

The program implements a menu driven calculator with user defined functions for arithmetic and trigonometric/logarithmic operations.

MediumNCERT
Q6.1. Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.

Answer:

Solution: Create a function that accepts a number and checks if it is divisible by 7. Sample Python code: ```python def is_divisible_by_7(num): if num % 7 == 0: return True else: return False # Example usage number = int(input("Enter a number: ")) if is_divisible_by_7(number): print(f"{number} is divisible by 7") else: print(f"{number} is not divisible by 7") ``` Explanation: - The function uses modulus operator to check divisibility. - Returns True if divisible, else False.

Explanation:

The function checks if the remainder when divided by 7 is zero. If yes, number is divisible by 7.

EasyNCERT
Q7.2. Write a program that uses a user defined function that accepts name and gender (as M for Male, F for Female) and prefixes Mr/Ms on the basis of the gender.

Answer:

Solution: Create a function that accepts name and gender and returns the name with prefix Mr or Ms. Sample Python code: ```python def prefix_name(name, gender): if gender.upper() == 'M': return "Mr. " + name elif gender.upper() == 'F': return "Ms. " + name else: return name # Example usage name = input("Enter name: ") gender = input("Enter gender (M/F): ") print(prefix_name(name, gender)) ``` Explanation: - The function checks gender and prefixes accordingly. - If gender is not M or F, returns name as is.

Explanation:

The function prefixes Mr or Ms based on gender input and returns the full name.

EasyNCERT
Q8.3. Write a program that has a user defined function to accept the coefficients of a quadratic equation in variables and calculates its determinant. For example : if the coefficients are stored in the variables a,b,c then calculate determinant as b2-4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.

Answer:

Solution: Create a function that accepts coefficients a, b, c and calculates determinant (discriminant) = b^2 - 4ac. Then check if determinant is positive, zero or negative and print the nature of roots. Sample Python code: ```python def determinant(a, b, c): det = b**2 - 4*a*c if det > 0: result = "Roots are real and distinct" elif det == 0: result = "Roots are real and equal" else: result = "Roots are complex" return det, result # Example usage a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) det, nature = determinant(a, b, c) print(f"Determinant: {det}") print(nature) ``` Explanation: - The function calculates determinant. - Based on determinant value, it determines the nature of roots.

Explanation:

Determinant is calculated using formula b^2 - 4ac. Positive determinant means real distinct roots, zero means real equal roots, negative means complex roots.

MediumNCERT