Saturday, August 26, 2023

Python Functions

 Python Functions:

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.. def greet(): print("Hello") print("Good Morning") greet() #**output**: #Hello #Good Morning def add(a,b): c = a+b print(c) #return d add(4,5) #**output**: # 9 def add(a, b): d = a + b return d result = add(6,7) print(result) #**output**: # 13 def add_sub(x,y): c= x+y d= x-y return c,d result1,result2 =add_sub(15,18) print(result1,result2) #**output**: 33 -3 def my_function(Title): print(" Rajani "+ Title ) my_function("Emil") my_function("Tobias") my_function("Linus") #**output**: Rajani Emil Rajani Tobias Rajani Linus def my_function(fname, lname): print(fname + "*****" + lname) my_function("Rishita ", "_Mohanty") #Rishita *****_Mohanty def my_function(*kids): print("The eldest child is " + kids[0]) my_function("Emil", "Tobias", "Linus") #The eldest child is Emil def my_function(child3, child1,child2): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") #The youngest child is Linus def my_function(child3, child2, child1): print("The youngest child is " + child2) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") #The youngest child is Tobias #If the number of keyword arguments is unknown, add a double ** before the parameter name: def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") #His last name is Refsnes #Default Parameter Value #The following example shows how to use a default parameter value. #If we call the function without argument, it uses the default value: def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") def my_function(country = "Norway"): print("I am from " + country) #my_function("Sweden") #my_function("India") #my_function() #my_function("Brazil") #Passing a List as an Argument ''' You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches the function: ''' def my_function(food): for y in food: print(y) fruits = ["apple", "banana", "cherry"] my_function(fruits) #apple #banana #cherry #Return Values def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) #15 #25 #45 ''' The pass Statement function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. ''' def myfunction(): pass

No comments:

Post a Comment