22 C
Jaipur
Friday, October 30, 2020

Python Functions – Linux Hint

Must read

How to Install YOURLS self-hosted URL shortener on CentOS 8

YOURLS is a free, open-source and self-hosted URL shortener written in PHP. It is very similar to TinyURL or Bitly and allows you to...

How to Install Jira Agile Project Management Tool on Ubuntu 20.04

JIRA is a project management tool developed by Atlassian which is used as an issue and bug-tracking system. It is a commercial tool and...

phishing: Cyberattacks hit over 1,000 schools, colleges between June and September: Report – Latest News

Spear phishing attacks hit the education sector hard between June and September, affecting more than 1,000 schools, colleges, and universities, according to a global...

Parliamentary panel questions Google, Paytm on data privacy, Chinese investment – Latest News

Google and digital payments major Paytm were questioned by a parliamentary panel in India on a range of issues including data privacy and China...

A function is a block or group of similar statements that perform a specific task. A function is written to perform the task. In Python, a function takes the input, performs the task, and returns the output. A function also makes the code reusable; instead of writing the same code again and again for performing a similar task, we can make a function and call it.

Python has various built-in functions, including print (), type (), and more. But, we can also define or write our functions. We call these functions “user-defined” functions. In this article, you will learn how to define a function with multiple examples. The Spyder3 editor is used for creating and writing the Python scripts shown in this article.

How to Define a Function

  • In Python, a function starts with the keyword def.
  • The keyword def is followed by the function name and a pair of parentheses [()]. The name of the function should be unique, which means that there should not be any other function with the same name throughout the script.
  • A function can have multiple parameters or arguments. A parameter or argument is the input value for the function and should be defined inside the parentheses.
  • After writing the function name and list of parameters, place a colon [:] and start writing the piece of code or statements.
  • Lastly, there is a return statement in the function, which returns the output of the function.
  • The following is the basic syntax of defining the function:

def function_name (parameters):
    statements
    return [value or expression]

Function Example

Let us look ats an example of a function in Python. This function takes a year as an input parameter and checks whether the given year is a leap year or not. The function is called by the function name.

# defining a function to check whether a year is a leap year or not
def leap_year(year):
    #if the year%4 is equal to zero then it is a leap year otherwise not.
    if(year%4==0):
        print(year,” is a Leap Year”)
    else:  
        print(year,” is not a leap year”)
#calling the function
leap_year(2020)

Output

The output is displayed on the right side of the Python console.

Passing Arguments

You can pass information to a function as an argument. An argument is specified inside the function name after the parentheses. You can add unlimited arguments in parentheses, but every argument must be separated by a comma. These are called the positional arguments. It is required to pass all the arguments while calling a function. Otherwise, it results in an error.

Let us see an example of passing multiple arguments in a function.

# defining a function to print the student information
def student_info(first_name,last_name,father_name,rollNo,email):
    #printing the student first name
    print(“The student first name is: “,first_name)
    #printing the student last name
    print(“The student last name is: “,last_name)
    #printing the student’s father name
    print(“The student’s father  name is: “,father_name)
    #printing the student’s roll number
    print(“The student roll number is: “,rollNo)
    #printing the student email
    print(“The student email is: “,email)
#calling the function
student_info(“Kamran”,“Awaisi”,“Abdul Sattar”,12,[email protected])

Output

The output is displayed on the right side of the Python console.

The terms “parameter” and “argument” are identical. A parameter is a value that is written inside the parentheses, and we use a parameter inside the function. For example, first_name, last_name, father_name, rollNo, and email are the parameters in the example given above.

On the other hand, an argument is a value that is sent to the function.

Defining an Argument’s Default Value

You can also define the default value of an argument. For example, we will define a function that takes two numbers as an argument and calculates the sum. The value of the second number (a parameter) is 10 by default. We will only pass the value of the first number as an argument and the function will calculate the sum.

# defining a function to calculate the sum of two numbers
# the value of the second variable is set to 10 by default
def calculate_sum(num1,num2=10):
    print(“The sum is: “,num1+num2)
