0% found this document useful (0 votes)
12 views9 pages

Ans of Ps

The document provides an overview of various programming concepts in Python and C, including lists, tuples, user-defined functions (UDFs), loop structures, memory representation of arrays, and features of Python. It explains list methods, tuple operations, categories of UDFs, loop types with examples, and the memory layout of 2D arrays. Additionally, it covers typecasting in Python, the use of loc and iloc in Pandas, and common DataFrame functions.

Uploaded by

bloodbank3001
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)
12 views9 pages

Ans of Ps

The document provides an overview of various programming concepts in Python and C, including lists, tuples, user-defined functions (UDFs), loop structures, memory representation of arrays, and features of Python. It explains list methods, tuple operations, categories of UDFs, loop types with examples, and the memory layout of 2D arrays. Additionally, it covers typecasting in Python, the use of loc and iloc in Pandas, and common DataFrame functions.

Uploaded by

bloodbank3001
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/ 9

Q.1.

Explain list with its method

A list is a collection of items in Python. It is one of the most commonly used data structures in
Python. Lists are mutable, which means that their elements can be changed after they are created.

Some of the methods that can be used with lists are:

1. append() – adds an element to the end of the list

2. insert() – inserts an element at a specific position in the list

3. remove() – removes the first occurrence of an element from the list

4. pop() – removes and returns an element from a specific position in the list

5. sort() – sorts the elements of a list in ascending or descending order

For example, if we have a list called “numbers” containing [1, 2, 3], we can use these methods as
follows:

- To add an element to the end of the list:


- Numbers.append(4) # numbers will now be [1, 2, 3, 4]
- To insert an element at a specific position:
- Numbers.insert(1, 5) # numbers will now be [1, 5, 2, 3]
- To remove an element from the list:
- Numbers.remove(2) # numbers will now be [1, 5, 3]
- To remove and return an element from a specific position:
- X = numbers.pop(1) # x will be equal to 5 and numbers will now be [1, 3]
- To sort the elements of a list:
- Numbers.sort() # numbers will now be [1, 3]

Q.2.Explain tuple and operators which can be performed on tuple

Ans:-A tuple is a collection of ordered, immutable elements in Python. Once a tuple is created, its
elements cannot be changed. Tuples are similar to lists, but they are typically used for storing
related pieces of information that should not be modified.

Some of the operators that can be performed on tuples are:

1. Indexing – accessing individual elements of a tuple using their position

2. Slicing – accessing a range of elements in a tuple

3. Concatenation – combining two or more tuples into one

4. Repetition – creating a new tuple by repeating an existing one multiple times

5. Membership testing – checking if an element is present in a tuple

For example, if we have two tuples called “fruits” and “vegetables” containing (“apple”, “banana”)
and (“carrot”, “broccoli”) respectively, we can use these operators as follows:

- To access individual elements of a tuple:


- Print(fruits[0]) # prints “apple”
- To access a range of elements in a tuple:
- Print(vegetables[1:]) # prints (“broccoli”,)
- To combine two or more tuples into one:
- Food = fruits + vegetables # food will now be (“apple”, “banana”, “carrot”, “broccoli”)
- To create a new tuple by repeating an existing one multiple times:
- Repeated_fruits = fruits * 3 # repeated_fruits will now be (“apple”, “banana”, “apple”,
“banana”, “apple”, “banana”)
- To check if an element is present in a tuple:
- Print(“carrot” in vegetables) # prints True

Q.3.explain the categories of udf in c

Ans:- User-Defined Functions (UDF) in C programming language can be categorized


into five different categories based on their return type and parameter list. These
categories are: a) Function with no arguments and no return value. b) Function with
arguments and no return values. c) Function with arguments and one return value.
d) Function with no arguments but return value. e) Function which returns multiple
values. The first category of UDF does not receive any data from the calling function,
and similarly, when it does not return a value, the calling function does not receive
any data from the called function. The second category of UDF takes one or more
arguments but does not return any value. The third category of UDF takes one or
more arguments and returns a single value. The fourth category of UDF does not
take any argument but returns a single value. Finally, the fifth category of UDF takes
one or more arguments and returns multiple values. It is important to note that all
UDFs must be declared before they are used, and their declaration is also called a
function header. Additionally, there are three elements for using UDF: function
declaration, function definition, and function call. These concepts are explained in
detail on pages 16-18 of this PDF file.

Q.4.Explain the loop structure in Python with example

Ans:-In Python, there are two types of loops: for loops and while loops.

A for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of
code for each element in the sequence. The general syntax of a for loop is:

```

For variable in sequence:

# code to be executed

```

Here, “variable” is a new variable that takes on the value of each element in the sequence one at a
time, and “sequence” is the collection of elements to be iterated over.

For example, if we have a list called “numbers” containing [1, 2, 3], we can use a for loop to print
each element as follows:

```

For num in numbers:

Print(num)

```
This will output:

```

```

A while loop is used to execute a block of code repeatedly as long as a certain condition is true. The
general syntax of a while loop is:

```

While condition:

# code to be executed

```

Here, “condition” is an expression that evaluates to either True or False. The code inside the loop
will continue to execute as long as the condition remains True.

For example, if we want to print all even numbers between 0 and 10 using a while loop, we can do
so as follows:

```

Num = 0

While num <= 10:

Print(num)

Num += 2

```

This will output:

```

10

```
Q.5. Differentiate between structure and union
Ans:-
Q.7.

Q.10. Explainthe memory representation of 2d array in c


Ans:- In C programming language, a two-dimensional array is stored in memory as a
contiguous block of memory. The elements of the array are stored in either Row
Major Representation or Column Major Representation. In Row Major Representation,
the elements of the first row are stored first, followed by the second row, and so on.
This means that consecutive elements of a row are stored together in memory. For
example, consider a 2D array `arr[2][3]` with values `{1, 2, 3}, {4, 5, 6}`. In Row
Major Representation, the memory layout would be `{1, 2, 3, 4, 5, 6}`. On the other
hand, in Column Major Representation, the elements of the first column are stored
first followed by the second column and so on. This means that consecutive
elements of a column are stored together in memory. For example, consider a 2D
array `arr[2][3]` with values `{1, 2, 3}, {4, 5 ,6}`. In Column Major Representation,
the memory layout would be `{1 ,4 ,2 ,5 ,3 ,6}`. The choice between Row Major
Representation and Column Major Representation depends on how you plan to
access your two-dimensional array. If you plan to access your two-dimensional array
row-wise more frequently than column-wise then Row Major Representation is more
efficient. Similarly if you plan to access your two-dimensional array column-wise
more frequently than row-wise then Column Major Representation is more efficient.

Q.11. Explain multidimensional array in c


Ans:- In C programming language, a multidimensional character array is an array of
arrays where each element of the array is a character array. It is also known as a
two-dimensional character array. A multidimensional character array can be
declared and initialized in the following way: ``` char arr[3][5] = { {'H', 'e', 'l', 'l',
'o'}, {'W', 'o', 'r', 'l', 'd'}, {'!', '\0', '\0', '\0', '\0'} }; ``` In this example, we have
declared a 2D character array `arr` with three rows and five columns. Each row
represents a string of characters. The first two rows contain strings "Hello" and
"World", respectively, while the third row contains only one character "!". The null
characters ('\0') are used to terminate the strings. We can access individual
elements of the multidimensional character array using their row and column
indices. For example, to access the first element of the second row, we can use
`arr[1][0]`, which will give us the value `'W'`.

Q.12.Write a note on features of Python programming language

Ans:-Python is a popular high-level programming language that is known for its


simplicity, readability, and ease of use. Here are some of the key features of Python:

1. Easy to Learn: Python has a simple and easy-to-learn syntax that makes it
an ideal language for beginners.
2. Interpreted Language: Python is an interpreted language, which means
that it does not need to be compiled before running.
3. Object-Oriented Programming (OOP): Python supports OOP concepts such
as encapsulation, inheritance, and polymorphism.
4. Dynamic Typing: Python is dynamically typed, which means that you do
not need to declare the data type of a variable before using it.
5. Large Standard Library: Python comes with a large standard library that
provides support for many common programming tasks such as string
processing, file I/O, and networking.
6. Cross-Platform: Python can run on various operating systems such as
Windows, Linux, and macOS.
7. Third-Party Libraries: There are many third-party libraries available for
Python that can be used to extend its functionality.
8. Easy to Read and Write: The syntax of Python is designed to be easy to
read and write, making it easier for developers to create clean and
maintainable code.
Overall, these features make Python a versatile language that can be used for a
wide range of applications including web development, data analysis, machine
learning, and more.
Q.13.Explain list slicing
Ans:- List slicing is a technique in Python that allows you to extract a portion
of a list by specifying a range of indices. The syntax for list slicing is as
follows:

``` list[start:end:step] ```

Here, `start` is the index of the first element you want to include in the slice,
`end` is the index of the first element you want to exclude from the slice, and
`step` is the number of elements to skip between each element in the slice
(default value is 1). For example, consider the following list:

``` my_list = [1, 2, 3, 4, 5] ```


If we want to extract a slice containing elements at indices 1 and 2 (i.e., `[2,
3]`), we can use the following code:

``` my_slice = my_list[1:3] print(my_slice) # Output: [2, 3] ```

Note that we specified `start=1` and `end=3`, which means that we want to
include elements at indices 1 and 2 (but not index 3). We can also use
negative indices to count from the end of the list. For example:

