12 Function tricks every Python developer should know
(Source/Credits: https://dev.to/jsdude005/12-function-tricks-every-python-developer-should-know-11p7)
New Python developer should learn these 12 function-related tricks to become good at programming
title: 12 Function tricks every Python developer should know published: true description: New Python developer should learn these 12 function-related tricks to become good at programming tags: Python, beginner, tutorial, codenewbie
I am taking all the examples from the Python learning Android app called Programming Hero
12 function-related exercises/concepts:
- Use parameter
- Use return
- Default parameter value
- Keyword Arguments
- Built-in function
- Use docstring
- Anonymous function
- Access global variable
- return more than one value
- Variable-length argument
- Pass by reference vs value
- use main() function
1. Use Parameter:
Know how to declare parameters. How you can pass values to get a different result based on the parameters
```python def add (a, b): sum = a + b print(sum)
add(2,3) ```
2. Use Return:
Practice how to use the return keyword. So that you can do something with the result. If needed, you can use the result of the function again. ```python def add (a, b): return a + b
x = add(2,3) y = add(5,10) total = add(x,y) print(total) ```
3. Default Parameter:
Learn how can you avoid passing specific parameters. If one or more parameters are not passed, you can have a default value. ```python def add (a, b = 5): return a + b
x = add(2,3) print(x) # 5
y = add(7) print(y) #112
total = add(x,y) print(total) ```
4. Keyword Arguments
If you are not sure about the order of the parameters (arguments), you can pass arguments by their name and you don’t have to maintain their order. ```python def add (a, b): return a + b
x = add(a = 2, b =3) print(x) # 5
y = add(b = 7, a=11) print(y) #16
total = add(b=x,a=y) print(total) ```
5. Built-in function
Python has tons of built-in function. Like min, list, pow, len, etc. Here is the list of all Built-in Functions.
6. Use docstring
Learn how would you write the purpose and special notes about a function. In that case, using docstring is a convention.
A docstring is written right after the function name. It starts with three double quotes and ends with three double quotes as well. A docstring could be written multiple lines as well.
python
def add (a, b):
""" Add two numbers or two strings """
return a + b
7. Anonymous function
An anonymous function could be considered an advanced topic. It is also known as a lambda function. It is a shortcut way to write a function in one line without giving it a proper name. ```python double = lambda x: x * 2
Output: 10
print(double(5)) ```
8. Access global variable
This tricks new developers. You can access external variables. However, if you want to set a value to a variable not declared inside the function or is not a parameter, you will get an exception. ```python c = 5 def add (a, b): c = a + b return c
will get an exception
x = add(12, 23)
use global
def add (a, b): global c c = a + b return c ```
9. return more than one value
In some cases, you will need to return more than one thing from a function. How would you do that?
The answer is: you can use a tuple, list, dictionary, class or, a dataclass. ```python def get_a_lot(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0, y1, y2)
things = get_a_lot(5) ```
10. Variable-length argument
In some cases, you might not know, how many parameters user will pass. In those cases, what will you do? ```python def add_everything(*args): return sum(args)
Calculate the sum
print(add_everything(1,4,5, 75, 112)) ```
11. Mutable Vs Immutable parameters
This is an advanced topic. However, you should check when you pass a variable, list, tuples or a dictionary to a function. What will happen if you change the value and what will happen if you just update one element of the collection?
If you are not sure, read the comment below by Jason.
12. use main() function
The main function has special importance to start an app. You should learn about this. ```python
Define main()
function
def main(): hello() print("This is a main function")
Execute main()
function
if name == 'main': main()
``` If you read up to this point, you should check out the intermediate and advanced level contents in Programming Hero
Comments section
codemouse92
•May 1, 2024
Python does neither. It has names which are bound to values. Values can be either mutable or immutable. This isn't really advanced, so much as unusual, but it is very important to understand when working in Python!
So, in...
``` answer = 42 insight = answer insight = 4
```
...the name
answer
is bound to the value42
.insight
is initially bound to the same value thatanswer
is (names cannot be bound to other names). On the third line,insight
is rebound to the value4
.The behavior you're referring to is actually related to whether the data type being passed is mutable or immutable.
Immutable types seem to behave like pass-by-value because the value cannot be modified.
``` def increment(num): num = num + 1 return num
spam = 5 eggs = increment(spam) print(spam) # 5 print(eggs) # 6
```
In that example,
foo
is passed toincrement()
, so the parameternum
gets bound to the same value asfoo
. This is identical tonum = foo
, by the way. However, an integer is immutable, meaning that value cannot be modified. So,num = num + 1
actually rebinds to a new value,6
, which is returned and bound toeggs
.Mutable data types, on the other hand, seem to behave like "pass-by-reference"...
``` def append_sum(numbers): numbers.append(sum(numbers)) return numbers
spam = [1, 2] eggs = append_sum(spam)
print(spam) # [1, 2, 3] print(eggs) # [1, 2, 3]
```
Lists are mutable. Again, when we pass
spam
to the function, it's the same as if we saidnumbers = spam
;numbers
is now bound to the same value asspam
. However, because that value is mutable, it can be changed directly, which we do with ournumbers.append()
call. Because bothspam
andnumbers
are still bound to the exact same value in memory, both see the mutation.Then, when we return
numbers
, we wind up binding that same value toeggs
as well. Thus,spam
andeggs
are (again) bound to the exact same value in memory.Common immutable data types:
bool
:True
,False
str
(string):"Hello, world!"
int
,float
,complex
tuple
:(1, 2, 3)
bytes
frozenset
Common mutable data types:
list
:[1, 2, 3]
set
:{1, 2, 3}
dict
(dictionary):{1: 'a', 2: 'b', 3: 'c'}
[## Dead Simple Python: Data Typing and Immutability
Jason C. McDonald ・ Jan 17 '19 ・ 19 min read
python
beginners
coding](/codemouse92/dead-simple-python-data-typing-and-immutability-41dm)
Also watch Ned Batchelder's excellent talk on this topic.
jsdude005 Author
•May 1, 2024
WOW. Well explained. Thanks, Jason