Python Functions is a block of statements that does the specific task, and it can return or can not return the result depending on implementation. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse the code contained in it repeatedly. AdvantagesIt increases the code reusability.
List of countriesprint("INDIA") print("USA") print("GERMANY") print("UK\n") print("INDIA") print("USA") print("GERMANY") print("UK\n") print("INDIA") print("USA") print("GERMANY") print("UK\n")
Function without argumentdef greetings(): print("INDIA") print("USA") print("GERMANY") print("UK\n") greetings() greetings()
Find the area of a rectangle or squarelength = 5 width = 10 area_of_rectangle_1 = length*width print("area: ", area_of_rectangle_1) length = 15 width = 10 area_of_rectangle_2 = length*width print("area: ", area_of_rectangle_2) length = 20 width = 10 area_of_rectangle_3 = length*width print("area: ", area_of_rectangle_3)
Area of rectangle and square using a function with argumentsdef area_of_rectanle_square(length, width): area = length*width print(f"area is {area}") area_of_rectanle_square(5,10) area_of_rectanle_square(15,10) area_of_rectanle_square(20,10) area_of_rectanle_square(30,30)
Area of rectangle and square using a function with arguments and return typedef area_of_rectanle_square(length, width): area = length*width return area area = area_of_rectanle_square(5,10) print(f"area is {area}")
Area of rectangle and square using a function with arguments and multiple returnsdef area_and_perimeter(length, width): area = length*width perimeter = 2*(length + width) return area, perimeter area, perimeter = area_and_perimeter(5,10) print(f"area: {area} and perimeter: {perimeter}")