2.1. Functions - JulTob/Python GitHub Wiki

🐍 Functions

def function_Name(Parameters):
def my_function():
    """Do nothing, but document it.
     No, really, it doesn't do anything.
    """
    pass

>>> print(my_function.__doc__)
Do nothing, but document it.
   No, really, it doesn't do anything.

πŸ¦– Processes

A program can be subdivided in processes. And by can I mean should

Inputs>>[Procedure]>>Outputs
def <name> (<parameters>):
    | indectation to same level
    | <expression>… 
    | return <expression>
def inc (number):
    return number+1
def get_name():
  user_name = input("Enter name: ")
  return user_name
def Say_Hi(user):
  print("Hello, ", user)
def main():
  user = get_name()
  Say_Hi(user)

main()

Python programs are modules. Can be imported to other programs.

script.py


print("Hello World!")


🐒 Default Argument Values

Parameters can be set to a default value.

def increment(a, by = 1)
   return a + by

⚠️ Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

Will give

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

🦎 Variable number of arguments

def foo(*args)
...

def some_function(stuff, *data)
...

def print(*text):
  for t in text:
    print(t)

🐊 Arbitrary arguments

def putData(**kwargs)
   print(kwargs["name"])
   print(kwargs["age"]

def foo(**data)
   print(data["name"])
   print(data["age"]

πŸ¦– Defining Functions

def fib(n):    # write Fibonacci series up to n
     """Print a Fibonacci series up to n."""
     a, b = 0, 1
     while a < n:
         print(a, end=' ')
         a, b = b, a+b
     print()

πŸ‰ Function Annotations

def f(ham: str, eggs: str = 'eggs') -> str: 
   ...
f.__annotations__

⬜️ Extra info

Defining a function creates a variable with the same name.

>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'>

Execution of code snippets

program = """list = [1,2,3,4,5]
for i in list:
   print(i, i*2)"""

exec(program)
⚠️ **GitHub.com Fallback** ⚠️