Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Functions in Python Syntax - With and Without Arguments

User image

Published by

sanya sanya

Published at: 13th Aug, 2023
7.29 mins read

Types of Functions

Python consists of two types of functions, namely :

  • Built-in Functions :

    These are pre-defined functions that are available in Python, and they can be used directly without the need to define them. Some examples of built-in functions include print(), len(), input(), range(), and type().

    Examples of built-in functions:

    1. print() function: The print() function is used to display text or variables in the console. It can be used with one or more arguments, separated by commas. Here's an example:

      print("Hello World!") # Output: Hello World!
    2. len() function: The len() function is used to find the length of an object. It can be used with strings, lists, tuples, dictionaries, and other data types. Here's an example:

      my_string = "Hello, world!" print(len(my_string)) # Output: 13
    3. input() function: The input() function is used to take user input from the console. It prompts the user to enter a value and returns the input as a string. Here's an example:

      user_input = input("Enter your name: ") print("Hello, " + user_input + "!") # Output: Hello, <user_input>!
    4. type() function: The type() function is used to determine the data type of an object. It returns a string indicating the type of the object. Here's an example:

      my_list = [1, 2, 3] print(type(my_list)) # Output: <class 'list'>
    5. sqrt() function: returns the square root of a number. For example:

      import math x = 16 print(math.sqrt(x)) # Output: 4.0
    6. min() and max() functions: return the minimum and maximum value from a set of values. For example:

      x = [1, 2, 3, 4, 5] print(min(x)) # Output: 1 print(max(x)) # Output: 5
  • User-defined Functions :

    These are functions that are defined by the user to perform a specific task or set of tasks. User-defined functions start with the keyword "def", followed by the function name, a set of parentheses, and a colon. The function body is then indented and contains the instructions that the function should execute. The user can call the function later in the code by using its name and passing in any required arguments.


Creating a Function - Syntax

The syntax for defining a function in Python is as follows:

def function_name(parameter1, parameter2, ...): """ Docstring: This is a description of what the function does """ # Code block # More code return value_to_return

def: This is the keyword used to define a function in Python.

function_name: This is the name you give to your function. It should be descriptive and follow the naming conventions for Python identifiers.

(parameter1, parameter2, ...): These are the optional parameters that your function can take as input. You can specify any number of parameters, separated by commas.

:: This colon indicates the start of the function body.

"""Docstring: This is a description of what the function does""": This is a docstring, which is a string that provides documentation for your function. It should describe what the function does, what parameters it takes, and what it returns.

# Code block: This is the actual code that the function will execute.

return value_to_return: This statement specifies the value that the function will return when it is called. If your function doesn't need to return a value, you can omit this statement.

Function with and without arguments

Arguments are values that you pass to a function when you call it. They allow you to provide input to a function and customize its behavior. Arguments are included in brackets following the function name. You can enter as many parameters as you wish, separated by a comma.

  1. Function Without Arguments

    A function without arguments, on the other hand, doesn't take any values as input when it is called. Instead, it performs some computation based on its internal logic and returns a result.

    Here's an example of a function without arguments in Python:

    def greet(): """ Prints a greeting message. """ print("Hello, how are you?")

    This function doesn't take any arguments. Instead, it simply prints a greeting message when it is called. When no arguments are passed, a function is called by function name followed by parenthesis. Below is the code to call the function when no arguments are passed.

    greet() # Output: "Hello, how are you?"
  2. Function With Arguments A function with arguments takes one or more values as input when it is called. These values are specified inside the parentheses when you call the function, and they are passed to the function as parameters. The function can then use these parameters to perform some computation and return a result.

    Here's an example of a function with arguments in Python:

    def area_of_rectangle(x,y): """ Returns the area of rectangle by length *breadth (x*y). """

    This function takes two arguments, x and y as length and breadth of rectangle and returns the area of the rectangle as (x*y). You can call this function with two values inside the parentheses:

    result = area_of_rectangle(3, 4) print(result) # Output: 12

    A function must be called with the right number of parameters by default. That is, if your function expects two parameters, you must call it with two arguments, not more or fewer.


The Return Statement

A Python function can either return a value or not. The return statement is used when we want our function to return a value to a function call.

Here's an example of a Python function with a return statement:

def area_of_rectangle(x, y): """ Returns the area of the rectangle. """ return x * y

This function takes two arguments, x and y, adds them together using the + operator, and returns the result using the return statement. You can call this function and store its output in a variable like this:

result = area_of_rectangle(3, 4) print(result) # Output: 12

And now below is the example of function without return statement

def greet(name): """ Prints a greeting message. """ print(f"Hello, {name}! How are you doing today?")

This function takes one argument, name, and prints a greeting message that includes the name. It doesn't use a return statement to provide a result back to the code that called it. Instead, it performs some computation based on its internal logic and outputs a message to the console. You can call this function like this:

greet("Alice") # Output: "Hello, Alice! How are you doing today?"

Default Parameter Value

In Python, default parameter values can be defined in a function definition by assigning a default value to a parameter. This default value will be used if the corresponding argument is not provided when the function is called.

def greet(name, greeting='Hello'): print(greeting, name) greet('John') # Output: Hello John greet('Jane', 'Hi') # Output: Hi Jane

In the greet function above, the name parameter is required, but the greeting parameter has a default value of 'Hello'. If the greeting argument is not provided when the function is called, it will default to 'Hello'. If a different greeting is provided, that value will be used instead.

Note that the default parameter values are assigned when the function is defined, not when it is called. So, if a mutable object such as a list or dictionary is used as a default parameter value and modified within the function, the modified value will persist across multiple function calls. This can sometimes lead to unexpected behavior, so it's important to be aware of when using mutable default parameter values.


Keyword Arguments

In Python, keyword arguments allow you to pass arguments to a function using their names as keywords. Keyword arguments are useful when you have a function that takes multiple arguments, some of which may have default values.

Below is an example,

def print_person(name, age, city="Unknown", country="USA"): print("Name:", name) print("Age:", age) print("City:", city) print("Country:", country) print_person(name="John", age=30, city="New York", country="USA")

In the example above, we defined a function print_person that takes four parameters: name, age, city, and country. The city and country parameters have default values of "Unknown" and "USA", respectively.

When we call the function, we use keyword arguments to specify the values of the parameters we want to pass. In this case, we pass the name, age, city, and country parameters in the form of name="John", age=30, city="New York", and country="USA".

Keyword arguments can be passed in any order, as long as their names match the parameter names of the function. This can make it easier to remember the order of the arguments, especially for functions with many parameters.

This is how functions are created in python. Have a happy learning ahead !!

Library

WEB DEVELOPMENT

FAANG QUESTIONS

On this page

: