0% found this document useful (0 votes)
4 views13 pages

Programming Assignment

The document explains the differences between global and local variables, immutable and mutable variables, and references and pointers in Python. It also covers how to create and access arrays and associative arrays (dictionaries) in Python, as well as how to create records using various data structures. Additionally, it discusses how to perform union operations on sets in Python.

Uploaded by

gracejamu4
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)
4 views13 pages

Programming Assignment

The document explains the differences between global and local variables, immutable and mutable variables, and references and pointers in Python. It also covers how to create and access arrays and associative arrays (dictionaries) in Python, as well as how to create records using various data structures. Additionally, it discusses how to perform union operations on sets in Python.

Uploaded by

gracejamu4
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/ 13

What is the difference between global variable and local variable?

Global variables are defined outside of any function or scope and can be accessed from
anywhere within a program whereas local variables are defined within a specific function or
block of code and only be accessed within that function or block.
What is the difference between immutable and mutable variables?
Immutable variables are those whose values cannot be changed once they are set, they are
typically used in functional programming where the focus is on function rather than its side
effects whereas mutable variables are those whose values can be changed after they are set
and they are useful when we need to modify the state of an object or data structure over time.
Mutable variables are typically used in imperative programming, where the focus is on the
side effects of a function.
What is the difference between references and pointers in python?
Refences are a way to access and manipulate objects. When an object is assigned to a
variable, the variable becomes a reference to that object, therefore a reference is a label or tag
attached to an object, allowing us to access and modify it. There are no pointers in python.
How do you create an array in python?
1. Using the `array` module:
- First, you need to import the `array` module by including the following line at the
beginning of your code: `from array import array`.
- Next, you can create an array by calling the `array ()` function and passing two
arguments: the type code and the initial values of the array. The type code specifies
the data type of the elements in the array.
- For example, to create an array of integers, you can use the type code `'i'`. Here's an
example that creates an array of integers with initial values `[1, 2, 3]`: `my_array =
array('i', [1, 2, 3])`.

2. Using the `numpy` library:


- First, you need to install the `numpy` library if it is not already installed. You can do
this by running `pip install numpy` in your command prompt or terminal.
- Once installed, you can import the `numpy` library by including the following line at
the beginning of your code: `import numpy as np`.
- To create an array using `numpy`, you can call the `np.array()` function and pass a
sequence-like object (such as a list or tuple) as an argument.
- For example, to create an array of integers with initial values `[1, 2, 3]`, you can use:
`my_array = np.array([1, 2, 3])`.

2. How do you access elements of an array in python?


To access elements of an array in Python, you can use indexing. In Python, arrays are
represented using the built-in list data structure. Each element in the array has a unique index
starting from 0.

To access a specific element in an array, you can use square brackets [] with the index value
inside them. For example, if you have an array called "my_array" and you want to access the
element at index 2, you would write:
my_array = [10, 20, 30, 40, 50]
element = my_array[2]
print(element) # Output: 30

In this example, the element at index 2 (which is the third element) is accessed and stored in
the variable "element". The value of "element" is then printed, resulting in the output of 30.

It's important to note that Python uses zero-based indexing, which means that the first
element of an array has an index of 0, the second element has an index of 1, and so on.
Therefore, to access the first element of an array, you would use an index of 0.

You can also use negative indexing to access elements from the end of the array. In this case,
-1 refers to the last element, -2 refers to the second-to-last element, and so on. Here's an
example:
my_array = [10, 20, 30, 40, 50]
element = my_array[-1]
print(element) # Output: 50

In this example, the last element of "my_array" is accessed using negative indexing (-1), and
it is stored in the variable "element". The value of "element" is then printed as 50.

Additionally, you can also access multiple elements from an array using slicing. Slicing
allows you to extract a portion of the array by specifying a start index, an end index
(exclusive), and an optional step size. Here's an example:

my_array = [10, 20, 30, 40, 50]


elements = my_array[1:4]
print(elements) # Output: [20, 30, 40]

In this example, the elements from index 1 to index 3 (exclusive) are extracted using slicing.
The resulting elements are stored in the variable "elements" and then printed as [20, 30, 40].
How do you create an associate array in python?
To create an associative array, also known as a dictionary, in Python, you can use the built-in
data structure called "dict". A dictionary is an unordered collection of key-value pairs, where
each key is unique and associated with a value. This data structure allows for efficient
lookup, insertion, and deletion of elements based on their keys.

To create a dictionary in Python, you can use curly braces {} or the built-in dict() constructor.
Here are a few examples:

Example 1: Using curly braces


my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Example 2: Using the dict() constructor


my_dict = dict(key1='value1', key2='value2', key3='value3')

In both examples, we have created a dictionary with three key-value pairs. The keys ('key1',
'key2', 'key3') are strings, and the corresponding values ('value1', 'value2', 'value3') can be of
any data type (e.g., strings, numbers, lists, or even other dictionaries).

You can access the values in a dictionary by using their corresponding keys. For example:

print(my_dict['key2']) # Output: value2

If you try to access a key that does not exist in the dictionary, it will raise a KeyError. To
avoid this error, you can use the get() method or check if the key exists using the "in"
keyword.

print(my_dict.get('key4')) # Output: None

if 'key4' in my_dict:
print(my_dict['key4'])
else:
print("Key not found")

To modify the value associated with a specific key, you can simply assign a new value to that
key:

my_dict['key2'] = 'new_value'
print(my_dict['key2']) # Output: new_value

You can also add new key-value pairs to an existing dictionary:

my_dict['key4'] = 'value4'
print(my_dict) # Output: {'key1': 'value1', 'key2': 'new_value', 'key3': 'value3', 'key4':
'value4'}

To remove a key-value pair from a dictionary, you can use the "del" keyword:

del my_dict['key3']
print(my_dict) # Output: {'key1': 'value1', 'key2': 'new_value', 'key4': 'value4'}

In addition to the basic operations mentioned above, dictionaries in Python provide various
methods and functionalities for manipulating and iterating over their elements. Some
commonly used methods include keys (), values(), items(), update(), pop(), clear(), and len().
How do you access the elements of an associative array?
To access the elements of an associative array in PHP, you can use the square bracket
notation `[]` followed by the key of the element you want to access. For example:

$my_array = array("name" => "John", "age" => 25);


echo $my_array["name"]; // Output: John

You can also use the dot notation `->` to access the elements of an associative array. This is
especially useful when the keys are not simple strings, but rather more complex data types
like objects or arrays themselves. For example:
$my_object = (object) array(
"name" => "John",
"age" => 25,
"address" => array(
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA"
)
);
echo $my_object->name; // Output: John
echo $my_object->address->street; // Output: 123 Main St
```
It's important to note that if the key does not exist in the associative array, using the square
bracket notation will result in a `NULL` value being returned, while the dot notation will
result in an exception being thrown. For example:
```
$my_array = array("name" => "John", "age" => 25);
echo $my_array["non_existent_key"]; // Output: NULL
$my_object = (object) array(
"name" => "John",
"age" => 25,
"address" => array(
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA"
)
);
echo $my_object->non_existent_key; // Output: NULL
```
In summary, to access the elements of an associative array in PHP, you can use either the
square bracket notation `[]` or the dot notation `->`, depending on your specific needs and the
structure of your data.
How do you create a record in python?

To create a record in Python, you can use various data structures such as lists, tuples,
dictionaries, or classes. Each of these structures has its own advantages and use cases, so the
choice depends on the specific requirements of your program.

1. Lists
A list is a collection of items that are ordered and changeable. You can create a record by
appending or inserting elements into a list. Here's an example:

record = ["John", "Doe", 25, "john.doe@example.com"]

In this example, the record contains four elements: first name, last name, age, and email
address.

2. Tuples
A tuple is similar to a list but is immutable, meaning its elements cannot be modified once
created. To create a record using a tuple, you can define it with parentheses. Here's an
example:
record = ("John", "Doe", 25, "john.doe@example.com")

3. Dictionaries
A dictionary is an unordered collection of key-value pairs. It allows you to access values
based on their associated keys rather than their position. To create a record using a dictionary,
you can define it with curly braces and specify the key-value pairs. Here's an example:
record = {
"first name": "John",
"last name": "Doe",
"age": 25,
"email": "john.doe@example.com"
}
In this example, the keys represent different attributes of the record.

4. Classes
If you want to create more complex records with additional functionality, you can define a
class. A class is a blueprint for creating objects that have attributes (variables) and methods
(functions). Here's an example:

```python
class Record:
def __init__(self, first_name, last_name, age, email):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.email = email

record = Record("John", "Doe", 25, "john.doe@example.com")


In this example, the class "Record" defines the structure of a record, and the `__init__`
method is used to initialize its attributes.

When creating a record in Python, you can choose the data structure that best suits your needs
based on factors such as mutability, order, and ease of access.
How do you access the elements of a record in python?
To access the elements of a record in Python, you can use either dot notation or square
bracket notation. The record can be represented as a dictionary or an object with attributes.

If the record is represented as a dictionary, you can access its elements using square bracket
notation. Each element in the dictionary has a key-value pair, where the key is used to access
the corresponding value. For example:
record = {"name": "John", "age": 25, "city": "New York"}
print(record["name"]) # Output: John
print(record["age"]) # Output: 25
print(record["city"]) # Output: New York
In this example, `record` is a dictionary with three elements. The keys are `"name"`, `"age"`,
and `"city"`, and the corresponding values are `"John"`, `25`, and `"New York"`.

If the record is represented as an object with attributes, you can use dot notation to access its
elements. Each element in the object corresponds to an attribute that can be accessed directly.
For example:

class Record:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city

record = Record("John", 25, "New York")


print(record.name) # Output: John
print(record.age) # Output: 25
print(record.city) # Output: New York

In this example, `Record` is a class that represents a record. The `__init__` method is used to
initialize the attributes of the object. The attributes `name`, `age`, and `city` can be accessed
using dot notation.

record = {"name": "John", "age": 25}


print(record.get("city")) # Output: None

record = Record("John", 25)


print(getattr(record, "city", None)) # Output: None

In the first example, `record.get("city")` returns `None` because the key `"city"` doesn't exist
in the dictionary. In the second example, `getattr(record, "city", None)` also returns `None`
because the attribute `city` doesn't exist in the object.
How do you create a union in python?
To create a union in Python, you can make use of the built-in `union` operator (`|`) or the
`union()` method provided by the `set` data type. A union operation combines two or more
sets and returns a new set that contains all the unique elements from the input sets.

Here is an example of using the `union` operator:


set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}

In this example, we have two sets `set1` and `set2`. The `union_set` is created by applying the
`|` operator between `set1` and `set2`, which combines all the elements from both sets into a
new set. The resulting set contains all the unique elements from both input sets.
How do you use a union in python?
In Python, the union operation is not directly available as a built-in function or operator.
However, you can achieve the union of two or more sets, lists, or other iterable objects using
various methods and techniques.

1. Using the set() Function:


The most straightforward way to perform a union in Python is by converting the iterable
objects into sets and then using the set union operation. The set data structure in Python
automatically eliminates duplicate elements, making it suitable for performing unions.

Here's an example of using the set() function to perform a union:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2)
print(union_set)

Output:

{1, 2, 3, 4, 5}

In this example, we create two sets `set1` and `set2`. We then use the `union()` method of
`set1` and pass `set2` as an argument to perform the union operation. The resulting set
contains all the unique elements from both sets.

2. Using the "|" Operator:


Python provides an alternative syntax for performing unions using the "|" (pipe) operator.
This operator can be used with sets or other iterable objects that support this operation.

Here's an example of using the "|" operator to perform a union:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1 | set2


print(union_set)

Output:
{1, 2, 3, 4, 5}

In this example, we use the "|" operator between `set1` and `set2` to perform the union
operation. The resulting set is the same as in the previous example.

3. Using the itertools.chain() Function:


If you have multiple iterable objects that are not sets, you can use the `itertools.chain()`
function to combine them into a single iterable object. Then, you can convert this combined
iterable into a set to obtain the union.

Here's an example of using `itertools.chain()` to perform a union:


import itertools

list1 = [1, 2, 3]
list2 = [3, 4, 5]

union_set = set(itertools.chain(list1, list2))


print(union_set)

Output:
{1, 2, 3, 4, 5}

In this example, we import the `itertools` module and use the `chain()` function to combine
`list1` and `list2` into a single iterable. We then convert this iterable into a set using the `set()`
function to obtain the union.
How do you create a set in python?
Sets are a collection of unique items that can be used to store and manipulate data in Python.
To create a set in Python, you can use the built-in `set()` function. Here's how:

Step 1: Define the Set


To create a set, you simply need to place the items you want to include in the set inside a set
literal. A set literal is a curly brace `{}` that contains the items you want to include in the set,
separated by commas. For example:
```
my_set = {1, 2, 3, 4, 5}
```
This creates a set called `my_set` that contains the integers 1, 2, 3, 4, and 5.

Step 2

Add Items to the Set


Once you have created a set, you can add items to it using the `add()` method. For example:
```
my_set.add(6)
my_set.add("apple")
```
This adds the integer 6 and the string "apple" to the set `my_set`.

Step 3

Remove Items from the Set


To remove an item from a set, you can use the `discard()` method. For example:
```
my_set.discard(2)
```
This removes the integer 2 from the set `my_set`.

Check if an Item is in the Set


To check if an item is in a set, you can use the `in` operator. For example:
```
print(2 in my_set) # Output: True
print(6 not in my_set) # Output: True
```
This checks if the integer 2 and the integer 6 are in the set `my_set`. The first one returns
`True`, because 2 is in the set, and the second one returns `False`, because 6 is not in the set

Convert a List to a Set


If you have a list of items, you can convert it to a set using the `set()` function. For example:
```
my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)
```
This converts the list `[1, 2, 3, 4, 5]` to a set called `my_set`.

Use Sets in Your Code


Now that you know how to create and manipulate sets in Python, you can start using them in
your code. For example, you could use a set to store a list of unique words in a text
document, or to keep track of a list of unique users who visit a website. The possibilities are
endless!
How do you add and remove elements from a set?
To add and remove elements from a set, you can use various methods and operations
depending on the programming language or data structure you are working with. In this
response, we will provide a general overview of how to perform these operations.

Adding Elements to a Set:


To add elements to a set, you typically use the "add" operation. This operation allows you to
insert a new element into the set if it doesn't already exist. The process usually involves
checking if the element is already present in the set and then adding it if it is not.

Here is an example of how you can add elements to a set using Python:

```python
my_set = {1, 2, 3} # Existing set
my_set.add(4) # Add element 4 to the set
my_set.add(2) # Element 2 already exists, so it won't be added again

print(my_set) # Output: {1, 2, 3, 4}


```

In this example, the `add()` method is used to add elements to the set. The first call adds the
element 4, while the second call does nothing since element 2 is already present.

Removing Elements from a Set:


To remove elements from a set, you can use different methods or operations based on your
programming language or data structure. The most common approaches include using the
"remove" operation or the "discard" operation.

Here is an example of how you can remove elements from a set using Python:

my_set = {1, 2, 3, 4} # Existing set


my_set.remove(3) # Remove element 3 from the set

print(my_set) # Output: {1, 2, 4}

In this example, the `remove()` method is used to remove an element from the set. The call
`my_set.remove(3)` removes the element 3 from the set, resulting in the updated set `{1, 2,
4}`.

It's important to note that if you try to remove an element that doesn't exist in the set using the
`remove()` method, it will raise a "KeyError" exception. To avoid this, you can use the
`discard()` method instead, which removes an element if it exists but does nothing if it
doesn't.
my_set = {1, 2, 4} # Existing set
my_set.discard(3) # Element 3 doesn't exist, so nothing happens

print(my_set) # Output: {1, 2, 4}

In this example, the `discard()` method is used to remove an element from the set. Since
element 3 doesn't exist in the set, calling `my_set.discard(3)` has no effect on the set.

