Functions
Functions:
Set of blocks which can be reused for making coding efficient and readable.
# Functions in Python
# # Functions are defined using the def keyword
# # Functions can take any number of arguments
# # Functions can return any number of values
# # Functions can return any type of object
# # Functions can be nested
# # Functions can be used as arguments to other functions
# # Functions can be used as elements in lists
# # Functions can be used as elements in tuples
# # Functions can be used as elements in dictionaries
# # Functions can be used as elements in sets
# # Functions can be used as elements in frozensets
# # Functions can be used as elements in arrays
# No parameters
def my_function():
print("Hello World")
return 0
my_function()
# single parameter
def print_my_name(name):
print("Hello " + name)
return 0
print_my_name("Puneet")
# multiple parameters
def print_my_full_name(first_name, last_name):
print("Hello " + first_name + " " + last_name)
return 0
print_my_full_name("Puneet", "Kumar Singh")
# Scope of varaibles. Through local and global variables
# local variable red scoped to function alone.
def print_color_red():
color = "red"
print(color)
return 0
print_color_red()
# global variable
color="blue"
print(color)
print_color_red()
# print(color) # it will print red because color is defined in this scope
def print_numbers(highestNumber, lowestNumber):
print("Highest number is: " + str(highestNumber))
print("Lowest number is: " + str(lowestNumber))
return 0
print_numbers(highestNumber=10, lowestNumber=1)
# returning value from function
def multiply_numbers(num1, num2):
return num1 * num2
solution = multiply_numbers(10, 20)
print("The solution is: " + str(solution))
# supplying list as parameter
def print_list(list_of_numbers):
for number in list_of_numbers:
print(number)
return 0
print_list([1, 2, 3, 4, 5])
# function calling another function
def buy_item(cost_of_item):
return cost_of_item + add_tax_to_item(cost_of_item)
def add_tax_to_item(cost_of_item):
tax_rate = 0.25
tax = cost_of_item * tax_rate
return tax
final_cost = buy_item(100)
print("The final cost is: " + str(final_cost))
# The final cost is: 125.0
Assignment:
"""
Create a function that takes in 3 parameters(firstName, lastName, age) and
returns a dictionary bvased on those values.
"""
def createUserDitionary(firstName, lastName, age):
userDictionary = {
"first_name": firstName,
"last_name": lastName,
"age": age
}
return userDictionary
# Example usage
user_info = createUserDitionary(firstName="Puneet", lastName="Kumar Singh", age=25)
print(user_info)
Comments
Post a Comment