Part 4 Modules Flashcards
Import a module to display current time
import datetime
x = datetime.datetime.now()
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.
x = datetime.datetime(2018, 6, 1)
x.strftime((‘%B’))
%B - this is the directive
strftime <- string format time
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
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)
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
import math
print(math.sqrt(64))
math.ceil(1.4)
math.floor(1.4)
math.pi
What does JSON stand for?
Import JSON and:
Create a variable that looks like JSON
Parse it
Print the results
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
Convert the below python into json
x = { ‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
import json
y = json.dumps(x)
print(y)
What are the json equivalents to the below
dict
list
tuple
str
int
float
True
False
None
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
The info is a bit hard to read after converting info into json, indent the code to make it more readable
json.dumps(x, indent=4)
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?
json.dumps(x, indent=4, separators=(‘. ‘, ‘=’)
json.dumps(x, indent=4, sort_keys=True
In JSON, what are dictionaries called?
Objects
{‘key’:’value’}
Import regular expessions
Search the below string to see if it starts with “The” and ends with ‘Spain’
import re
txt = ‘The rain in Spain’
x = re.search(‘^The.*Spain$’, txt)