__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------==================================================================================="""
PART -1===================================================================================
Topics to be covered in today's class:
--> What is purpose of function ?
--> Types of functions
--> Non recursive function
--> recursive function
"""
"""
The purpose of a function is code re-usability
Once the basic structure of a function is finalized,
you can execute by calling it from another function or directly from the Python shell
Function Syntax:
===============
def func_name([arguments]):
function_suite
return [value/values]
Types of functions :2 (1. Non-recursive functions & 2. Recursive function) """
"""
Non recursive functions
1. function without arguments
2. functions with arguments/ positional arguments/ Required arguments
3. functions with Default arguments
4. functions with Variable-length arguments (* args)
5. functions with Keyword arguments (**args) / (**kw_args)
******* Not define: functions with Keyword based arguments
"""
'''
Following is an example to call the printme() function −
'''
""" function without arguments """
# print("Narendra")
# print("Surendra and Aruna")
# print(" *******")
# print("Narendra")
# print("Surendra and Aruna")
# print(" *******")
# print("Narendra")
# print("Surendra and Aruna")
# print(" *******")
# print("Narendra")
# print("Surendra and Aruna")
# print(" *******")
# print("Narendra")
# print("Surendra and Aruna")
# print(" *******")
def print_my_info(): # Function without arguments # function definition
print("Narendra")
print("Surendra and Aruna")
print(" *******")
# print_my_info() # calling function
# print_my_info() # the purpose of function is code re-usability
# print_my_info()
# print_my_info()
""" 2. Function with arguments/ positional arguments/ required arguments"""
def gen_email(first_name, last_name):
print(first_name+"_"+last_name+"@"+"brtechnosoluions.com")
# Now you can call printme function
# gen_email("Boyina", "narendra") # programmer friendly
# gen_email("nanditha", "g") # programmer friendly
# gen_email("raahi", "faraz") # programmer friendly
# gen_email("raahi") # TypeError: missing 1 required positional argument: 'last_name'
# first_name = input("Enter first name: ")
# last_name = input("Enter last name : ")
# gen_email(first_name, last_name) # user friendly
'''
Function with Arguments also known as Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the "function call" should match exactly with the "function definition".
'''
def print_me(subbu, venkt, sujana): # Function definition is here
"""This prints a passed string into this function"""
print(subbu, venkt, sujana)
# Now you can call printme function
# print_me(12, 23, 22)
# print_me(3, 5)
'''
OUTPUT:
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 3 argument (2 given)
'''
'''
Function with Default Arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
The following example gives an idea on default arguments,
it prints default age if it is not passed
'''
name ="nanditha" # name is a variable
def print_info(name, age=34): # Function definition is here
"""This prints a passed info into this function"""
print("Name: ", name)
print("Age :", age,"year/s")
# # Now you can call printinfo function
# print_info()
# print_info("Narendra")
# print_info("Mahalakshmi", 4)
# print_info("Surendra",36)
# print_info("kruthika")
def maha(c, d, a=24, b=10):
"""
this function
"""
print(a, b, c, d)
# maha()
# maha(12, 21)
# maha(3, 6, 1, 9)
'''
Keyword based Arguments
Keyword based 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.
This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
'''
# # Function definition is here
def printinfo(sal, name, age, x):
"This prints a passed info into this function"
print("Name: ", name)
print("Sal: ", sal)
print("Age :", age)
print("x value is: ", x)
# # Now you can call printinfo function
# print(45000,"venkat", 35, 4567)
# printinfo(45000, x=22, age=27, name="Narendra")
# def addtion(a,b):
# print(a+b)
#
# addtion(2,3)
"""
Function with Variable-length Arguments :
If you want to take undefined number of inputs from the user then you have to use "Function with Variable-length Arguments"
Syntax :
def function_name([formal_args,], *var_args ):
function_docstring
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the value/s of all non-keyword variable arguments.
This tuple remains empty if no additional arguments are specified during the function call.
Following is a simple example −
"""
# Function definition is here
def printinfo(arg1, *arg_2):
"""
this function performs variable length arguments
other than 1st argument remaining values will be stored in tuple
"""
print("arg1 value is: ", arg1)
print("arg2 value is: ", arg_2)
# for var in var_tuple:
# print("Var_tuple arg is", var)
# return
# Now you can call printinfo function
# printinfo() # TypeError: printinfo() missing 1 required positional argument: 'arg1'
# printinfo(10)
# printinfo(60, 70)
# printinfo(50, 60, 70)
# printinfo(50, 60, 279, "Narendra", 67.87)
def sample_calculator(a=0, *var_tuple):
print(a, var_tuple)
# calculator addition
for element in var_tuple: # where b is tuple of values provided by user
a = a + element
print(a)
# calculator multiplication
for element in var_tuple:
a = a * element
print(a)
# sample_calculator(2, 3, 2, 5)
#===================================================================================
PART -2===================================================================================__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> Function with keyword arguments
--> Assignments
"""
"""
Function with keyword arguments
Syntax for a function with non-keyword variable arguments is given below −
def function_name([formal_args],[*var_rgs], **kw_args):
function_docstring
function_suite
return [expression]
order: passing arguments while defining a function.
=====
def func_name(positional_args, default_args, *args, **kwargs):
doc_string
function_suite
:return
"""
def kw_fun(*venkat, **nanditha):
print(venkat, nanditha)
num_list = [1, 2, 3] # initialization
num_tuple = (4, 5, 6) # initialization
d = {'a': 7, 'b': 8, 'c': 9} # initialization
# kw_fun() # calling function
# kw_fun(11, 2.2, "Narendra") # (11, 2.2, 'Narendra') {}
# kw_fun(name="narendra", designation="Technical lead", exp=10.8) # () {'a': 1, 'c': 3, 'b': 2}
# kw_fun(a=1, b=2, c=3.5, zzz="hi") # () {'a': 1, 'c': 3.5, 'b': 2, 'zzz': 'hi'}
# kw_fun(1, 2.5, "narendra", a=1, b=2.5, c="Narendra")
# kw_fun(*num_list, **d) # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8} if user provides in list of elements still it takes into tuple
# kw_fun(*num_tuple, **d) # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8} if user provides in tuple of elements still it takes into tuple
# kw_fun(1, 2, *num_tuple)
# kw_fun(q="winning", **d)
# kw_fun(1, 2, *num_tuple, q="winning", **d)
# kw_fun(1, 2, *num_list, *num_tuple, q="winning", **d )
#
# kw_fun(1, 2, *num_tuple, q="winning", **d, *num_list)
# positional_args, default_args, *variable_len_args, **kwargs
def sujana(narendra, subhashini, ganesh=10, *priyanka, **rindha):
print(narendra, subhashini, ganesh, priyanka, rindha)
# sujana(2, 5, 7, 19, 2.2, 15, "venkat", age=40, salary=165000, exp=5)
"""
*********************** Assignments *******************************
"""
""" Let's create a real-world example using a function to manage a restaurant order
This function will include a required argument for the dish name,
default argument, additional positional arguments for the side dishes,
and keyword arguments for optional parameters like special requests or dietary preferences """
def place_order(Main_dish_name, water="general_water", *side_dishes, **special_requests):
# Print the required dish name
print(f"Main Dish: {Main_dish_name}")
print(water)
# Print any additional side dishes
if side_dishes:
print("Side Dishes:")
for side in side_dishes:
print(f" - {side}")
else:
print("No side dishes ordered.")
# Print any special requests
if special_requests:
print("Special Requests:")
for key, value in special_requests.items():
print(f" - {key}: {value}")
else:
print("No special requests.")
# calling function
# place_order("Chiken fry piece biryani family pack",
# "Mineral water", # default argument
# "panner Naan", # Side Dish 1
# "panner butter masala", # Side Dish 2
# "crispy prawns fry", # Side Dish 3
# omlet="half boil", # Special request
# extra_lemon="Please add extra lemon slices" # Special request
# )
"""
small Contact Book application
Add Contact: Adds a new contact by taking the name and phone number as inputs.
View Contacts: Displays all contacts in the contact book.
Search Contact: Allows you to search for a contact by name.
Delete Contact: Deletes a contact by name.
This is a simple command-line contact book.
"""
# Basic Contact Book
contacts = {}
# Function to add a contact
def add_contact(name, phone):
if name in contacts:
print(f"{name} already exists in the contact book.")
else:
contacts[name] = phone
print(f"Contact {name} added successfully.")
# Function to view all contacts
def view_contacts():
if contacts:
print("\nContact List:")
for name, phone in contacts.items():
print(f"Name: {name}, Phone: {phone}")
else:
print("No contacts available.")
# Function to search for a contact
def search_contact(name):
if name in contacts:
print(f"Name: {name}, Phone: {contacts[name]}")
else:
print(f"{name} not found in the contact book.")
# Function to delete a contact
def delete_contact(name):
if name in contacts:
del contacts[name]
print(f"{name} has been deleted from the contact book.")
else:
print(f"{name} not found in the contact book.")
# Main menu
def menu():
while True:
print("\n--- Contact Book Menu ---")
print("1. Add Contact")
print("2. View All Contacts")
print("3. Search Contact")
print("4. Delete Contact")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
name = input("Enter contact name: ")
phone = input("Enter contact phone number: ")
add_contact(name, phone)
elif choice == '2':
view_contacts()
elif choice == '3':
name = input("Enter the name to search: ")
search_contact(name)
elif choice == '4':
name = input("Enter the name to delete: ")
delete_contact(name)
elif choice == '5':
print("Exiting contact book. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the contact book menu
# menu()Author: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment