4. Functions, Packing, and Unpacking (65m) Flashcards

1
Q

What is a function in python?

A

In Python, a function is a block of reusable code that performs a specific task or a set of tasks. Functions allow you to organize your code into modular and reusable units, making your code more readable, maintainable, and efficient.

def greet(name):
    """This function greets the person with the given name."""
    print("Hello, " + name + "!")

Function call
greet("Alice")

What is a Function?
A function is a reusable block of code that’s given a name. Functions should accomplish one programming task, and do that task very well. They allow us to keep our code clean and DRY - dry meaning “Don’t Repeat Yourself”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create a simple function to print name and call out the function

A

Write your function here!

Here:
~~~
# Write your function here!

def print_name():
print(“hello Sethu”)

print_name()
~~~

How to Write a Function
Functions are notated by the keyword def, the name of the function, a set of parentheses, and then a colon. After the colon, on a new indented line, you can write the body of your function.
~~~
# A function definition
def my_function_name():
print(“Hello, I’m a function!”)
~~~

Calling, or Invoking, a Function
To call a function, you simply type its name followed by a set of parenthesis. The parens tell the Python interpreter that we’re talking about function and not something else, and routes the program execution over the function, and then back to the main code.
~~~
# Calling/invoking the my_function_name function
my_function_name()
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why the following code prints 5 instead of 10?

num = 10

def set_num():
    num = 5

set_num()

print(num)
A

The code is printing 10 instead of 5 because of the concept of variable scope in Python.

In Python, variables have scope, which determines the visibility and accessibility of a variable within different parts of the code. When you define a variable inside a function, it creates a new local variable that is separate from any variables with the same name in the outer (global) scope.

In your code, the variable num is defined globally with a value of 10. Inside the set_num() function, you define a new local variable num and assign it a value of 5. However, this local variable num is different from the global variable num.

Therefore, when you call the set_num() function, it modifies the local variable num to 5, but it does not affect the global variable num which remains unchanged at 10. As a result, when you print num after calling set_num(), it prints the value of the global variable num, which is 10.

If you want to modify the global variable num within the function, you can use the global keyword to indicate that you are referring to the global variable. Here’s an updated version of your code that demonstrates this:

num = 10

def set_num():
    global num  # Referencing the global variable
    num = 5

set_num()

print(num)

In this modified code, the global keyword is used inside the set_num() function to indicate that the variable num being modified is the global variable. Now, when you print num, it will output 5 because the global variable num has been modified by the function.

Scope
When the program is executing inside a function, that’s called the local context. Variables inside the local context, or inside a function, are only visible inside that function. Variables in the global context, or the highest level of the program, can be seen and accessed by the entire program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Create a function called my_first_function. Inside the function body, indent 4 spaces and write the word “pass”.

A

Certainly! Here’s the code for creating a function called my_first_function with the word “pass” inside the function body:

def my_first_function():
    pass

In this code, the def keyword is used to define a function named my_first_function. The function body is indented with 4 spaces, and the pass keyword is written inside the function body. The pass statement is a placeholder statement in Python that does nothing. It is often used as a placeholder when you want to define a function or a code block that doesn’t have any code yet.

Feel free to add your desired code inside the function body to perform the specific tasks you need.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. Write a function called hello_student. This function should receive one argument, name. This function should return one value, the string ‘Hello ‘ followed by the value of the name parameter.
  2. Call the hello_student() function and save the return value to a variable called hello.
A
def hello_student(name):
    return 'Hello ' + name

student_name = 'Alice'
hello = hello_student(student_name)
print(hello)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is it true “When we pass a value to a function in a function call, we’re passing a parameter.”?

A

No, that statement is not accurate. When we pass a value to a function in a function call, we are actually passing an argument, not a parameter.

To clarify the terminology:

Parameters: Parameters are the variables declared in the function definition. They act as placeholders for the values that will be passed to the function when it is called. Parameters are defined when creating the function.

Arguments: Arguments are the actual values or expressions that are passed to a function when it is called. They correspond to the parameters defined in the function’s definition. Arguments are provided when invoking a function.

In a function call, you pass arguments to the function, and these arguments are received by the corresponding parameters defined in the function’s definition. So, the correct statement would be: “When we pass a value to a function in a function call, we’re passing an argument.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Is it true “When we pass a value to a function in a function call, we’re passing an argument.”?

A

Yes, that statement is correct. When you pass a value to a function during a function call, you are indeed passing an argument.

In the context of function calls:

Parameters are the variables declared in the function definition.
Arguments are the actual values or expressions that are passed to the function during the function call.
When you invoke a function and provide a value or expression within the parentheses, that value or expression is considered an argument. It is then received by the corresponding parameter within the function’s definition.

So, to restate the statement: “When we pass a value to a function in a function call, we’re passing an argument.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Is it true “The variable inside the parens of a function definition is known as a parameter.”?

A

No, that statement is not accurate. The variable inside the parentheses of a function definition is not called a parameter; it is called a parameter name.

In the context of function definitions:

Parameter: A parameter is a variable specified in the function definition. It serves as a placeholder for the values that will be passed to the function when it is called. Parameters are defined by their names, which are typically included inside the parentheses following the function name.

Parameter Name: The parameter name refers to the identifier used to represent a parameter within the function definition. It is the variable name that is used to access the corresponding argument passed to the function during its execution.

When defining a function, you provide the parameter names inside the parentheses to specify the inputs the function expects. These parameter names allow you to refer to the arguments passed to the function within the function’s body.

So, to clarify the statement: “The variable inside the parentheses of a function definition is known as a parameter name.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

is it true “Arguments and parameters are synonymous and can be used interchangeably.”?

A

No, arguments and parameters are not synonymous and cannot be used interchangeably. They have distinct meanings in the context of functions.

In the context of a function, a parameter refers to a variable listed in the function definition. It serves as a placeholder for the value that will be passed to the function when it is called. Parameters are defined when creating the function and are used to specify what inputs the function expects.

An argument, on the other hand, refers to the actual value or expression that is passed to a function when it is called. Arguments are provided when invoking a function, and they correspond to the parameters defined in the function’s definition. The argument is the actual value that is being passed into the function to be used during its execution.

In summary, parameters are defined in the function declaration, whereas arguments are the actual values or expressions passed to a function when it is called. They are related but distinct concepts in the context of functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Parameters are not assigned a value until the function is called and an argument is passed? True or False?

A

Yes, that is correct. Parameters in a function definition do not have a value until the function is called and arguments are passed to them.

When you define a function and specify parameters, you are essentially declaring placeholders for the values that will be provided when the function is invoked. The actual values, called arguments, are passed to the function during the function call.

Once the function is called with specific arguments, the parameter names within the function definition are assigned the corresponding argument values. These assigned values can then be used within the function’s body to perform calculations, operations, or any other desired actions.

To summarize, parameters in a function definition act as placeholders that receive values from the arguments passed during the function call. The assignment of values to parameters occurs dynamically when the function is called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain the following code:

def my_function(arg1, arg2, arg3, arg4):
    print(arg1)
    print(arg2)
    print(arg3)
    print(arg4)
    
my_function("Hello", "I", "love", "python")
A

The given code defines a function named my_function that takes four parameters: arg1, arg2, arg3, and arg4. Inside the function, it prints the values of these parameters using the print() function.

Then, the function my_function is called with the arguments “Hello”, “I”, “love”, and “python”. During the function call, these values are passed to the corresponding parameters.

When the function is executed, it will print each argument on separate lines using the print() function. The output will be as follows:
~~~
Hello
I
love
python
~~~

Each argument is printed on a new line, as specified by the print() statements in the function’s body. The values “Hello”, “I”, “love”, and “python” are passed to the respective parameters arg1, arg2, arg3, and arg4 when calling the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain the following code:
~~~
def my_function(*args):
print(args)

my_function(“Hello”, “I”, “love”, “python”)
~~~

A

The given code defines a function named my_function with a parameter called *args. The asterisk (*) before the parameter name indicates that it can accept any number of positional arguments.

Inside the function, the print() function is used to print the value of args.

When the function my_function is called with the arguments “Hello”, “I”, “love”, and “python”, these arguments are collected and packed into a tuple. This tuple is then assigned to the parameter args.

The function my_function prints the value of args, which will be the tuple containing the passed arguments. The output will be:
~~~
(‘Hello’, ‘I’, ‘love’, ‘python’)
~~~

The *args parameter allows the function to handle a variable number of arguments. It collects all the arguments passed to the function and packs them into a tuple. This allows you to pass any number of arguments to the function, and they will be accessible as elements within the args tuple.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain the following code:

def my_function(*args):
    for val in args:
        print(val)
        
my_function("Hello", "I", "love", "python")
A

The given code defines a function named my_function with a parameter called *args, which indicates that it can accept any number of positional arguments.

Inside the function, there is a for loop that iterates over the elements of the args tuple. Each element is assigned to the variable val.

During the function call my_function(“Hello”, “I”, “love”, “python”), the arguments “Hello”, “I”, “love”, and “python” are collected into the args tuple.

The for loop then iterates over each element in the args tuple and prints the value of each element using the print() function. Each element is printed on a separate line.

Therefore, the output of the code will be:
~~~
Hello
I
love
python
~~~

The for loop allows the function to iterate over the variable number of arguments passed to my_function. By printing each value within the loop, the code effectively displays each argument on a separate line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is packing or packers or tuple packing mean in python?

A

In Python, “packing” or “tuple packing” refers to the process of creating a tuple by grouping multiple values together. It allows you to assign multiple values to a single variable or parameter, and Python automatically packs them into a tuple.

The general syntax for tuple packing is to provide multiple values separated by commas, without explicitly specifying a tuple:

value1, value2, value3 = 1, 2, 3

In this example, the values 1, 2, and 3 are packed into a tuple, and the tuple is automatically assigned to the variables value1, value2, and value3, respectively. You can think of it as implicitly creating a tuple on the right-hand side and assigning its values to the variables on the left-hand side.

You can also use tuple packing when calling functions:

my_tuple = 1, 2, 3
my_function(*my_tuple)

In this case, the values 1, 2, and 3 are packed into the my_tuple tuple, and then the * operator is used to unpack the tuple as individual arguments when calling the my_function function.

Packing allows you to conveniently group multiple values together and work with them as a single entity, making your code more concise and expressive.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

what does *args do in python?
ChatGPT

A

In Python, *args is a special syntax used in function definitions to allow a variable number of arguments to be passed to the function. The * (asterisk) before args unpacks the arguments, which are then accessible within the function as a tuple.

Here’s a simple example to illustrate its usage:
~~~
def my_function(*args):
for arg in args:
print(arg)

my_function(‘apple’, ‘banana’, ‘orange’)
~~~

Output:
~~~
apple
banana
orange
~~~

In this example, *args collects any number of arguments that are passed to the my_function and packs them into a tuple called args. Within the function, we can iterate over the args tuple and perform operations on each individual argument.

The *args syntax allows flexibility in function definitions by accepting any number of positional arguments. It is commonly used when the exact number of arguments is not known in advance or when a function needs to handle varying numbers of inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain the following code:
~~~
def calculate_total(*args):
total = sum(args)
print(total)

calculate_total(100, 50, 50, 100)
~~~

A

The provided code defines a function called calculate_total that accepts a variable number of arguments using the *args syntax. The function calculates the sum of all the arguments passed to it and then prints the total.

Let’s break down the code step by step:

def calculate_total(*args):: This line defines the calculate_total function with *args as a parameter. The *args syntax allows the function to accept any number of arguments, which will be packed into a tuple named args.

total = sum(args): This line calculates the sum of all the elements in the args tuple using the sum() function. The sum() function takes an iterable (in this case, the args tuple) and returns the sum of its elements.

print(total): This line prints the calculated total to the console.

