2.1. Functions - JulTob/Python GitHub Wiki
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.
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!")
Parameters can be set to a default value.
def increment(a, by = 1)
return a + by
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
def foo(*args)
...
def some_function(stuff, *data)
...
def print(*text):
for t in text:
print(t)
def putData(**kwargs)
print(kwargs["name"])
print(kwargs["age"]
def foo(**data)
print(data["name"])
print(data["age"]
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()
def f(ham: str, eggs: str = 'eggs') -> str:
...
f.__annotations__
Defining a function creates a variable with the same name.
>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'>
program = """list = [1,2,3,4,5]
for i in list:
print(i, i*2)"""
exec(program)