0% found this document useful (0 votes)
4 views3 pages

Functions Notes

This document discusses different types of functions in Python including: 1. Required arguments - Functions that require a specific number and type of arguments to be passed to them. 2. Keyword arguments - Functions that allow arguments to be passed by name instead of position. 3. Default arguments - Functions that set default values for optional arguments so they don't need to be passed if the default is desired. 4. Variable length arguments - Functions that allow a variable number of arguments to be passed via the *args syntax.

Uploaded by

pranavr12s22021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Functions Notes

This document discusses different types of functions in Python including: 1. Required arguments - Functions that require a specific number and type of arguments to be passed to them. 2. Keyword arguments - Functions that allow arguments to be passed by name instead of position. 3. Default arguments - Functions that set default values for optional arguments so they don't need to be passed if the default is desired. 4. Variable length arguments - Functions that allow a variable number of arguments to be passed via the *args syntax.

Uploaded by

pranavr12s22021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Function definition

1. A group of related statements that perform a specific task.


2. It is a block of organised, reusable code.
3. It provides better modularity for your application and a high degree of code
reusing

def - The keyword ' def ' that marks the start of a function header.

function name - uniquely identifying the function

parameters - to pass values to a function. They are optional.

: - to mark the end of the function header

docstring - optional documentation string to describe what the function does.

return - optional statement. Used to exit from a function and go back to the
place from where it was called. Also used to return a value from a function

__doc__ - docstring is available to us through print statement through


__doc__ attribute of the function.

# Differences between comment and docstring

Use comments to explain how code works.


Comments are great for leaving notes for people working on your program.
Docstrings provide documentation about functions, classes, and modules.
Use docstrings to teach other developers how to use your program.
...................................................................................
...................

#function demo for greeting


def greet(n):
"This function performs greeting action" #docstring

#print("Hello " + n + ", Good Morning")


#return()

n1=input("Enter a name")
#s=greet(n1) #Function calling
print(greet(n1))
print(greet.__doc__) # giving out the documentation string at runtime

...................................................................................
................

#Function with two arguments


def score(name,totalscore):
#print("name: "+ name + "totalscore: " + totalscore)
print("%s scored %d" %(name,totalscore))
score('Ann',9.5) # Implicit function calling with position of arguments
score(totalscore=9,name='Amrita') #Explicit function calling with names

...................................................................................
......

#Function with one initialized argument


def area(r,pi=3.14):
a=pi*r*r
print("Area of the circle is: " , a)
area(10)# Calling the function with a single value (other is already initialised)

................................................................................

#if-else inside a function


def absolute(num):
if num>=0:
return num
else:
return -num
print(absolute(10))#Function Calling
print(absolute(-200))#Function Calling

...................................................................................
..
#Function with boolean return
def boolean(b):
return bool(b)

result=boolean(2>5)
print("The result is: ",result)

..............................................................................

# Returning Multiple values


def alphanum():
return 'x','t',100,200
print(alphanum()) # printing the result a tuple

a,b,c,d=alphanum() # Unpacking the result tuple into different variables

result=alphanum() #Unpacking the result tuple and printing the result using index
values
print(result[0])
print(result[1])
print(result[2])
print(result[3])

...................................................................................
.........
Function Types

#Required arguments
#Keyword Arguments
#Default Arguments
#Variable length Arguments
.....................................................
#Required arguments
def valuechange(a):
a=10
print("Inside, the value of a is ", a)

# Main Program Code


a=int(input("Enter a number"))
valuechange()#Fn call
print("Outside the fun - valu of a is", a)

...................................................................................
.........
#Keyword Arguments
def studinfo(rollno,name,course):
print("Roll NO : ",rollno)
print("Name : ",name)
print("Course : ",course)

#Fun call
studinfo(course="UG",rollno=50,name='John')

..............................................................................
#Default Arguments
def studinfo(rollno,name,course="UG"):
print("Roll NO : ",rollno)
print("Name : ",name)
print("Course : ",course)

