Mod 5 Flashcards

1
Q

How are Modules identified? What do they consist of? How do you use them? How do they relate to the Python standard library?

A
  • it is identified by its name
  • forms the Python standard library (along with functions)
  • consists of entities (functions, variables, constants, classes and objects)
  • must import before using
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write the code to import the math module

A

import math

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Where must the “import math” instruction be placed in the code?

A

It can go anywhere in the code, but must be placed before it is used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write the code to access the pi entity after the “import math” statement:

A
math.pi
for example (math.pi/2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write the import statement to access the pi entity within the math module:

A

from math import pi

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write the code to access the pi entity after the “from math import pi” statement:

A

pi

for example pi/2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Write the code to import all entities from the math module:

A

from math import *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
Write the code to import the math module with an alias of "m":
Also, is the math module name usable? (for example math.pi)
A

import math as m

no

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write the code to import the pi entity with an alias of “PI”

A

from math import pi as PI

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what does dir(module) do?

A

returns sorted list containing all entities names in the module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does the random() function do? What is its syntax?

A

produces a random float number between 0 and 1.

random()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does randrange() do? What is its syntax?

A

produces a random integer value within a specified range.

randrange(start, stop, step)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does choice() do? What is its syntax?

A

Takes in a sequence (list for example) and chooses a random element
choice(sequence)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does sample() do? What is its syntax?

A
draws the numbers randomly so they are unique and no duplicates
sample(sequence, # to choose)
sample of code:
from random import *
list=[1,2,3,4,5]
print(sample(list,3))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the platform module do? What of the platform() function?

A
module - underlying platforms data (hardware, operating system, interpreter version info)
function - environment description 
Sample of code:
from platform import platform
print(platform())
Linux-4.4.0-206-generic-x86_64-with
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the machine() function do?

A
See generic name of the processor
Sample of code:
from platform import machine
print(machine())
x86_64
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does the processor() function do?

A
See real processor name (if possible)
Sample of code:
from platform import processor
print(processor())
#returns nothing for me
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the system() function do?

A
See Operating System name
Sample of code:
from platform import system
print(system())
Linux
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does the version() function do?

A
See Operating System version
Sample of code:
from platform import system
print(version())
#238-Ubuntu SMP Tue Mar 16 07:52:37 UTC 2021
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the python_implementation() function do?

A
see the python implementation
Sample of code:
from platform import python_implementation
print(python_implementation())
CPython
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does python_version_tuple function do?

A
see 3 element function with the major part of Pythons version, the minor part, the patch level number
Sample of code:
from platform import python_version_tuple
for atr in python_version_tuple():
   print(atr)
3
7
10
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do functions, modules and packages relate to each other?

A

Packages contains modules and modules contain functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When a module is imported what happens to the module and its content?

A
  • its content is implicitly executed by Python

- it initializes (which only happens once)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What happens to __name__ when its file is ran?

What happens when a file with __name__ is imported?

A
  • when you run a file directly, its __name__ variable is set to __main__
  • when a file is imported as a module, its __name__ variable is set to the files name (excluding .py)
    Sample of code:
    module.py file:
    print(“I like python”) #output: I like python
    print(__name__) output: __main__
    main.py file:
    import file #output: I like python
    module
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

When underscores are added before and after a variable name what does it do?

A

It makes the variable personal/private. It is a convention however and users may or may not obey it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

True or False: Python is able to treat zip files as ordinary folders

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What module is the path variable from? What does it do? Explain its behavior?

A
  • Accessible through sys module
  • It stores all locations that are searched to find a module (module requested by the import instruction)
  • searches in order, based on the list
  • the search starts with the first path’s element
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Write the code to find a module, start the search in “‘C:\Users\user\py\modules” folder:

A
from sys import path
path.append('..\\modules')
import module
or
from sys import path
path.insert(1, 'C:\\Users\\user\\py\\modules')
import module
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do you transform a folder directory to a Python package?

A

Initialize by including the “__init__.py” file inside the package’s folder.
The content of the file is executed when any of the packages modules are imported. You can leave the file empty if you there are no special initializations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Facts about the __init__.py file (4):

A
  • The content of the file is executed when any of the packages modules are imported.
  • You can leave the file empty if you there are no special initializations.
  • the file can go anywhere in the package
  • can have multiple init files per package
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Where do you put the subtree to make it accessible to Python?

A

anywhere

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Write the code to access the funS() function from the sigma module from the best, good, extra package(3):

A
from sys import path
path.append('..\\packages')
import extra.good.best.sigma
print(extra.good.best.sigma.funS())
or
from sys import path
path.insert(1, 'C:\\Users\\user\\py\\modules')
from extra.good.best.sigma import funS
print(funS())
or 
from sys import path
path.append('..\\packages')
import extra.good.best.sigma as sig
print(sig.funS())
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are the 2 steps that Python does when raising an exception?

A
  1. Stops the program

2. Creates data called an exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What happens when an exception is handled? What of when it is not handled?

A
  • the program will resume and execution can continue

- The program will be forcibly terminated and user will see an error message in the console

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the output of the code when 1 and 1 are inputted?
firstNumber = int(input(“Enter the first number: “))
secondNumber = int(input(“Enter the second number: “))

try:
print(firstNumber / secondNumber)
except:
print(“This operation cannot be done.”)

print(“THE END.”)

A

1.0

THE END.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is the output of the code when 1 and 0 are inputted?
firstNumber = int(input(“Enter the first number: “))
secondNumber = int(input(“Enter the second number: “))

try:
print(firstNumber / secondNumber)
except:
print(“This operation cannot be done.”)

print(“THE END.”)

A

This operation cannot be done.

THE END.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q
What is the output of:
try:
    print("1")
    x = 1 / 0
    print("2")
except:
    print("Oh dear, something went wrong...")

print(“3”)

A

1
Oh dear, something went wrong…
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Facts about exceptions(8):

A
  • except branches are searched in the same order as they appear in the code
  • cannot duplicate exception names
  • must have at least one except branch and cannot be used without try
  • if any except branches are executed no other branches will be visited
  • each exception raised falls into the first matching branch
  • if none of the except branches matches the raised exception, the exception remains unhandled
  • if an unnamed except branch exists, it must be the last
  • put general exceptions towards the end
39
Q

What is the name of the root exception?

A

BaseException

40
Q
Is the below code legal?
def badFun(n):
    try:
        return 1 / n
    except (ArithmeticError, BaseException):
        print("Arithmetic Problem!")
    return None

badFun(0)

print(“THE END.”)

A

Yes

41
Q

True or False: If an exception is raised inside a function, it can be handled inside the function and outside the function.

A

True

42
Q

What does raise do?

A

The keyword prompts Python to raise an exception to then handle the exception. This allows you to test your exception handling.

43
Q

True or False: If raise is used in a function, it must be handled in an except branch only.

A

True

44
Q

What does ASCII stand for? Facts (3)

A

American Standard Code for Information Interchange

  • provides space for 256 different characters
  • space for whitespaces
  • Lower case are larger ints than Upper case
45
Q

What is a code point?

A

Its a number which makes a character. For example A = 65

46
Q

What does UTF stand for in UTF-8 and what it does.

A
  • Derived from Unicode Transformation Format

- Uses as many bits for each of the code points as it really needs to represent them

47
Q

String facts (6). How do they relate to whitespaces? Multilinestrings?

A
  • Immutable sequences
  • not able to modify the string using del, append, insert
  • can use del to delete the whole string
  • can create a new copy of a string to modify
  • can index, iterate, slice
  • can be concatenated and replicated
  • whitespaces add to the length (space between words, new line \n)
  • multiline strings can be delimited by triple quotes and triple apostrophes
48
Q

What does the ord() function do?

A

Identifies a character’s ASCII/Unicode code point value

49
Q

What does the chr() function do?

A

Takes a code point and returns its character

50
Q

What is the output of:
alpha = “peplum”

print(alpha[1:3])
print(alpha[3:])
print(alpha[:3])
print(alpha[3:-2])
print(alpha[-3:4])
print(alpha[::2])
print(alpha[1::2])
A
ep
lum
pep
l
l
ppu
elm
51
Q

What is the output of:
alphabet = “abcdefghijklmnopqrstuvwxyz”

print("f" not in alphabet)
print("F" not in alphabet)
print("1" not in alphabet)
print("ghi" not in alphabet)
print("Xyz" not in alphabet)
A
False
True
True
False
True
52
Q

What do the min() and max() functions do? What if the argument is empty?

A

Finds the minimum and maximum element of the sequence. The argument cannot be empty or will return an exception.

53
Q

What does the index() method do? What if the element is not in the sequence?

A

Searches the sequence from the beginning in order to find the first element of the value specified in its argument. If the element searched for is not in the sequence it return an exception.

54
Q

What is the output of:
print(“aAbByYzZaA”.index(“b”))
print(“aAbByYzZaA”.index(“Z”))
print(“aAbByYzZaA”.index(“A”))

A

2
7
1

55
Q

What does the list() function do?

A

It takes a string and creates a list containing all the strings characters.

56
Q

What does the count() method do? What if the element isnt present?

A

It counts all occurrences of the element inside the sequence. Absence of the element doesn’t cause a exception.

57
Q

What does the capitalize method do?

A

Creates a new string filled with characters taken from the source string.
If the first character inside the string is a letter, it will be converted to upper case. All remaining letters from the string will be converted to lower case.

58
Q

What is the output of:

print(‘Captain Jack Sparrow”.capitalize())

A

Captain jack sparrow

59
Q

Facts about applying methods to strings (3)

A
  • the original string is not changed in any way
  • the modified string is returned
  • unless a variable is assigned to the modified string, it is gone and not saved
60
Q

What does the center() method do?

A

It centers a string by adding spaces before and after the string.

61
Q

What is the syntax of the center() method?

A

center(output length, delimiter)

62
Q

What is the output of:

print(‘apple’.center(6,’*’))

A

apple*

63
Q

What does the endswith() method do?

A

Checks if the given string ends with the specified argument and returns True or False

64
Q

What does the find() method do?

A

It looks for a substring and returns the index of first occurrence of this substring. It doesnt generate an exception if the argument doesnt exist.

65
Q
What is the output of:
t = 'theta'
print(t.find('eta'))
print(t.find('et'))
print(t.find('the'))
print(t.find('ha'))
A

2
2
0
-1

66
Q

What is the syntax of the find() method?

A

string.find(characters_to_find, start_index, stop_index)

67
Q

What does the isalnum() method do?

A

Checks if the string contains only digits or alphabetical characters (letters) and returns True or False.

68
Q

What does the isalpha() method do?

A

Checks if the string contains only letters. Returns True or False. Whitespaces are not letters.

69
Q

What does the isdigit() method do?

A

Checks if the string contains only digits. Returns True or False.

70
Q

What does the islower() method do?

A

Checks for lower case only. Returns True or False.

71
Q

What does the isspace() method do?

A

Checks for whitespaces only. Returns True or False.

72
Q

What does the isupper() method do?

A

Checks for upper case only. Returns True or False.

73
Q

What does the join() method do?

A

Performs a join. The input is a list and outputs a string.

74
Q

What is the output of:
a = [‘Curly’, ‘Larry’, ‘Moe’]
print(“,”.join(a))

A

Curly,Larry,Moe

75
Q

What does the lower() method do?

A

Makes a copy of a source string, replaces all upper case letters with their lower case counterparts.

76
Q

What does the lstrip() method do?

A

Returns a newly created string formed from the original one by removing all leading specified characters (letter, number, whitespaces).

77
Q

What is the output of:
name = Mr. Magoo
print(name.lstrip(‘Mr.”)

A

Magoo (with space in front)

78
Q

What does the replace() method do?

A

Returns a copy of the original string in which all occurrences of the first argument have been replaced by the second argument.

79
Q

What is the syntax of the replace() method?

A

replace(first string, second string, number of replacements)

80
Q

What does the rfind() method do?

A

Provides the index of where a string is. It starts the search from the right.

81
Q

What is the syntax of the rfind() method?

A

rfind(string to find, starting search index, ending search index)

82
Q

What does the rstrip() method do?

A

Returns a newly created string formed from the original one by removing the indicated elements (string, whitespaces, etc)

83
Q

What does the split() method do?

A

Splits the string and builds a list of all detected substrings. It assumes the substrings are delimited by whitespaces.

84
Q

What is the output of:

print(“phi chi\npsi”.split())

A

[‘phi’, ‘chi’, ‘psi’]

85
Q

What does the startswith() method do?

A

It checks if a given string starts with the specified substring.

86
Q

What does the strip method do?

A

Makes a new string lacking all the leading and trailing designated characters (whitespaces, letters, numbers).

87
Q

What is the output of:

print(“Hello Harry!”.strip(‘H’))

A

ello Harry!

88
Q

What does the swapcase() method do?

A

It swaps the case of all letters within the source string.

89
Q

What does the title() method do?

A

Changes every word’s first letter to upper case during all others to lower case

90
Q

What does the upper() method do?

A

Replaces all lower case letters to their upper case counterparts

91
Q

Facts about comparing strings(4):

A
  • It compares the code point values
  • Compares the first different character in both strings
  • if strings are identical at the beginning, the longer one is considered greater
  • lower case letters are greater than their upper case counterparts
92
Q
What is the output of:
'10' == '010'
'10' > '010'
'10' > '8'
'20' < '8'
'20' < '80'
A
False
True
False
True
True
93
Q

What is the difference between sorted() and sort()?

A

sorted() is a function that returns a new sorted list

sort() affects the list itself, no new list is created

94
Q

What is the output of:

print(float(“1, 2”))

A

ValueError