0% found this document useful (0 votes)
3 views4 pages

Operations To Be Performed On Functions

Uploaded by

projectajinkya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Operations To Be Performed On Functions

Uploaded by

projectajinkya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Operations to be performed on Functions

Let's go through each operation with examples and explanations.

### 1. Defining a Function


Defining a function involves creating a function with the `def` keyword followed by the function
name and parentheses.

def greet():

print("Hello, World!")

```

### 2. Calling a Function


Calling a function involves using the function name followed by parentheses.

greet() # Output: Hello, World!

```

### 3. Function with Parameters


A function can take parameters to process data.

def greet(name):

print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

```

### 4. Function with Return Value


A function can return a value using the `return` keyword.

def add(a, b):

return a + b

result = add(3, 4)

print(result) # Output: 7

```
### 5. Default Parameters
Functions can have default parameter values, which are used if no argument is provided.

def greet(name="World"):

print(f"Hello, {name}!")

greet() # Output: Hello, World!

greet("Alice") # Output: Hello, Alice!

```

### 6. Keyword Arguments


Keyword arguments allow you to specify arguments by name.

def greet(name, message):

print(f"Hello, {name}! {message}")

greet(message="How are you?", name="Alice") # Output: Hello, Alice! How are you?

```

### 7. Variable-length Arguments


Functions can take an arbitrary number of arguments using `*args` and `**kwargs`.

def greet(*names):

for name in names:

print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie")

# Output:

# Hello, Alice!

# Hello, Bob!

# Hello, Charlie!

def greet(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")
greet(name="Alice", age=30)

# Output:

# name: Alice

# age: 30

```

### 8. Lambda Functions


Lambda functions are small anonymous functions defined using the `lambda` keyword.

add = lambda a, b: a + b

print(add(3, 4)) # Output: 7

```

### 9. Nested Functions


Functions can be defined within other functions.

def outer_function():

def inner_function():

print("Hello from inner function!")

inner_function()

outer_function()

# Output: Hello from inner function!

```

### 11. Anonymous Functions


An anonymous function can be created using `lambda`.

square = lambda x: x * x

print(square(5)) # Output: 25

```

```

You might also like