0% found this document useful (0 votes)
8 views17 pages

Kwargs

Uploaded by

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

Kwargs

Uploaded by

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

**kwargs

Program 1: Print All Keyword Arguments


This program demonstrates how to print all the key-value pairs passed to the
function.
python
Copy code
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

# Example call
print_kwargs(name="Alice", age=25, country="USA")
Output:
makefile
Copy code
name: Alice
age: 25
country: USA

Program 2: Check for Specific Argument


This program checks if a specific key exists in the keyword arguments.
python
Copy code
def check_key(**kwargs):
if 'name' in kwargs:
print(f"Name is: {kwargs['name']}")
else:
print("Name not provided.")

# Example call

1
check_key(age=30, city="London")
Output:
Copy code
Name not provided.

Program 3: Default Value with get()


Use the .get() method to provide default values for missing keys.
python
Copy code
def student_info(**kwargs):
name = kwargs.get('name', 'Unknown')
age = kwargs.get('age', 'Not specified')
print(f"Student Name: {name}")
print(f"Student Age: {age}")

# Example call
student_info(name="Bob")
Output:
yaml
Copy code
Student Name: Bob
Student Age: Not specified

Program 4: Combine Fixed and Arbitrary Arguments


This program combines normal parameters and **kwargs.
python
Copy code
def describe_pet(pet_type, **kwargs):
print(f"Pet type: {pet_type}")
for key, value in kwargs.items():
print(f"{key}: {value}")

2
# Example call
describe_pet("Dog", name="Buddy", age=3, breed="Golden Retriever")
Output:
yaml
Copy code
Pet type: Dog
name: Buddy
age: 3
breed: Golden Retriever

Program 5: Count Keyword Arguments


This program counts how many keyword arguments were passed.
python
Copy code
def count_kwargs(**kwargs):
print(f"Number of keyword arguments: {len(kwargs)}")

# Example call
count_kwargs(name="Sarah", age=22, city="Paris")
Output:
javascript
Copy code
Number of keyword arguments: 3

Program 6: Modify a Dictionary


This program modifies an existing dictionary with the **kwargs.
python
Copy code
def update_dict(original, **kwargs):
original.update(kwargs)
return original

3
# Example call
my_dict = {"a": 1, "b": 2}
updated = update_dict(my_dict, b=3, c=4)
print(updated)
Output:
css
Copy code
{'a': 1, 'b': 3, 'c': 4}

Program 7: Return a Dictionary


This program accepts **kwargs and directly returns the resulting dictionary.
python
Copy code
def create_dict(**kwargs):
return kwargs

# Example call
result = create_dict(name="Emma", age=29, city="New York")
print(result)
Output:
arduino
Copy code
{'name': 'Emma', 'age': 29, 'city': 'New York'}

Program 8: Filter Even Numbers


This program filters and prints only the keyword arguments with even values.
python
Copy code
def filter_even_numbers(**kwargs):
for key, value in kwargs.items():
if value % 2 == 0:
print(f"{key}: {value}")

4
# Example call
filter_even_numbers(a=1, b=2, c=3, d=4)
Output:
makefile
Copy code
b: 2
d: 4

Program 9: Greeting with Optional Details


This program greets a person and displays optional details using **kwargs.
python
Copy code
def greet(name, **kwargs):
print(f"Hello, {name}!")
for key, value in kwargs.items():
print(f"{key}: {value}")

# Example call
greet("Alice", age=25, city="Berlin", hobby="Reading")
Output:
makefile
Copy code
Hello, Alice!
age: 25
city: Berlin
hobby: Reading

Program 10: Flexible Calculation


This program takes **kwargs to perform addition or multiplication based on the
operation type.
python

5
Copy code
def calculate(operation, **kwargs):
result = 0 if operation == "add" else 1
for key, value in kwargs.items():
if operation == "add":
result += value
elif operation == "multiply":
result *= value
print(f"Result: {result}")

# Example call
calculate("add", a=10, b=20, c=30)
calculate("multiply", x=2, y=3, z=4)
Output:
makefile
Copy code
Result: 60
Result: 24

These examples cover a variety of basic use cases for **kwargs to help you
understand its flexibility and power!

What is **kwargs in Python?


**kwargs in Python functions allows you to pass arbitrary keyword arguments
(key-value pairs) to a function.
 Arbitrary: The number of keyword arguments doesn't have to be fixed.
 Keyword Arguments: Arguments are passed as key=value pairs.

6
 Inside the function, Python collects these arguments into a dictionary.

Why Use **kwargs?


