Programming
Python Programming Essentials
Function Overview
Definition of a Function: A block of organized, reusable code that performs a single, related action.
Benefits:
Enhances modularity of applications.
High degree of code reusability.
Defining a Function
Function blocks start with the keyword
deffollowed by the function name and parentheses( ).Input Parameters:
Arguments can be placed within the parentheses.
Can define parameters inside parentheses.
Code Block:
Begins with a colon
:and must be indented.
Return Statement:
return [expression]exits a function and can return an expression to the caller.A return with no arguments returns None.
Defining and Calling a Function
Example:
def greet: print("hi") greet();
Function with Parameter
Example:
def greet(name): print("hi" + name) greet('John');
Function with Default Value Parameters
Example:
def greet(name="John Doe"): print("hi" + name) greet(); greet("Ana"); def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1="Emil", child2="Tobias", child3="Linus")
Function with Return
Example:
def greet(): return "Hello" print(greet()); def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) def myfunction(): pass
Arbitrary Arguments, *args
Definition: Allows you to pass a variable number of arguments.
Example:
def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")Note: Use a
*before the parameter name to receive a tuple of arguments.
Arbitrary Arguments, **kwargs
Definition: Allows passing a variable number of keyword arguments.
Example:
def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname="Tobias", lname="Refsnes")Note: Use
**before the parameter name to receive a dictionary of arguments.
Passing a List as an Argument
Example:
def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)You can send any data type (string, number, list, dictionary, etc.) to a function, and it will be treated as the same data type inside the function.
Recursion
Definition: A function that calls itself.
Example:
def factorial(x): if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num))
Factorial Calculation Steps
Diagram of recursive calls:
factorial(3)--> 3 *factorial(2)factorial(2)--> 2 *factorial(1)factorial(1)--> returns 1Returns through the levels:
Result: 3 * 2 * 1 = 6 .
Factorial Calculations Notation
Factorial Notation:
4! = 4 * 3!3! = 3 * 2!2! = 2 * 1!1! = 1.