Question 31.Why is there an error in the code and how would you fix it?
def foo(a=1, b=2):
return a + b
x = foo() - 1
Question 32. What will the following script output? Please try to do this mentally if you can.
c = 1
def foo():
return c
c = 3
print(foo())
3
Explanation:
This is what happens here:
Line 1: c is assigned 1.
Line 2-3: We create a function which if executed will return the value of c .
Line 4: c is updated and is now equal to 3.
Line 5: We tell the blueprint to print out the value of c which is at the point where we call the function 3.
Question 33. Here's another similar exercise. What will the following script output? Try to do this mentally if you can.
c = 1
def foo():
c = 2
return c
c = 3
print(foo())
Question 34. The following script throws a NameError in the last line saying that c is not defined. Please fix the function so that there is no error and the last line is able to print out the value of c (i.e. 1 ).
def foo():
c = 1
return c
foo()
print(c)
Expected output:
1
def foo():
global c
c = 1
return c
foo()
print(c)
Explanation:
Adding global c fixes the code. That line makes available name c in the global namespace. Therefore, print is able to access variable c .
Question 35. Create a function that takes any string as input and returns the number of words for that string.
d = {"a": 1, "b": 2, "c": 3}
Expected output:
6
def count_words(strng):
strng_list = strng.split()
return len(strng_list)
print(count_words("Hey there it's me!"))
Explanation:
We're using split here which is a string method that splits a string into several strings given a separator passed inside the brackets. When you don't pass a separator, split will split a string at white spaces. This will output a list of strings..Applying len to that list returns the number of list items, so the number of words.
Question 36. Please download the words1.txt file from the attachment and then create a Python function that takes a text file as input and returns the number of words contained in the text file.
Expected output:
10
def count_words(filepath):
with open(filepath, 'r') as file:
strng = file.read()
strng_list = strng.split(" ")
return len(strng_list)
print(count_words("words1.txt"))
Note: For the above script to work, you should have a file named words1.txt in the same directory with the Python script.
Explanation:
The function here takes as input a file path. If the file path is in the same directory with your Python script, you can simply pass in the file name as in the above script. If your text file is somewhere else, then you need to pass the full path when calling the function. Example:
print(count_words("C:/Home/words1.txt"))
The rest of the script consists of opening the file in read mode, loading the text into a string using read and then splitting and counting the number of words.
Question 37. Create a function that takes a text file as input and returns the number of words contained in the text file.
Please take into consideration that some words can be separated by a comma with no space.
For example "Hi,it's me." would need to be counted as three words.
For your convenience, you can use the text file in the attachment.
def count_words(filepath):
with open(filepath, 'r') as file:
string = file.read()
string = string.replace(",", " ")
string_list = string.split(" ")
return len(string_list)
print(count_words("words2.txt"))
Explanation 1:
This solution is like the solution of the previous exercise with the difference that before splitting
we are replacing all commas with a space which will let the split method count the number of words.
Answer 2:
import re
def count_words_re(filepath):
with open(filepath, 'r') as file:
string = file.read()
string_list = re.split(",| ", string)
return len(string_list)
print(count_words_re("words2.txt"))
Explanation 2:
This alternative solution uses the built-in re module which provides regular expression matching operations.
We're using the split method of that module and the expression ",| " is meant to replace commas with spaces.
Using methods from the re module can be more appropriate than Python built-in methods when string operations are complicated.
However, for this simple scenario the re module could be skipped.
Question 38. The following code is supposed to print out the square root of 9, but it throws an error instead because another line before that is missing. Please fix the script so that it prints out the square root of 9.
math.sqrt(9)
Expected output:
3
import math
math.sqrt(9)
Explanation:
Since you get the error that math is not defined, that means math is not in the default namespace.
With some internet research you could easily find out that math is a module,
so you simply need to do import math
Question 39. The script is supposed to output the cosine of angle 1 radian, but instead it is throwing an error. Please fix the code so that it prints out the expected output.
import math
print(math.cosine(1))
Expected output:
0.5403023058681397
import math
print(math.cos(1))
Question 40. Please try to guess what is missing in the following code and add the missing part so that the code works fine.
import math
print(math.pow(2))
Hint: Simply pass two arguments.
import math
print(math.pow(2, 3))
Explanation:
You could pass any number there, so 3 is just an example.
As the error suggested, you simply needed to pass a second argument so that pow can calculate the power of the first argument.
If you didn't understand the error, you could do help(math.pow) to see how the method works.
Question 41. Create a script that generates a text file with all letters of English alphabet inside it, one letter per line.
Hint: You need to open a file in write mode, iterate through a list of letters, and use a write method in each iteration.
import string
with open("letters.txt", "w") as file:
for letter in string.ascii_lowercase:
file.write(letter + "\n")
Explanation:
The ascii_lowercase property of the string module is quite helpful here to generate a string of all letters.
Then we create a file and while the file is open, we iterate through the string and apply the write method in
each iteration to write the letters in the text file.
We are also appending \n to each letter which is a special character that creates break lines.
That makes sure to separate the letters in different lines.
Question 42. Print out in each line the sum of homologous items of the two sequences.
a = [1, 2, 3]
b = (4, 5, 6)
Expected output:
5
7
9
a = [1,2,3]
b = [4,5,6]
for i, j in zip(a,b):
print(i + j)
Question 43. Create a script that generates a file where all letters of English alphabet are listed two in each line.
The inside of the text file would look like:
ab
cd
ef
and so on
Hint 1: Use the zip function to iterate through two slices of the letters sequence.
Hint 2: One slice would be string.ascii_lowercase[0::2] and the other string.ascii_letters[1::2]
import string
with open("letters.txt", "w") as file:
for letter1, letter2 in zip(string.ascii_lowercase[0::2], string.ascii_letters[1::2]):
file.write(letter1 + letter2 + "\n")
Question 44. Create a script that generates a file where all letters of English alphabet are listed three in each line.
The inside of the text file would look like:
abc
def
ghi
and so on.
import string
letters = string.ascii_lowercase + " "
slice1 = letters[0::3]
slice2 = letters[1::3]
slice3 = letters[2::3]
with open("letters.txt", "w") as file:
for s1, s2, s3 in zip(slice1, slice2, slice3):
file.write(s1 + s2 + s3 + "\n")
Explanation:
This is like the previous exercise with the difference that we're using a different slicing step of 3 here.
Another difference is that we are adding one white spaces to ascii_lowercase
so that we get a string of 27 items as opposed to 26 that ascii_lowercase provides.
By slicingascii_lowercase we would get two slices with a length of 9 and one slice with a length of 8.
That means the iteration would stop at the shortest slice so letters y and z wouldn't be written in the file.
That's why we add a white space so we get three slices each with a length of 9.
That means we get 9 iterations and not 8 as we would get with the original ascii_lowercase string.
The 9th iteration would write letters y and z in the file.
Note that this solution might not be the best and there are surely improvements to be made so the script works with any number of letters.
Question 45. Please create a script that generates 26 text files named a.txt, b.txt, and so on up to z.txt.
Each file should contain a letter reflecting its filename.
So,
a.txt will contain letter a, b.txt will contain letter b and so on.
Hint: Start iterating with a for loop and create a file in each iteration.
import string, os
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_lowercase:
with open("letters/" + letter + ".txt", "w") as file:
file.write(letter + "\n")
with open("letters.txt", "w") as file:
for letter1, letter2 in zip(string.ascii_lowercase[0::2], string.ascii_letters[1::2]):
file.write(letter1 + letter2 + "\n")