Python Functions - Combo Reviewer (Day 11 of 30 Days of Python)
FUNCTIONS IN PYTHON
- Functions are reusable blocks of code used to perform a task.
- Defined using `def` keyword.
- Function types: no parameters, with parameters, with default values, returning values, and using
*args for variable arguments.
- Functions can also take other functions as arguments.
FUNCTION SYNTAX
```python
def function_name(parameters):
# block of code
return value
```
FUNCTION TYPES
- No Parameters:
```python
def greet():
print("Hello")
```
- With Parameters:
```python
def greet(name):
return "Hello " + name
```
- Returning Values:
```python
def add(a, b):
return a + b
```
- Default Parameters:
```python
def greet(name="User"):
return "Hello " + name
```
- Arbitrary Arguments (*args):
```python
def sum_all(*nums):
return sum(nums)
```
- Function as Argument:
```python
def square(x):
return x * x
def do_something(func, x):
return func(x)
```
KEY POINTS
- Use `return` to send back values.
- Use *args to accept multiple arguments.
- You can pass arguments by position or by keyword (key=value).
QUICK CHECKS
Q: What keyword defines a function in Python?
A: `def`
Q: What happens if a function has no return statement?
A: It returns `None` by default.
Q: Can you pass arguments in any order?
A: Yes, if you use key=value syntax.
Q: How do you allow a function to take any number of arguments?
A: Use `*args`.
PRACTICE SECTION
LEVEL 1
1. Write a function to add two numbers.
2. Write a function to compute the area of a circle.
3. Write `add_all_nums` that sums all given numbers and checks for number types.
4. Convert Celsius to Fahrenheit.
5. Check the season from a given month.
LEVEL 2
1. Count evens and odds in a given range.
2. Write a factorial function.
3. Create functions for mean, median, mode, range, variance, and standard deviation.
LEVEL 3
1. Write `is_prime` to check if a number is prime.
2. Check if all items in a list are unique.
3. Check if all items in a list are of the same type.
4. Check if a variable is a valid Python variable.