







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A collection of exercises and answers related to python programming for data science, focusing on fundamental concepts and practical applications. It covers topics such as data types, operators, control flow, functions, and data structures, offering a valuable resource for beginners and those seeking to enhance their python skills for data analysis.
Typology: Exams
1 / 13
This page cannot be seen from the preview
Don't miss anything!
what's the diff btwn / and // in python? ANSWER the single one always result in float while double slash result in integer
run code in Jupyter ANSWER Shift + enter
import sys
print(sys.version) ANSWER Find which version of python u are using in jupyter
sys is a module which includes lots of system specific parameters and functions including Python version being used. Before using it. - ANSWER we must explicitly import it.
In python to write comments use the. symbol - ANSWER hash
The. message in tells you: 1. where the error occurred (more useful in large notebook cells or scripts), and 2. what kind of error it was (NameError) - ANSWER error.message in python
Python is what is called an,,,,,,,,,,,,,language. Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution. Instead, Python reads your script line by line when it runs your program. Python will then terminate the execution of the whole program in case of finding an error this is, if that error is an unexpected one - and hence, not handled - by the programmer, something that we'll consider in more advanced detail later on during the course. - ANSWER interpreted language
Object-oriented Python language
There are many different types of objects in Python.such as - ANSWER strings, integers and floats.
strings, integers and floats. float(x) does what - ANSWER cast x to flot
Convert string to integer - ANSWER int('1')
String, we can index string using numbers Musa[1] - ANSWER indexing
Replicate String = 3* Names - ANSWER NamesNamesNames
Names.Find('isa').find substring. - ANSWER the method finds starting index of a substring
Find number of character : len("Michael Jackson") - ANSWER find length of charcter
Slicing : We can get more than one characters in a string by slicing. NAME = "TIJJANI"
○ - ANSWER NAME[0:4] = TIJJ
Concatenate String IN PYTHON - ANSWER Statement = Name + "is the best"
replace the old substring with the new target substring is the segment has been found in the string
A = "Michael Jackson is the best"
B = A.replace('Michael', 'Janet') - ANSWER Replace method:
find the first index of the sub-string - ANSWER G.find('snow')
Split string - ANSWER "Isa Musa".split() =" Isa" "Musa".
How to Split using specific xter, below will split with, - ANSWER "Isa Musa".split("," )
cloning a list so that we do not change original copied - ANSWER If we change A, B will not change, but if we do normal assigment, B will change if A is change B = A[:]
- What diff btwe List and Tuple - ANSWER Both lists and tuples are sequence data types that can store a collection of items. Each item stored in a list or a tuple can be of any data type. And you can also access any item by its index. So the question is, are they different at all?
main diff betwe tuple and list - ANSWER The major difference between the lists and a tuples is a fact that lists are mutable whereas tuples are immutable. if you know that your object is immutable, use tuples. Otherwise, use lists.
- Concatenate Tuples? - ANSWER We can concatenate or combine tuples by using the
Can we Nest Tuple? - ANSWER A tuple can contain another tuple as well as other more complex data types. This process is called 'nesting'
We can use the second index to access other tuples as demonstrated in the figure: e.g A[1][0] or. - ANSWER A[1,0]
Show continuation of line using \ in. - ANSWER python jupyter
What is a List - ANSWER A list is a sequenced collection of different objects such as integers, strings, and other lists as well. The address of each element within a list is called an index. An index is used in order to access and refer to items within a list.
What can List contain? - ANSWER A Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures.
extend and append method - ANSWER We can use the method extend to add new elements to the list:
Another similar method is append. If we apply append instead of extend, we add one element to the lis
We can turn a string into a list using split. For example, the function split converts every sequence of characters in a string, separated by a space, into an item in a list: hard rock'.split() returns ['hard', 'rock'] - ANSWER split function
Copy and Clone List
When we set one variable equal to both and are referencing the same list in memory: - ANSWER You can clone list A using the following syntax: Clone copy-by-value the list A
○ B = A[:]
○ Now if you change A, B will not change:
Dictionariy - ANSWER Dictionaries are a kind of collection in Python. If you remember, a list is integer indexes. These are like addresses. A list also has elements. A dictionary has keys and values. The key is analogous to the index, they are like addresses but they don't have to be integers. They are usually character
How to create dictinary? - ANSWER To create a dictionary, we use curly brackets. The keys are the first elements. They must be immutable and unique. Each key is followed by a value separated by a colon. The values can be immutable, mutable, and duplicates. Each key and value pair is separated by a comma
Dictionary are rep by?? - ANSWER curly braces
In dictionary, keys have to be immutable and. - ANSWER unique
How to Use intersection method to find the intersection of album_list1 and album_list2 - ANSWER album_set1.intersection(album_set2)
How to Find union - ANSWER album_set1.union(album_set2)
Set??? - ANSWER In Python, a set is a collection of unique elements which is unordered. You can declare a set by using a curly bracket {}. Python will automatically discard the duplicate items:
for square in squares : print square.how to. - ANSWER loop in python
for i,x in enumerate(['A','B','C']): print(i,x) - ANSWER for with iteration value
- How to access each individual element after input - ANSWER dates = [1982,1980,1973]
N = len(dates)
for i in range(N):
print(dates[i])
enumerate function - ANSWER The enumerate() function takes a collection (e.g. a tuple) and renders it as an enumerate object.
The enumerate() function adds a counter as the key of the enumerate object.
What if we don't know when we want to stop the loop? What if we want to continue executing a code block while a certain condition is met? The while loop exists for the purpose of repeated execution based on a condition. The code block will keep executing until the given logical condition returns a False boolean value. - ANSWER when to use while loop?
Mult.mult(2, "x") will give - ANSWER "xx". Multiply
Sorted : return sorted sequence - ANSWER E,g sorted(list).will return the sorted list but the variable "list" will not change. It will stay the way it is. but using the method sort(), this will change the list
how to define function? - ANSWER Function start with def
Def add():
○ A+b
○ return
In python, function can't contain empty body.but. - ANSWER Python does not allow an empty body. However we can use the key word pass, which satisfies the condition.
Global function - ANSWER Global Scope: Variable outside function said to be in global scope and can be access anywhere after they are define• We can have variable of the same name. Global and Local variable• If a function is not define, within a function, python will check global scope
Here are some simple rules to define a function in Python: - ANSWER • Blocks of functions start with the word def followed by the name of the function and parentheses ().
**- There are input parameters or arguments that should go inside these parentheses.
Can we acces any variable declare inside function in python - ANSWER We can't
A a way to create global variables from within a function as follows: - ANSWER global
we use open and read function for.
The open() function returns a file object, which has a read() method for reading the content of the file: example - ANSWER f = open("demofile.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how many characters you want to return.what is an example - ANSWER f = open("demofile.txt", "r")
print(f.read(5))
You can return one line by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline()) - ANSWER By calling readline() two times, you can read the two first lines:
To read an entire file you can use the for loop as shown in this example to read all lines one at a time : - ANSWER f = open("demofile.txt", "r")
for x in f:
print(x)
It is a good practice to always close the file when you are done with it. - ANSWER f = open("demofile.txt", "r")
print(f.readline())
f.close()
It is a good practice to open a file using the with statement. This will automatically close the file even when the code throws an exception. Code within the indent block will run and then it will close the file object. - ANSWER with open(example1, "r") as file1:
FileContent = file1.read()
print(FileContent)
- # Check if file is closed - ANSWER • file1.closed
how to write line to file - ANSWER with open('/resources/data/Example2.txt', 'w') as writefile:
writefile.write("This is line A")
The method.write() works similar to the method.readline(), except instead of reading a new line it. - ANSWER writes a new line.
Copy file to another - ANSWER with open('Example2.txt','r') as readfile:
with open('Example3.txt','w') as writefile:
for line in readfile:
writefile.write(line)
Pandas - ANSWER Pandas, one of the most usable libraries when it comes to data analysis.
what is dependencies or libraries - ANSWER Dependencies or libraries are pre-written code to help solve problems.
what python object do you cast to a dataframe? - ANSWER Dictionary :Key is the colum and Value is the raws
how to find size of array? - ANSWER Size of array.Get the size of numpy array
a.size
how to get dimention of an arry? - ANSWER a.ndim
Dot product pf 2 numpy array is. - ANSWER np.dot(u, v)
what is Linspace? - ANSWER A useful function for plotting mathematical functions is "linespace". Linespace returns evenly spaced numbers over a specified interval. We specify the starting point of the sequence and the ending point of the sequence. The parameter "num" indicates the Number of samples to generate, in this case 5:.
np.linspace(-2, 2, num=5)
Accessing various elements of a Numpy Array - SOLUTION Access the element at the second row and third column : A[1, 2]
We can also access the elements by the following notation: A[1][2]
Access the element at the first row and first and second columns : A[0][0:2]
Access the element at the first and second rows and third column :A[0:2, 2]
creating matrix using numpy - ANSWER C = np.array([[1,1],[2,2],[3,3]]).not with double square bracket
Union definition - ANSWER Union of two given sets is the smallest set which contains all the elements of both the sets. Union of two given sets A and B is a set which consists of all the elements of A and all the elements of B such that no element is repeated. (Makes sure no elements are repeated)