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

7 Days Analytics Course 3feiz7 3

The document provides examples of using various Python functions and modules. It explains functions like zip(), sorted(), max(), min(), join(), replace(), input(), and modules like random and re. It also covers topics like creating dictionaries from lists, removing duplicates from lists, and handling exceptions.

Uploaded by

anupamakarupiah
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)
12 views8 pages

7 Days Analytics Course 3feiz7 3

The document provides examples of using various Python functions and modules. It explains functions like zip(), sorted(), max(), min(), join(), replace(), input(), and modules like random and re. It also covers topics like creating dictionaries from lists, removing duplicates from lists, and handling exceptions.

Uploaded by

anupamakarupiah
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/ 8

17

python

text1 = "Hello"
text2 = "123"
print(text1.isalpha())
print(text2.isdigit())
How do you create a dictionary from two lists in Python?
You can create a dictionary from two lists in Python using the 'zip()' function to combine the lists
and the 'dict()' function to convert the result into a dictionary.

Example:

python

keys = ["name", "age", "country"]


values = ["John", 30, "USA"]
my_dict = dict(zip(keys, values))
print(my_dict)
What is the purpose of the 'zip()' function in Python?
The 'zip()' function in Python is used to combine multiple iterables into a single iterable of tuples.
It returns an iterator that aggregates elements from each of the iterables.

Example:

python

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
zipped = list(zip(list1, list2))
print(zipped)

How do you remove duplicates from a list in Python?


You can remove duplicates from a list in Python by converting it to a set, which automatically
removes duplicates, and then converting it back to a list. Alternatively, you can use list
comprehension to create a new list with unique elements.

Example (using set):

python

my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = list(set(my_list))
print(new_list)
Example (using list comprehension):
18

python

my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = []
[new_list.append(x) for x in my_list if x not in new_list]
print(new_list)
Explain the use of the 'sorted()' function in Python.
The 'sorted()' function in Python is used to sort elements in an iterable in ascending order and
returns a new list. It can also accept a 'reverse' argument to sort in descending order.

Example:

python

my_list = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_list = sorted(my_list)
print(sorted_list)
How do you find the maximum and minimum values in a list in Python?
You can find the maximum and minimum values in a list in Python using the 'max()' and 'min()'
functions, respectively.

Example:

python

my_list = [3, 1, 4, 1, 5, 9, 2, 6]
print(max(my_list))
print(min(my_list))
What is the purpose of the 'enumerate()' function in Python?
The 'enumerate()' function in Python is used to add a counter to an iterable and returns it as an
enumerate object. This can be useful for obtaining an indexed list while iterating.

Example:

python

my_list = ["apple", "banana", "cherry"]


for index, value in enumerate(my_list):
print(index, value)
How do you create a virtual environment in Python?
You can create a virtual environment in Python using the 'venv' module, which is part of the
standard library. You can create a virtual environment by running 'python -m venv myenv' in the
command line.
19

Explain the purpose of the 'join()' method in Python.


The 'join()' method in Python is used to join elements of an iterable, such as a list, into a string.
It concatenates each element of the iterable with a specified separator.

Example:

python

my_list = ["apple", "banana", "cherry"]


separator = ", "
result = separator.join(my_list)
print(result)
How do you check the type of a variable in Python?
You can check the type of a variable in Python using the 'type()' function, which returns the data
type of the variable.

Example:

python

x=5
print(type(x))
What is the purpose of the 'replace()' method in Python strings?
The 'replace()' method in Python strings is used to replace occurrences of a specified substring
with another substring. It returns a new string and does not modify the original string.

Example:

python

text = "Hello, world!"


new_text = text.replace("world", "Python")
print(new_text)
How do you perform arithmetic operations in Python?
You can perform arithmetic operations in Python using the standard arithmetic operators, such
as '+', '-', '*', '/', and '%', for addition, subtraction, multiplication, division, and modulo,
respectively.

Example:

python

x=5
20

y=3
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x % y) # Modulo
Explain the use of the 'input()' function in Python.
The 'input()' function in Python is used to accept user input from the console. It prompts the user
with a message and waits for the user to enter a value, which is then returned as a string.

Example:

python

name = input("Enter your name: ")


print("Hello, " + name)
How do you define a class in Python?
You can define a class in Python using the 'class' keyword followed by the class name and a
colon. You can then define class attributes and methods within the class.