calculate_total(100, 50, 50, 100): This line calls the calculate_total function and passes four arguments: 100, 50, 50, and 100. These values will be packed into the args tuple within the function.

When the code is executed, the calculate_total function will calculate the sum of the provided arguments (100 + 50 + 50 + 100 = 300) and print the result: 300.

Note that if you were to call the calculate_total function with a different number of arguments, it would still work correctly. For example, calculate_total(10, 20, 30) would print 60, which is the sum of 10, 20, and 30. The *args syntax allows for this flexibility.

17
Q

Edit the provided packer function so that instead of having three parameters, it will have only one packed parameter.

def packer(param1, param2, param3):
    pass

packer('Functions', 'are', 'fun!')
A

To modify the packer function to have only one packed parameter instead of three individual parameters, you can use the *args syntax to collect all the arguments into a single tuple. Here’s the updated code:

def packer(*args):
    pass

packer('Functions', 'are', 'fun!')
18
Q

What is packing and unpacking in python?

A

In Python, packing and unpacking refer to operations involving collections of values, such as tuples or lists.

  • Packing: Packing refers to combining multiple values into a single collection, such as a tuple or a list. It allows you to group multiple values together into a single entity. For example:
    ~~~
    my_tuple = (1, 2, 3) # Packing three values into a tuple
    my_list = [4, 5, 6] # Packing three values into a list
    ~~~

In the above examples, the values are packed into a tuple and a list, respectively. The values are enclosed within parentheses or square brackets to create a single collection.

  • Unpacking: Unpacking is the reverse operation of packing. It involves extracting values from a collection and assigning them to individual variables. It allows you to retrieve the individual values from a collection. For example:
    ~~~
    my_tuple = (1, 2, 3)
    x, y, z = my_tuple # Unpacking the tuple into three variables
    print(x) # 1
    print(y) # 2
    print(z) # 3

my_list = [4, 5, 6]
a, b, c = my_list # Unpacking the list into three variables
print(a) # 4
print(b) # 5
print(c) # 6
~~~

In the above examples, the values stored in the tuple and list are unpacked into individual variables x, y, z, a, b, and c.

Packing and unpacking are useful concepts that allow you to work with collections of values in a flexible way. They enable you to group related values together or retrieve individual values from a collection, making your code more concise and readable.

19
Q

Explain the following code:

def unpacker():
    return (1, 2, 3)

var1, var2, var3 = unpacker()

print(var1)
print(var2)
print(var3)
A

The provided code demonstrates an example of unpacking in Python. Let’s break it down step by step:

  1. def unpacker():: This line defines a function called unpacker with no parameters. This function returns a tuple containing the values 1, 2, and 3.
  2. return (1, 2, 3): This line specifies the return value of the unpacker function as a tuple containing the values 1, 2, and 3.
  3. var1, var2, var3 = unpacker(): This line performs unpacking. It calls the unpacker function, and the returned tuple (1, 2, 3) is unpacked into the variables var1, var2, and var3. Each variable receives the corresponding value from the tuple.
  4. print(var1): This line prints the value of var1 to the console. In this case, it will output 1.
  5. print(var2): This line prints the value of var2 to the console. It will output 2.
  6. print(var3): This line prints the value of var3 to the console. It will output 3.

By using unpacking, the code assigns the individual values from the returned tuple of the unpacker function to the variables var1, var2, and var3. Then, the print statements display the values of these variables.

In summary, the code demonstrates how to unpack a tuple returned by a function into separate variables, allowing you to access and use the values independently.

20
Q

Explain the following code:

def unpacker():
    return (1, 2, 3)

var1, var2, var3 = unpacker()

print(var1)
print(var2)
print(var3)
A