``` my_slice = my_list[-3:-1] print(my_slice) # Output: [3, 4] ```

Here, we specified `start=-3` and `end=-1`, which means that we want to


include elements at indices -3 and -2 (but not index -1). Overall, list slicing is a
powerful technique that allows you to extract subsets of lists quickly and
easily.

Q.14. Explain typecasting in Python with proper example

Ans:- Typecasting in Python refers to the process of converting a variable from one
data type to another. Python is an object-oriented language, and so it uses classes to
define data types, including its primitive types. Casting in Python is therefore done
using constructor functions.

Here’s an example of typecasting in Python:


```
# Converting a string to an integer
My_string = “123”
My_int = int(my_string)
Print(my_int) # Output: 123
# Converting a float to an integer
My_float = 3.14
My_int = int(my_float)
Print(my_int) # Output: 3
# Converting an integer to a string
My_int = 123
My_string = str(my_int)
Print(my_string) # Output: “123”
# Converting a string to a float
My_string = “3.14”
My_float = float(my_string)
Print(my_float) # Output: 3.14
```
In the above example, we use the `int()`, `float()`, and `str()` constructor
functions to convert variables from one data type to another. For example, we
convert the string `”123”` to an integer using `int(“123”)`, which returns the
integer value `123`. Similarly, we convert the float value `3.14` to an integer
using `int(3.14)`, which returns the integer value `3`.
Overall, typecasting is a useful technique that allows you to convert variables
from one data type to another as needed in your program.

Q.15.explain loc and iloc function with example


Ans:- In Pandas, `loc` and `iloc` are two important functions that allow you to select
rows and columns from a DataFrame based on their labels or integer indices,
respectively. Here's an example of how to use `loc` and `iloc` functions in a
DataFrame:

``` import pandas as pd # Create a sample DataFrame data = {'name': ['Alice',


'Bob', 'Charlie', 'David'], 'age': [25, 30, 35, 40], 'gender': ['F', 'M', 'M', 'M']} df =
pd.DataFrame(data) # Select rows using loc function print(df.loc[1:2]) # Output: #
name age gender # 1 Bob 30 M # 2 Charlie 35 M # Select rows using iloc function
print(df.iloc[1:3]) # Output: # name age gender # 1 Bob 30 M # 2 Charlie 35 M #
Select columns using loc function print(df.loc[:, ['name', 'age']]) # Output: # name
age # 0 Alice 25 # 1 Bob 30 # 2 Charlie 35 # 3 David 40 # Select columns using iloc
function print(df.iloc[:, [0,1]]) # Output: # name age #0 Alice F #1 Bob M #2 David
M ```

In the above example, we first create a sample DataFrame with three columns:
`name`, `age`, and `gender`. We then use the `loc` and `iloc` functions to select
rows and columns from the DataFrame. To select rows using the `loc` function, we
specify the range of row labels we want to select (inclusive of both start and end
indices). For example, we use `df.loc[1:2]` to select rows with labels `'Bob'` and
`'Charlie'`. To select rows using the `iloc` function, we specify the range of integer
indices we want to select (exclusive of the end index). For example, we use
`df.iloc[1:3]` to select rows with integer indices `[1]` and `[2]`. To select columns
using the `loc` function, we specify a list of column labels we want

Q.16.Explain the function used on DataFrame of pandas

Ans:-Pandas is a popular Python library for data manipulation and analysis. It


provides a wide range of functions that can be used to work with DataFrames, which
are two-dimensional labeled data structures with columns of potentially different
types.

Here are some of the most commonly used functions in Pandas for working with
DataFrames:
1. `head()` and `tail()`: These functions allow you to view the first or last few
rows of a DataFrame, respectively.
2. `info()`: This function provides information about the DataFrame, such as
the number of rows and columns, column names, data types, and memory
usage.
3. `describe()`: This function provides summary statistics for each column in
the DataFrame, such as count, mean, standard deviation, minimum value,
maximum value, and quartiles.
4. `shape`: This attribute returns a tuple representing the dimensions of the
DataFrame (i.e., number of rows and columns).
5. `columns`: This attribute returns a list of column names in the DataFrame.
6. `iloc[]` and `loc[]`: These functions allow you to select rows or columns
from a DataFrame based on their integer indices or labels, respectively.
7. `drop()`: This function allows you to remove one or more rows or columns
from a DataFrame.
8. `fillna()`: This function allows you to fill missing values in a DataFrame
with a specified value or method (e.g., forward fill or backward fill).
9. `groupby()`: This function allows you to group rows in a DataFrame based
on one or more columns and perform aggregate operations (e.g., sum,
mean) on each group.
10.`merge()`: This function allows you to combine two DataFrames based on
one or more common columns.
Overall, these functions provide powerful tools for working with DataFrames in
Pandas and can help streamline your data analysis workflow.

You might also like