Part 4 Modules Flashcards

1
Q

Import a module to display current time

A

import datetime

x = datetime.datetime.now()

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

There is a method in the datetime module that outputs more human readable formats but requires DIRECTIVES. Use it, but first pass the year 2018, the month June and the day 1 to it.

A

x = datetime.datetime(2018, 6, 1)
x.strftime((‘%B’))

%B - this is the directive
strftime <- string format time

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

Show the absolute value of -17
show the lowest and highest values of the below list:
[5, 10, 48]

Calculate the value of 4 to the power of 3

A

print(abs(-7.25))

print(min(5, 10, 48))
print(max(5, 10, 48))
print(pow(4, 3)
This basically means 3 over for or (4 * 4 * 4)

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

Import a module to:
determine the square root of 64

round 1.4 to the upwards to the nearest integer and then downward to the

show the value of pi

A

import math
print(math.sqrt(64))

math.ceil(1.4)
math.floor(1.4)

math.pi

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

What does JSON stand for?
Import JSON and:
Create a variable that looks like JSON
Parse it
Print the results

A

Java Script Object Notation

import json

x = ‘{ ‘name’: ‘John’, ‘age’ : 30, ‘city’: ‘New York}’

y = json.loads(x)

print(y[‘age’])

parsing - divide something into parts to analyze individually
data parsing - Converting one data format to another

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

Convert the below python into json

x = { ‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}

A

import json
y = json.dumps(x)
print(y)

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

What are the json equivalents to the below
dict
list
tuple
str
int
float
True
False
None

A

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

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

Via the json module, convert a dictionary named ‘x’ into json format, giving an indentation for 4 spaces for readability.

A

json.dumps(x, indent=4)

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

JSON normally indents using a comma and a space to separate each object and a colon and a space to separate keys from values, how would you change this

Also, how would you sort the keys?

A

json.dumps(x, indent=4, separators=(‘. ‘, ‘=’)

json.dumps(x, indent=4, sort_keys=True

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

In JSON, what are dictionaries called?

A

Objects
{‘key’:’value’}

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

Import regular expessions
Search the below string to see if it starts with “The” and ends with ‘Spain’

x = The rain in Spain

A

import re

txt = ‘The rain in Spain’
x = re.search(‘^The.*Spain$’, txt)

^ <- starts with
$ <- ends with
.* <- match any characters (zero or more)

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

What is PIP

A

PIP is python’s package manager

you can find pip packages at:
https://pypi.org/

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

How do you install and uninstall a pip package

A

pip install package
pip uninstall package

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

List all pip packages on your system

A

pip list

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

Your code does not contain an x variable. This would normally stop the code in its tracks. How would you keep the code functioning despite this error.

If you know the answer, handle two errors.

A

try:
print(x)
except NameError:
print(“Variable x not defined”)
except:
print(“Something else went wrong”)

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

Handle an error
Add a block of code that prints a message if there is no error and also if there is one.

A

try:
print(‘hello’)
except:
print(‘error’)
else:
print(‘no error’)

17
Q

What is a good use case for ‘finally’?

A

If you’ve opened a file, you’ll want to close it regardless of a success. The ‘with’ statement will also do this.

18
Q

Create an exception error, then create a TypeError

A

raise Exception(‘Sorry, no numbers below zero.’)

raise TypeError(‘only integers are allowed’)

If you raise the ‘TypeError’ here your code will lump that in with other TypeErrors, allowing you to handle it later with except TypeError: in the future.

Example:

a = input(‘input the number 5’)
a = int(a)
if a != 5:
raise Exception(‘The number is not 5’)

19
Q

Why would you use raise?

A

It creates an exception where there wouldn’t normally be.

After this step you can move on to exception handling, so the code breaks out to where nothing will break or not function properly eventually.

f you raise the ‘TypeError’ here your code will lump that in with other TypeErrors, allowing you to handle it later with except TypeError: in the future.

20
Q

Gather user stdin and place it in a variable

A

username = input(‘Enter your username’)

21
Q

For file handling, you use the ‘open()’ function where you insert a ‘filename’ and a ‘mode’.

What are all the modes you can use?

A

‘r’ - read
‘a’ - append, creates file if it does not exist
‘w’ - write
‘x’ - create, returns error if file exists

additionals:
‘t’ - text mode
‘b’ - binary mode

22
Q

create a variable that opens ‘demofile.txt’ in text mode to read

Now actually use a function to read it.

A

f = open(‘demofile.txt’, ‘rt’)

print(f.read())

23
Q

You’ve opened a file to read which is stored in the variable ‘f’

Return only the first 5 characters.

return only one line from a file, then the next

Close the file after you are done with it.

A

f = open(‘demofile.txt’, ‘r’)
print(f.read(5))

print(f.readline(), f.readline())

f.close()

24
Q

Open a file, append something to it, close it, then read it

A

f = open(‘demofile.txt’, ‘a’)
f.write(‘new line’)
f.close

f = open(‘demofile.txt’, ‘r’)
print(f.read())

25
Q

How do you completely overwrite a file?

26
Q

Removing a file is a slightly different process.

Delete the file ‘demofile.txt’

It might be better to check if the file exists first as to not raise an error.

Now Delete an entire folder named ‘myfolder’ (Only removes empty folders.)

A

import os
if os.path.exists(‘demofile.txt’):
os.remove(‘demofile.txt’)
else:
print(‘the file does not exist.’)

os.rmdir(‘myfolder’)