YouTip LogoYouTip

Python3 Function

# Python3.x Python3 Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse. You already know that Python provides many built-in functions like `print()`. But you can also create your own functions, these are called user-defined functions. * * * ## Defining a Function You can define a function with the functionality you want. Here are the simple rules: * Function blocks begin with the keyword **def**, followed by the function name and parentheses **()**. * Any input parameters and arguments must be placed within the parentheses. You can define parameters within the parentheses. * The first statement of the function can optionally be a docstring β€” used to store the function description. * The function body starts with a colon `:` and is indented. * **return ** exits the function, optionally passing back a value to the caller. A return statement without an expression is equivalent to returning `None`. !(#) * * * ### Syntax Python defines a function using the `def` keyword. The general format is: ```python def function_name( parameter_list ): function_body By default, parameter values and parameter names are matched in the order they are defined in the function declaration. ### Example Let's use a function to print "Hello World!": ```python #!/usr/bin/python3 def hello() : print("Hello World!") hello() A more complex application, with parameter variables in the function: ## Example (Python 3.0+) Compare two numbers and return the larger one: ```python #!/usr/bin/python3 def max(a, b): if a > b: return a else: return b a = 4 b = 5 print(max(a, b)) The output of the above example is: 5 ## Example (Python 3.0+) Function to calculate area: ```python #!/usr/bin/python3 # Function to calculate area def area(width, height): return width * height def print_welcome(name): print("Welcome", name) print_welcome("") w = 4 h = 5 print("width =", w, " height =", h, " area =", area(w, h)) The output of the above example is: Welcome width = 4 height = 5 area = 20 * * * ## Function Calls Defining a function gives it a name, specifies the parameters it contains, and the code block structure. Once the basic structure of a function is finalized, you can execute it from another function or directly from the Python command prompt. The following example calls the **printme()** function: ## Example (Python 3.0+) ```python #!/usr/bin/python3 # Define function def printme( str ): # Print any string passed in print(str) return # Call the function printme("I'm calling the user-defined function!") printme("Calling the same function again") The output of the above example is: I'm calling the user-defined function! Calling the same function again * * * ## Parameter Passing In Python, types belong to objects, objects have different types, and variables have no type: ```python a = [1,2,3] a = "" In the code above, **[1,2,3]** is a List type, **""** is a String type, and the variable `a` has no type. It is simply a reference (a pointer) to an object, which can point to a List type object or a String type object. ### Mutable and Immutable Objects In Python, strings, tuples, and numbers are immutable objects, while lists, dictionaries, etc., are mutable objects. * **Immutable type:** After assigning a variable `a = 5`, reassigning `a = 10` actually creates a new int value object 10 and makes `a` point to it. The original 5 is discarded. This is not changing the value of `a`, but rather creating a new `a`. * **Mutable type:** After assigning a variable `la = [1,2,3,4]`, reassigning `la = 5` changes the third element of the list `la`. The list `la` itself is not moved; only a part of its internal values is modified. Python function parameter passing: * **Immutable type:** Similar to C++'s pass-by-value, such as integers, strings, tuples. For example, `fun(a)` only passes the value of `a`, without affecting the `a` object itself. If `a` is modified inside `fun(a)`, a new `a` object is created. * **Mutable type:** Similar to C++'s pass-by-reference, such as lists, dictionaries. For example, `fun(la)` passes `la`
← Python3 Data StructurePython3 Loop β†’