###### tags: Python
# Function
DRY = Donot repeat yourself
Should do one thing really well.
Should return something.
## Parameters
```
def say_hello(name, emoji):
print(f'helllooo {name}{emoji}')
```
## Positional arguments
say_hello('Andrei', ':)')
## Keyword arguments
say_hello(emoji=':)', name='Bibi')
## Default parameters
```
def say_hello(name='Darth Vader', emoji='@@')
print(f'helllooo {name}{emoji}')
```
## Return
```
def sum(num1, num2):
return num1 + num2
```
```
def sum(num1, num2):
def another_func(n1, n2):
return n1 + n2
return another_func(num1, num2)
```
## Docstring
```
def teas(a):
'''
Info: this function tests and prints param a
'''
print(a)
help(test)
print(test.__doc__)
```
## Clean code
```
def is_even(num):
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
```
neater
```
def is_even(num):
if num % 2 == 0:
return True
else:
return False
```
neater
```
def is_even(num):
if num % 2 == 0:
return True
return False
```
neater
```
def is_even(num):
return num % 2 == 0
```
## Arguments / Keyword arguments
Rule: params, *args, default paramters, **kwargs
def super_func(name, *args, 'hi', **kwargs)
### *args = arguments
```
def super_func(*args):
print(args) - type:tupple
returm sum(args)
```
### *kwargs = keyword arguments
```
def super_func(*args, **kwargs):
total = 0
for items in kwargs.values():
total += items
returm sum(args) + total
print(super_func(1,2,3,4,5, num1=5, num2=10))
```
output:30
# Method
be owned by something
ex: 'hello'.capitalize()
# Scope - what variables do I have access to?
#1 - start with local scope
#2 - parent local scope
#3 - global
#4 - built-in python functions
```
a = 1
def parent():
a = 10
def confusion():
return a
return confusion()
print(confusion())
print(a)
```
## non local
```
def outer():
x = 'local'
def inner():
nonlocal x
x = 'nonlocal'
print('inner:', x)
inner()
print('outer:', x)
```