Python functions

  • Post author:
  • Post comments:0 Comments
  • Reading time:27 mins read

What is a function?

A function is a block of code that performs a specific task. Functions help you organize your code and make it reusable.

How to define a function in Python?

In Python, you can define a function using the def keyword, followed by the function name and a set of parentheses (). Inside the parentheses, you can define any parameters that the function takes. The code block within every function starts with a colon : and is indented.

For example:


def greet(name):
  print("Hello, " + name)

This is a function called greet that takes a single parameter called name. When the function is called, it prints out a greeting with the name provided.

How to call a function in Python?

To call a function in Python, you simply need to use the function name followed by a set of parentheses (), and pass any required arguments inside the parentheses.

For example:


greet("John")

This would call the greet function and pass the argument “John” to it. The function would then print out “Hello, John”.

Returning a value from a function

In Python, you can use the return keyword to specify a value that a function should return. When a function encounters the return keyword, it will immediately exit and return the specified value.

For example:


def add(a, b):
  result = a + b
  return result

sum = add(1, 2)

print(sum)

This function, called add, takes two arguments a and b, and returns their sum. When the function is called with the arguments 1 and 2, it returns the value 3, which is then stored in the variable sum and printed out.

Here are some more examples of functions in Python:


def is_even(n):
  if n % 2 == 0:
    return True
  else:
    return False


def calculate_area(length, width):
  return length * width


def add_and_multiply(a, b, c):
  result = a + b
  result *= c
  return result


def say_hello():
  print("Hello!")

Publisher

Publisher

Publisher @ideasorblogs

Leave a Reply