#Fun call
studinfo(rollno=51,name='Jack')

......................................................................

#Variable length Arguments


def varlen(*arg):
print("Result:", )
for i in arg:
print(i)

varlen(100,35,87,5000) #Fn Call

Common questions

Powered by AI

The design and implementation of reusable code functions foster better software development practices by encouraging modularity, reducing redundancy, and facilitating easier debugging and maintenance. Reusable functions allow developers to abstract common patterns and behaviors into distinct units that can be independently developed, tested, and updated. This leads to streamlined workflows, with changes needing to be made in a single location rather than multiple, edifying DRY principles (don't repeat yourself). They also improve collaboration as functions with clear documentation can be effortlessly integrated and adapted by different team members .

Returning multiple values from a function is advantageous as it allows the encapsulation and simultaneous return of different pieces of related data without the need for complex data structures. This method can enhance performance and simplicity when the function's output directly relates to the returned values. However, when more complex relationships or data manipulations are needed, using structures like dictionaries or objects might provide better organization and clarity, as they can include descriptive keys or attributes for better context .

Printing direct outputs from a function serves immediate feedback or display purposes but ties the function's usability to a specific context, limiting flexibility in reusing the output elsewhere in code. Returning values, on the other hand, gives the caller full control over how to handle the output, allowing further processing, storage, or conditional actions externally, promoting higher modularity and reusability of functions. While returning values incurs more upfront planning in coding, it typically results in cleaner design and broader application potential .

Keyword arguments improve code readability and usability by explicitly associating argument values with parameter names when calling functions. This reduces ambiguity, making code easier to understand and maintain, especially when functions have many parameters. It also allows for greater flexibility in function calls by not requiring a specific order of parameters .

Boolean return types are crucial in controlling program execution flow, frequently used within conditional constructs to make decisions or trigger different branches of code. They typically result from evaluations or checks performed within the function, determining whether the state of certain variables or conditions meets predefined criteria. This guides the program to respond with forks in execution, enabling dynamic and adaptable behaviors based on the input or current state .

Scope confines variables to specific areas of code, such as within a function, limiting their availability outside that function. This prevents unintentional interference or modification from other parts of the codebase, thus promoting code encapsulation and easier debugging. However, it can also lead to inefficiencies if variables needed across several functions are constantly passed as arguments instead of being stored globally when appropriate. Developers need to balance between effective scope management and practical considerations for code reuse and performance .

Default arguments allow functions to be more flexible by letting them be called with fewer arguments, providing default values when certain arguments are not specified. This enhances modularity by enabling a single function definition to handle a broader range of cases without requiring overloads or additional functions. As a result, code reuse is improved because the same function can be used in different contexts without modification, simplifying maintenance and reducing redundancy .

Required arguments in Python enforce strictness and can lead to runtime errors if not supplied, ensuring that necessary data is provided for the function to operate. This enforces discipline but may reduce robustness if arguments are frequently missing. Default arguments, by contrast, automatically fill in gaps with predefined values, preventing certain types of errors and increasing flexibility. However, they can introduce subtle bugs if defaults are inappropriate for particular contexts, requiring careful design to balance robustness and convenience .

Docstrings are more beneficial than comments when the focus is on documenting the purpose and use of a function for other developers. They serve as a form of API documentation that can be extracted and displayed by tools, aiding developers in understanding how to utilize the function correctly. Unlike comments, which explain code logic and are meant for developers reading the code internally, docstrings are accessible at runtime through the __doc__ attribute and are intended for users of the code rather than its authors .

Python does not support traditional function overloading found in other languages. However, similar effects can be achieved using default and variable-length arguments to accommodate varying numbers and types of inputs. Default arguments provide baseline values when certain arguments are not supplied, while variable-length arguments (using *args and **kwargs) allow functions to accept any number of positional or keyword parameters. This approach provides flexibility and can simulate overloading by processing inputs based on type or count within the function body itself .

You might also like