The provided code demonstrates an example of unpacking in Python. Let’s break it down step by step:

  1. def unpacker():: This line defines a function called unpacker with no parameters. This function returns a tuple containing the values 1, 2, and 3.
  2. return (1, 2, 3): This line specifies the return value of the unpacker function as a tuple containing the values 1, 2, and 3.
  3. var1, var2, var3 = unpacker(): This line performs unpacking. It calls the unpacker function, and the returned tuple (1, 2, 3) is unpacked into the variables var1, var2, and var3. Each variable receives the corresponding value from the tuple.
  4. print(var1): This line prints the value of var1 to the console. In this case, it will output 1.
  5. print(var2): This line prints the value of var2 to the console. It will output 2.
  6. print(var3): This line prints the value of var3 to the console. It will output 3.

By using unpacking, the code assigns the individual values from the returned tuple of the unpacker function to the variables var1, var2, and var3. Then, the print statements display the values of these variables.

In summary, the code demonstrates how to unpack a tuple returned by a function into separate variables, allowing you to access and use the values independently.

21
Q

Explain the following code:

def unpacker():
    return "hey"

var1, var2, var3 = unpacker()

print(var1)
print(var2)
print(var3)
A

It would output
~~~
h
e
y
~~~

In Python, a string is considered an iterable object, meaning it can be iterated over letter by letter. When you perform unpacking, each letter of the string is assigned to the corresponding variable on the left side of the assignment.

Let’s break down the code again, considering the behavior of string unpacking:

  1. def unpacker():: This line defines a function called unpacker with no parameters.
  2. return “hey”: This line specifies the return value of the unpacker function as the string “hey”.
  3. var1, var2, var3 = unpacker(): This line attempts to unpack the string returned by the unpacker function into three variables: var1, var2, and var3. Since a string is iterable, each letter of the string will be assigned to the corresponding variable.
  4. print(var1): This line prints the value of var1 to the console. It will output “h”, which is the first letter of the string.
  5. print(var2): This line prints the value of var2 to the console. It will output “e”, which is the second letter of the string.
  6. print(var3): This line prints the value of var3 to the console. It will output “y”, which is the third letter of the string.

So, in this case, the string “hey” is unpacked letter by letter into the variables var1, var2, and var3. Each variable holds one letter of the string, and when printed, they output the individual letters “h”, “e”, and “y”.

22
Q

Explain the following Code:

full_name = input('Enter your full name: \n').split(' ')
print(full_name)

first_name, last_name = input('Enter your first and last name: \n').split(' ')

print(first_name)
print(last_name)
A

The provided code demonstrates the usage of the split() function to separate a string into multiple parts based on a delimiter. Here’s a breakdown of the code:

  1. full_name = input('Enter your full name: \n').split(' '): This line prompts the user to enter their full name. The input() function takes the user’s input as a string. The split(‘ ‘) method is then applied to the input string, splitting it into multiple parts based on the space delimiter ‘ ‘. The resulting parts are stored in a list called full_name.
  2. print(full_name): This line prints the full_name list, displaying the parts of the name that were obtained by splitting the input string. Each part corresponds to a section of the full name, such as the first name, middle name(s), and last name.
  3. first_name, last_name = input('Enter your first and last name: \n').split(' '): This line prompts the user to enter their first and last name. Similar to the previous line, the split(‘ ‘) function is used to split the input string into two parts, the first name and the last name. The parts are then assigned to the variables first_name and last_name respectively.
  4. print(first_name): This line prints the value of the first_name variable, displaying the user’s entered first name.
  5. print(last_name): This line prints the value of the last_name variable, displaying the user’s entered last name.

To summarize, the code first prompts the user to enter their full name, splits it into individual parts (assuming they are separated by spaces), and stores those parts in a list. It then prints the list of name parts.

Next, the code prompts the user to enter their first and last name in a separate input. It splits the input string into two parts based on the space delimiter and assigns those parts to the variables first_name and last_name. Finally, it prints the values of first_name and last_name separately.

23
Q

Edit the variable assignment under the provided function so that the tuple returned from the function call is unpacked into 2 variables, val1, val2

def unpacker(*args):
    return args
    
val = unpacker('Python', 'rocks!')
A

To unpack the tuple returned from the unpacker function call into two variables, val1 and val2, you can modify the variable assignment as follows:

def unpacker(*args):
    return args
    
val1, val2 = unpacker('Python', 'rocks!')