← Cheat Sheets

Python Functions, Classes and Errors

Structure code with functions and classes.

# Python Functions, Classes and Errors

Structure code with functions and classes.

```python
def greet(name, greeting="Hi", *args, **kwargs):
    """Docstring."""
    return f"{greeting} {name}"

square = lambda x: x * x

from dataclasses import dataclass
@dataclass
class Point:
    x: float
    y: float = 0.0
    def dist(self): return (self.x ** 2 + self.y ** 2) ** 0.5

class Dog(Animal):
    def __init__(self, name):
        super().__init__(name)

try:
    risky()
except (ValueError, KeyError) as e:
    print(e)
except Exception:
    raise
else:
    print("ok")
finally:
    print("always")
```