Python Functions

Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

Topics:

Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain.

Defining a Function:

In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses, and a colon. The function body is indented behind the definition line.

Python
Python
Python
def capital(word):
    print(f"{word.upper()}")

The camel function in this example takes one parameter and prints out a capital cased word.

Calling a Function:

To use a function, we call its name and provide required parameters if asked. This is how you would refer to the capital function:

Python
Python
Python
capital("Use Python")
>>>USE PYTHON

Returning Values:

Functions can also return values using the return statement. This is useful when you want the function to calculate something and provide a result back to the caller.

Python
Python
Python
def mul(a, b):
    return a * b
print(mul(7, 8))
>>>56

Default Arguments:

You can provide default values for function parameters, so they become optional when calling the function. If a value is not provided, the default value is used.

Python
Python
Python
def listed(original_number, offset=2):
    return original_number - offset
print(listed(9))
print(listed(9,5))
>>>7
>>>4

Function Quiz1

Click here to complete the task related to functions. Test you knowledge.

Function Quiz2

Click here to complete the task related to functions. Test you knowledge.

Function Quiz3

Click here to complete the task related to functions. Test you knowledge.

Variable Number of Arguments:

*args (for positional arguments) and **kwargs (for keyword arguments) enable functions to provide a variable number of arguments.

Python
Python
Python
def avg_marks(*marks):
     return sum(marks)/len(marks)
avg_marks(81,92,88,65,79,83,90)
>>>82.57

Lambda Functions:

Lambda functions are small, anonymous functions defined using the lambda keyword. They are often used for simple operations.

Python
Python
Python
marks=[81,92,88,65,79,83,90]
total = lambda x: sum(x)
print(total(marks))
>>>578

These are just the basics of Python functions. They play a crucial role in organizing and structuring your code for better readability and maintainability. Feel free to ask if you have more specific questions about functions or any other aspect of Python programming!

You can pass many arguments through a function in Python using a couple of techniques. Let’s explore two common ways: using positional arguments and using the *args syntax.

Using Positional Arguments:

Positional arguments are passed to a function in the order they are defined. You can simply provide the values when calling the function, separated by commas.

Python
Python
Python
def print_names(name1, name2, name3):
    print(f"Name 1: {name1}")
    print(f"Name 2: {name2}")
    print(f"Name 3: {name3}")

print_names("Alice", "Bob", "Charlie")

In this example, the print_names function accepts three arguments (name1, name2, and name3), and you pass three values when calling it.

Using *args for Variable Number of Arguments:

If you want to pass a variable number of arguments without having to define each argument explicitly, you can use the *args syntax. This allows you to pass any number of positional arguments, and they will be collected into a tuple within the function.

Python
Python
Python
def print_all(*args):
    for arg in args:
        print(arg)

print_all("Apple", "Banana", "Cherry", "Date")

In this example, the print_all function accepts any number of arguments and prints each one.

Example with Both Techniques:

You can also mix both techniques if you want to pass a combination of explicitly defined arguments and a variable number of arguments.

Python
Python
Python
def show_info(name, age, *hobbies):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print("Hobbies:", hobbies)

show_info("Alice", 30, "Reading", "Swimming", "Cooking")

In this example, the show_info function takes the first two arguments (name and age) as positional arguments and then collects any additional arguments as hobbies using *args.

Remember that *args should always be the last parameter in the function definition, as it collects all remaining positional arguments.

How useful was this post?

Click on a star to rate it!

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • ANOVA (Analysis of Variance ) part 1

    A method to find a statistical relationship between two variables in a dataset where one variable is used to group data.

  • Basic plots with Seaborn

    Seaborn library has matplotlib at its core for data point visualizations. This library gives highly statistical informative graphics functionality to Seaborn.

  • Matplotlib in python

    The Matplotlib library helps you create static and dynamic visualisations. Dynamic visualizations that are animated and interactive. This library makes it easy to plot data and create graphs.

  • Plotly with Python and R

    This library is named Plotly after the company of the same name. Plotly provides visualization libraries for Python, R, MATLAB, Perl, Julia, Arduino, and REST.

  • Numpy Array

    Numpy array have functions for matrices ,linear algebra ,Fourier Transform. Numpy arrays provide 50x more speed than a python list.

  • NumPy: Python’s Mathematical Backbone

    Numpy has created a vast ecosystem spanning numerous fields of science.

  • Introduction to Pandas: A Guide

    Pandas is a easy to use data analysis and manipulation tool. Pandas provides functionality for categorical,ordinal, and time series data . Panda provides fast and powerful calculations for data analysis.

  • Pandas Dataframe in brief

    In this tutorial, you will learn How to Access The Data in Various Ways From the dataframe.

  • Exploring the World of Sets in Python

    Understand one of the important data types in Python. Each item in a set is distinct. Sets can store multiple items of various types of data.

  • A Beginner’s Guide to Immutable Tuples

    Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.

Instagram
WhatsApp
error: Content is protected !!