# calling the function
#passing the value of the first variable as an argument
calculate_sum(15)

Output

The output is displayed on the right side of the Python console.

If we enter the value of the second variable as an argument, then the function will not take the default value.

# defining a function to calculate the sum of two numbers
# the value of the second variable is set to 10 by default
def calculate_sum(num1,num2=10):
    print(“The sum is: “,num1+num2)
# calling the function
#passing the value of the first variable as an argument
calculate_sum(15,25)

Output

The output is displayed on the right side of the Python console.

Keyword Arguments

You can pass arguments by using the parameter name. In this case, it is not necessary to remember the order of the parameters. You only have to write the name of the parameter, and then define its value and pass it as an argument. When using the keyword arguments, the name of the parameter and the keyword should be the same. Let us see an example:

# defining a function to calculate the sum of two numbers
def calculate_sum(num1,num2):
    print(“The sum is: “,num1+num2)
# calling the function
#passing the value of variables by using keyword argument
calculate_sum(num1=15,num2=25)

Output

The output is displayed on the right side of the Python console.

When using the keyword arguments, make sure that the name of the parameter and keyword are the same. The order of defining the keywords could be different. In this case, the compiler does not show any error. Let us see an example of this function with a changed order.

# defining a function to calculate the sum of two numbers
def calculate_sum(num1,num2):
    print(“The sum is: “,num1+num2)
# calling the function
#passing the value of variables by using the keyword argument.
The order of num1 and num2 is changed
calculate_sum(num2=15,num1=25)

Output

The output is displayed on the right side of the Python console.

Now, let us change the names of the keywords and see what happens.

Output

In the output, it can be seen that it now shows the error “Unexpected keyword argument.

Variable-Length Arguments

In some cases, if you are not sure about the number of parameters, then you can use variable-length arguments. These arguments are unlike the keyword default arguments. They are not defined by a name inside the parentheses. Let us see an example of this:

# defining a function to print the information
def print_linuxhint(*myargs):
    for i in myargs:
        print(i)
# calling the function
#passing the value of multiple variables
print_linuxhint(“Hello”,“and”,“welcome”,“to the”,“LinuxHint”)

Output

The output is displayed on the right side of the Python console.

Return Statement

The return statement is used at the end to exit the function. This statement passes the output back to where the function was called.

Let us see an example of a return statement:

# defining a function to calculate the sum of two numbers
def calculate_sum(num1,num2):
    # adding the return statement
    # the return statement returns the value of the sum to the caller.
    return num1+num2
# calling the function
print(calculate_sum(15,25))

Output

The output is displayed on the right side of the Python console. The output shows that the return statement returns the value of the sum without any error.

Conclusion

This article helped beginners to understand Python functions with the help of some simple examples. Using functions can make your Python code reusable and more structured. Instead of writing the same code again and again for performing a similar type of task, you can make a function and call it more easily.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

How to Install YOURLS self-hosted URL shortener on CentOS 8

YOURLS is a free, open-source and self-hosted URL shortener written in PHP. It is very similar to TinyURL or Bitly and allows you to...

How to Install Jira Agile Project Management Tool on Ubuntu 20.04

JIRA is a project management tool developed by Atlassian which is used as an issue and bug-tracking system. It is a commercial tool and...

phishing: Cyberattacks hit over 1,000 schools, colleges between June and September: Report – Latest News

Spear phishing attacks hit the education sector hard between June and September, affecting more than 1,000 schools, colleges, and universities, according to a global...

Parliamentary panel questions Google, Paytm on data privacy, Chinese investment – Latest News

Google and digital payments major Paytm were questioned by a parliamentary panel in India on a range of issues including data privacy and China...

startups: MoUs to be inked with 25 startups for exchange of tech: IGCAR – Latest News

The Indira Gandhi Centre for Atomic Research (IGCAR) at Kalpakkam near here on Friday said it was aiming to sign memoranda of understanding (MOUs)...