In summary, adding elements to a set involves using the "add" operation or method specific
to your programming language or data structure. Removing elements from a set can be done
using the "remove" operation or the "discard" operation, depending on whether you want to
raise an exception or not when trying to remove a non-existent element.
How do you create a pointer in python?
In Python, there is no direct way to create a pointer like in some other programming
languages such as C or C++. However, Python does have a concept called "references" that
can be used to achieve similar functionality.

In Python, every variable is essentially a reference to an object. When you assign a value to a
variable, you are actually binding that variable to the memory address where the object is
stored. This means that variables in Python act as pointers to objects.

To demonstrate this concept, let's consider an example:

```python
a = 10
b=a
```
In this example, `a` and `b` are both references to the same integer object with a value of 10.
If we change the value of `a`, it will not affect the value of `b`, as they are separate
references.

```python
a = 20
print(b) # Output: 10
```

However, it's important to note that Python handles memory management automatically
through a process called garbage collection. This means that you don't have direct control
over memory addresses like you would in lower-level languages.

If you want to achieve pointer-like behavior in Python, you can use mutable objects such as
lists or dictionaries. These objects can be modified in-place without changing their reference.
For example:

list1 = [1, 2, 3]
list2 = list1

list1.append(4)
print(list2) # Output: [1, 2, 3, 4]

In this example, both `list1` and `list2` refer to the same list object. When we modify `list1`
by appending an element, the change is reflected in `list2` as well.

It's worth mentioning that while Python doesn't have explicit pointers like in some other
languages, it does provide the `id()` function, which returns the unique identifier of an object.
This identifier can be thought of as a memory address, although it's not directly accessible or
manipulable.

a = 10
print(id(a)) # Output:

In conclusion, while Python doesn't have traditional pointers like in languages such as C or
C++, it uses references to achieve similar functionality. Variables in Python act as references
to objects, and changes made to one reference can affect other references pointing to the same
object. However, Python handles memory management automatically, so you don't have
direct control over memory addresses.
How do you use a pointer in python?
In Python, pointers are not used in the same way as they are in languages like C or Java.
Instead of using pointers to directly manipulate memory, Python uses references to objects to
store and manipulate data. Here's how you can use pointers in Python:

Using Pointers with NumPy


One way to use pointers in Python is through the NumPy library. NumPy provides support
for arrays and matrices, which can be accessed using pointers. To access an array or matrix
using a pointer, you can use the `pointer` attribute of the array or matrix object. For example:
```
import numpy as np

Create an array of integers


arr = np.array([1, 2, 3, 4, 5])
Get a pointer to the array
ptr = arr.pointer()
Print the contents of the array using the pointer
print(ptr) # Output: [1, 2, 3, 4, 5]
```
In this example, we create an array of integers using NumPy and then get a pointer to the
array using the `pointer()` method. We can then use the pointer to print the contents of the
array.

Using Pointers with Pandas


Another way to use pointers in Python is through the Pandas library. Pandas provides support
for data frames and series, which can be accessed using pointers. To access a data frame or
series using a pointer, you can use the `__getitem__` method of the data frame or series
object. For example:
```
import pandas as pd

Create a data frame with two columns


df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
Get a pointer to the data frame
ptr = df.__getitem__(['A', 'B'])
Print the contents of the data frame using the pointer
print(ptr) # Output: [[1, 4], [2, 5], [3, 6]]
```
In this example, we create a data frame with two columns using Pandas and then get a pointer
to the data frame using the `__getitem__` method. We can then use the pointer to print the
contents of the data frame.

Using Pointers with Other Libraries


There are other libraries in Python that provide support for pointers, such as the `ctypes`
library. The `ctypes` library allows you to define custom data types and functions that can be
used with pointers. For example:
```
import ctypes

Define a function that takes a pointer to an integer as an argument


def add_int(ptr):
return ctypes.cast(ptr, ctypes.c_int).value + 1

Create a pointer to an integer


ptr = ctypes.c_int(1)
Call the function with the pointer
result = add_int(ptr)
Print the result
print(result) # Output: 2
```
In this example, we define a function that takes a pointer to an integer as an argument and
returns the result of adding 1 to the value pointed to. We then create a pointer to an integer
and call the function with the pointer. The result is printed to the console.

You might also like