Example:

python

class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
What is the purpose of inheritance in Python classes?
Inheritance in Python allows a class to inherit attributes and methods from another class. It
facilitates code reusability and helps create a hierarchy of classes. Subclasses can override or
extend the functionality of the superclass.

What is the purpose of inheritance in Python classes?


Inheritance in Python allows a class to inherit attributes and methods from another class. It
facilitates code reusability and helps create a hierarchy of classes. Subclasses can override or
extend the functionality of the superclass.

Explain the concept of method overriding in Python.


Method overriding in Python occurs when a subclass redefines a method from its superclass.
This allows the subclass to provide a specific implementation of the method that is different from
the superclass. It helps customize the behavior of a method for a particular subclass.

How do you create a module in Python?


21

You can create a module in Python by saving a Python script with the '.py' extension, which
contains various functions, classes, and variables. You can then import this module into other
Python scripts to use its functionality.

What is the purpose of the 'super()' function in Python?


The 'super()' function in Python is used to access methods and attributes from a superclass. It
allows you to call methods of the superclass in the subclass, enabling you to access and use
the superclass's functionality.

How do you handle multiple exceptions in Python?


You can handle multiple exceptions in Python using multiple 'except' blocks, each corresponding
to a specific type of exception. You can also use a single 'except' block to handle multiple
exceptions using tuple or list syntax.

Example (handling multiple exceptions separately):

python

try:
# Code that may raise exceptions
pass
except ValueError:
# Handling ValueError
pass
except KeyError:
# Handling KeyError
pass
Example (handling multiple exceptions together):

python

try:
# Code that may raise exceptions
pass
except (ValueError, KeyError) as e:
# Handling ValueError and KeyError
pass
Explain the purpose of the 'is' and '== ' operators in Python.
The 'is' operator in Python checks if two variables refer to the same object, while the '=='
operator checks if two variables have the same value. The 'is' operator checks for object
identity, whereas the '==' operator checks for equality.

How do you use the 'random' module in Python?


22

You can use the 'random' module in Python to generate pseudo-random numbers, select
random elements from a sequence, and shuffle sequences. It provides various functions for
different randomization tasks.

Example (using the random module to generate a random number):

python

import random
print(random.randint(1, 100)) # Generates a random integer between 1 and 100
What is the purpose of the 'with' statement in Python?
The 'with' statement in Python is used to wrap the execution of a block of code within a context
manager. It simplifies resource management by ensuring that acquired resources are properly
released, even in the case of exceptions.

Explain the purpose of the 're' module in Python.


The 're' module in Python provides support for regular expressions. It allows you to work with
patterns and perform various operations such as pattern matching, searching, and substitution
within strings.

How do you install external packages in Python using pip?


You can install external packages in Python using the pip package manager, which comes
pre-installed with most Python distributions. You can use the 'pip install' command followed by
the name of the package to install it from the Python Package Index (PyPI).

Example:

pip install package_name


23

Day 3 - Pandas Round 1 Questions

How to create a DataFrame from a dictionary in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
print(df)
Explanation: This code creates a DataFrame from a dictionary where the keys are the column
names and the values are the data for each column.

How to select a single column from a DataFrame in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
selected_column = df['Name']
print(selected_column)
Explanation: This code selects the 'Name' column from the DataFrame and stores it in a
separate variable.

How to filter rows in a DataFrame based on a condition in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
filtered_df = df[df['Age'] > 30]
print(filtered_df)
Explanation: This code filters the DataFrame to select rows where the 'Age' column is greater
than 30.
24

How to add a new column to a DataFrame in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
df['Gender'] = ['Male', 'Female', 'Male', 'Female']
print(df)
Explanation: This code adds a new column 'Gender' to the DataFrame and assigns values to it.

How to drop a column from a DataFrame in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
df = df.drop('Age', axis=1)
print(df)
Explanation: This code drops the 'Age' column from the DataFrame using the drop method.

How to rename columns in a DataFrame in Pandas?

python

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],


'Age': [28, 33, 45, 29]}
df = pd.DataFrame(data)
df = df.rename(columns={'Name': 'Full Name', 'Age': 'Years'})
print(df)
Explanation: This code renames the 'Name' column to 'Full Name' and the 'Age' column to
'Years' in the DataFrame.

How to read a CSV file into a DataFrame in Pandas?

python

You might also like