12 Function tricks every Python developer should know

12 Function tricks every Python developer should know

Function tricks every Python developer should know

Originally published by JS Dude at dev.to

I am taking all the examples from the Python learning Android app called Programming Hero

12 function-related exercises/concepts:

  1. Use parameter
  2. Use return
  3. Default parameter value
  4. Keyword Arguments
  5. Built-in function
  6. Use docstring
  7. Anonymous function
  8. Access global variable
  9. return more than one value
  10. Variable-length argument
  11. Pass by reference vs value
  12. 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

def add (a, b):
    sum = a + b


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.

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.

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.

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.

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.

double = lambda x: x * 2

Output: 10


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.

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.

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?

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.

# Define main() function
def main():
  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

Originally published by JS Dude at dev.to


Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

python web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Hire Python Developers India

Looking to build robust, scalable, and dynamic responsive websites and applications in Python? At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, we constantly endeavor to give you exactly what you need. If you need to...

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...