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
Via the json module, convert a dictionary named ‘x’ into json format, giving an indentation for 4 spaces for readability.
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’
x = The rain in Spain
import re
txt = ‘The rain in Spain’
x = re.search(‘^The.*Spain$’, txt)
^ <- starts with
$ <- ends with
.* <- match any characters (zero or more)
What is PIP
PIP is python’s package manager
you can find pip packages at:
https://pypi.org/
How do you install and uninstall a pip package
pip install package
pip uninstall package
List all pip packages on your system
pip list
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.
try:
print(x)
except NameError:
print(“Variable x not defined”)
except:
print(“Something else went wrong”)
Handle an error
Add a block of code that prints a message if there is no error and also if there is one.
try:
print(‘hello’)
except:
print(‘error’)
else:
print(‘no error’)
What is a good use case for ‘finally’?
If you’ve opened a file, you’ll want to close it regardless of a success. The ‘with’ statement will also do this.
Create an exception error, then create a TypeError
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’)
Why would you use raise?
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.
Gather user stdin and place it in a variable
username = input(‘Enter your username’)
For file handling, you use the ‘open()’ function where you insert a ‘filename’ and a ‘mode’.
What are all the modes you can use?
‘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
create a variable that opens ‘demofile.txt’ in text mode to read
Now actually use a function to read it.
f = open(‘demofile.txt’, ‘rt’)
print(f.read())
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.
f = open(‘demofile.txt’, ‘r’)
print(f.read(5))
print(f.readline(), f.readline())
f.close()
Open a file, append something to it, close it, then read it
f = open(‘demofile.txt’, ‘a’)
f.write(‘new line’)
f.close
f = open(‘demofile.txt’, ‘r’)
print(f.read())
How do you completely overwrite a file?
f.write()
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.)
import os
if os.path.exists(‘demofile.txt’):
os.remove(‘demofile.txt’)
else:
print(‘the file does not exist.’)
os.rmdir(‘myfolder’)