Python-08

/

/

/

python/08-custom-functions

Create Custom Functions in Python

Let's dive into one of the most essential concepts in programming: Functions. They enable you to reuse code, making your programs cleaner, more organized, and easier to maintain.

Python-08

/

/

/

python/08-custom-functions

Create Custom Functions in Python

Let's dive into one of the most essential concepts in programming: Functions. They enable you to reuse code, making your programs cleaner, more organized, and easier to maintain.

Lesson Objectives

  • Why do we need to reuse code?

  • What is a Function and how to create it?

  • Create Function with Arguments, Parameters and Returning Value.

Are you Ready?

Summary

The next key concept in Python

It's time to talk about Functions in python.

Functions allow you reuse code by wrapping it in a container that can be easily reused. This is an absolute must for anyone looking to write clean and efficient code.

If you start copy-pasting your code, then you are doing something wrong…

Programming is all about efficiency and that means reusing your code whenever possible. So, if you catch yourself copying code, take a step back and think how can you make it into a reusable function.

  • Take your piece of code

  • Wrap it in a function

  • Give it a Name

  • And then call this name to reuse

Sometimes you might have minor differences you would want to change. And that's where arguments come to rescue.

Arguments let you customize a function's behavior, acting as dynamic inputs for each use.

When you create functions, you can specify arguments that can be provided when you use that function.

This way you will dynamically provide different data to execute with your reusable code.


Think of Python's built-in print()function.

It doesn't always print the same message, does it? Instead, you specify an argument when you use it. And you can achieve the same with you custom functions too.

Let's look into the syntax so you understand how it actually works.

Basic Syntax: Functions

Let's start with the basics.

Here is how to define a simple function and call it to trigger the code inside of it:

# Define a function
def say_hello():
    print("Hello, BIM World!")

# Call the function
say_hello()
  • You create a function by using def keyword (stands for 'define')

  • Provide a name of your function

  • Add Parenthesis for Arguments (can be empty)

  • And your code is written as a code block (with identation)

And that's a simple function.

Calling a Function

When you define a function, it's just a template.

You have to "call" the function to execute it. For example:

# Define and call the function
def say_hello():
    print("Hello, BIM World!")

say_hello()
say_hello()
say_hello()

This will print "Hello, BIM World!" three times.

Adding Arguments to a Function

If you would want to add arguments to your function, you can specify a name of your arguments inside parenthesis. This will act as a variable that can be reused inside your function.

For Example:

# Function with arguments
def greet(name):
    print("Hello, {}!".format(name))

# Call the function with different arguments
greet("Erik")
greet("Kristina")
greet("Ricky")
greet("Klaus")

Now we can use the same function, but provide different names.

Using Default Arguments

You also have an option to specify a default value for your arguments.

This way you can also execute your function without providing any arguments at all.

# Function with a default argument
def greet(name="Erik"):
    print("Hello, {}!".format(name))

# Call the function
greet()  # Outputs: Hello, Eric!
greet("Kristina")  # Outputs: Hello, Kristina!
Parameters vs. Arguments

Also, you will hear a lot that people use Parameters and Arguments very similar. Let me break down the difference

  • Parameters: Variables defined in the function definition in parenthesis, which is used inside the function itself.

  • Arguments: Actual values passed when calling the function.

Overall they refer to the same thing, but in different context.

Returning Values from a Function

The next thing you need to know is that you can return values from your functions.

Let's say you want to provide 2 numbers and add them together. You also want to display the equation in the console and get the results.

Here is how you would do that with the function:

# Function that returns a value
def add_numbers(a, b):
    total = a + b
    return total

# Use the returned value
result = add_numbers(5, 10)
print(result)  # Outputs: 15

This way you can call your function and assign the result to another variable.

Functions Example

Alright let's summarize what we've learnt.

Let's create a function to read data from a dictionary of rooms or areas, calculate the square area, and then display results in a console.

I'm going to call this function spatial_calculator and make it like this:

def spatial_calculator(dict_elements, spatial_type):
    print('\n' * 5)
    print('CALCULATE {}S:'.format(spatial_type.upper()))

    for name, sizes in dict_elements.items():
        L = sizes[0]
        W = sizes[1]
        area = L * W

        print('-' * 30)
        print('{} Name: {}'.format(spatial_type,name))
        print('{} Size: {}m x {}m'.format(spatial_type,L, W))
        print('Calculating Area: {}m2'.format(area))



rooms = {'Room_A': (10, 12),
         'Room_B': (15, 20),
         'Room_C': (8, 10),
         'Room_D': (5, 8)}

areas = {'Area_A' :(55,20),
         'Area_B': (15, 45),
         'Area_C': (10, 70),
         'Area_D': (20, 45)}



spatial_calculator(rooms, spatial_type='Room')
spatial_calculator(areas, spatial_type='Area')

Now if you need to make any changes, you just do it in one place, and it will be applied everywhere you use it. That's the power of reusing your code.

HomeWork

It can still be a little confusing, but you need to practice creating functions.

So, here is your simple task:

  • Take a piece of code from previous lessons

  • Turn it into a function.

  • Try adding arguments or default values.

  • Experiment with returning values.

  • Call your function multiple times with different inputs.

Keep it simple.

Functions are a game-changer in programming. Practice them, and you’ll see how much easier and cleaner your code becomes.

⌨️ Happy Coding!

Questions:

Do functions always need to return?

Do functions always need to return?

Can I put function in a function?

Can I put function in a function?

What is yield?

What is yield?

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API