1. When you don't know in advance what keyword arguments might be
passed.
2. To create flexible and reusable functions that can handle extra information
dynamically.

Syntax
python
Copy code
def function_name(**kwargs):
# kwargs is a dictionary
for key, value in kwargs.items():
print(f"{key}: {value}")

Example Code: Using **kwargs


python
Copy code
def display_info(**kwargs):
print("Keyword arguments received:")
for key, value in kwargs.items():
print(f"{key}: {value}")

# Call the function with arbitrary keyword arguments


display_info(name="Alice", age=30, country="USA")

How it Works:
1. The function display_info uses **kwargs.
2. Inside the function, kwargs is a dictionary containing the passed keyword
arguments (name, age, country).
3. The for loop iterates through the dictionary to print each key-value pair.

7
Output:
yaml
Copy code
Keyword arguments received:
name: Alice
age: 30
country: USA

Additional Example: Combining Positional, Default, and **kwargs


python
Copy code
def greet_user(greeting, **kwargs):
print(greeting)
for key, value in kwargs.items():
print(f"{key}: {value}")

# Call the function


greet_user("Hello!", name="Bob", hobby="Cycling", age=35)
Output:
makefile
Copy code
Hello!
name: Bob
hobby: Cycling
age: 35
Summary
 **kwargs is used to pass a variable number of keyword arguments to a
function.
 It collects these arguments into a dictionary.
 This makes your function flexible and capable of handling extra input
dynamically.

8
9
What are Return Values in Python
Functions?
In Python, a return value is the output of a function. It is the value that a
function sends back to the caller (where the function was called).
 The return keyword is used to specify the value that a function
should return.

10
 A function can return:
o A single value
o Multiple values
o No value (implicitly returns None if no return is used)

Why Use Return Values?


1. To use the output of a function in other parts of the program.
2. To make the function reusable and modular.
3. To store the result for further processing.

Syntax
python
Copy code
def function_name(parameters):
# Code block
return value

Examples of Return Values


1. Returning a Single Value
python
Copy code
def add(a, b):
return a + b

# Call the function and store the result


result = add(3, 5)
print(result)
Output:
Copy code
8

11
2. Returning Multiple Values
python
Copy code
def get_name_and_age():
name = "Alice"
age = 25
return name, age

# Call the function and unpack the returned values


name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
Output:
yaml
Copy code
Name: Alice, Age: 25

3. Returning Nothing (Default None)


python
Copy code
def greet(name):
print(f"Hello, {name}!")

# Call the function


result = greet("John")
print(result) # No explicit return value
Output:
css
Copy code
Hello, John!

12
None

4. Using Return Value in Another Function


python
Copy code
def square(number):
return number * number

def sum_of_squares(a, b):


return square(a) + square(b)

# Call the function


result = sum_of_squares(3, 4)
print(result)
Output:
Copy code
25

Key Points:
1. A function stops executing as soon as it encounters a return
statement.
2. If no return is specified, the function implicitly returns None.
3. You can return any data type (integers, strings, lists, dictionaries,
etc.).

13
What is the pass Statement in
Python?
The pass statement in Python is a placeholder. It does nothing and is
used when a statement is syntactically required but no action is needed.
It is often used in the following cases:
1. To define an empty function, class, or loop as a placeholder while
building the code.

14
2. To avoid syntax errors when the body of a function or block is yet to
be implemented.

Key Characteristics:
 It is a no-operation (NOP) statement.
 It is a way to write valid Python code without functionality in certain
blocks.

Syntax
python
Copy code
def function_name():
pass # This does nothing for now

Code Examples
1. Using pass in a Function
python
Copy code
def my_function():
pass # Placeholder for future implementation

print("Function defined successfully!")


Output:
javascript
Copy code
Function defined successfully!

2. Using pass in a Loop


python
Copy code
for i in range(5):

15
pass # Placeholder for loop body

print("Loop executed successfully!")


Output:
vbnet
Copy code
Loop executed successfully!

3. Using pass in a Class Definition


python
Copy code
class MyClass:
pass # Placeholder for the class body

print("Class defined successfully!")


Output:
perl
Copy code
Class defined successfully!

4. Using pass with Conditional Statements


python
Copy code
x = 10

if x > 5:
pass # Placeholder for 'if' block
else:
print("x is 5 or less")

16
print("Code executed successfully!")
Output:
css
Copy code
Code executed successfully!

Why Use the pass Statement?


 To write code without implementation while avoiding syntax errors.
 It helps in creating the structure of a program, making it easier to fill
in the details later

17

You might also like