Give an example of a tuple:
myTuple = (1,2,3,'a','b',[4,5,6])
myTuple
What is the difference between a tuple and a list?
A tuple is immutable while a list is mutable
Always start with writing pseudocode!
What is the different syntax between a function and a method?
functionName()
<object>.methodName()
Calculate the average of the list [1,2,3.5,5,6.2] to one decimal
myList = [1,2,3,5,6]
round(sum(myList)/len(myList),1)
Take the list ['i','know','python'] as input and output the string 'I KNOW PYTHON'
' '.join(['i','know','python']).upper()
What are the characteristics of a set?
A set contains an unordered collection of unique and immutable objects
Create a set containing the integers 1,2,3, and 4, add 3,4,5, and 6 to the set. How long is the set?
mySet = {1,2,3,4}
mySet.add(3)
mySet.add(4)
mySet.add(5)
mySet.add(6)
len(mySet)
... Hm, starting to be difficult now...
dictionary
¶Syntax:
a = {}
(create empty dictionary)
d = {'key1':1, 'key2':2, 'key3':3}
myDict = {'drama': 4,
'thriller': 2,
'romance': 5}
myDict
myDict = {'drama': 4,
'thriller': 2,
'romance': 5}
len(myDict)
myDict['drama']
myDict['horror'] = 2
#myDict
#del myDict['horror']
#myDict
'drama' in myDict
myDict.keys()
myDict.items()
myDict.values()
myDict = {'drama': 182,
'war': 30,
'adventure': 55,
'comedy': 46,
'family': 24,
'animation': 17,
'biography': 25}
Hint! If the genre is not already in the dictionary, you have to add it first
fh = open('../downloads/250.imdb', 'r', encoding = 'utf-8')
genreDict = {} # create empty dictionary
for line in fh:
if not line.startswith('#'):
cols = line.strip().split('|')
genre = cols[5].strip()
glist = genre.split(',')
for entry in glist:
if not entry.lower() in genreDict: # check if genre is not in dictionary, add 1
genreDict[entry.lower()] = 1
else:
genreDict[entry.lower()] += 1 # if genre is in dictionary, increase count with 1
fh.close()
print(genreDict)
Tip!
Here you have to loop twice
fh = open('../downloads/250.imdb', 'r', encoding = 'utf-8')
genreDict = {}
for line in fh:
if not line.startswith('#'):
cols = line.strip().split('|')
genre = cols[5].strip()
glist = genre.split(',')
runtime = cols[3] # length of movie in seconds
for entry in glist:
if not entry.lower() in genreDict:
genreDict[entry.lower()] = [int(runtime)] # add a list with the runtime
else:
genreDict[entry.lower()].append(int(runtime)) # append runtime to existing list
fh.close()
for genre in genreDict: # loop over the genres in the dictionaries
average = sum(genreDict[genre])/len(genreDict[genre]) # calculate average length per genre
hours = int(average/3600) # format seconds to hours
minutes = (average - (3600*hours))/60 # format seconds to minutes
print('The average length for movies in genre '+genre\
+' is '+str(hours)+'h'+str(round(minutes))+'min')
A lot of ugly formatting for calculating hours and minutes from seconds...
def FormatSec(genre): # input a list of seconds
average = sum(genreDict[genre])/len(genreDict[genre])
hours = int(average/3600)
minutes = (average - (3600*hours))/60
return str(hours)+'h'+str(round(minutes))+'min'
fh = open('../downloads/250.imdb', 'r', encoding = 'utf-8')
genreDict = {}
for line in fh:
if not line.startswith('#'):
cols = line.strip().split('|')
genre = cols[5].strip()
glist = genre.split(',')
runtime = cols[3] # length of movie in seconds
for entry in glist:
if not entry.lower() in genreDict:
genreDict[entry.lower()] = [int(runtime)] # add a list with the runtime
else:
genreDict[entry.lower()].append(int(runtime)) # append runtime to existing list
fh.close()
for genre in genreDict:
print('The average length for movies in genre '+genre\
+' is '+FormatSec(genre))
def addFive(number):
final = number + 5
return final
addFive(4)
from datetime import datetime
def whatTimeIsIt():
time = 'The time is: ' + str(datetime.now().time())
return time
whatTimeIsIt()
def addFive(number):
final = number + 5
return final
addFive(4)
#final
final = addFive(4)
final
def someFunction():
# s = 'a string'
print(s)
s = 'another string'
someFunction()
print(s)
Example:
formatSec()
in the fileimport
the functionfrom myFunctions import formatSec
seconds = 32154
formatSec(seconds)
from myFunctions import formatSec, toSec
seconds = 21154
print(formatSec(seconds))
days = 0
hours = 21
minutes = 56
seconds = 45
print(toSec(days, hours, minutes, seconds))
→ Notebook Day_3_Exercise_1 (~30 minutes)
sys.argv
¶The `sys.argv` function
Python script called print_argv.py
:
Running the script with command line arguments as input:
Instead of:
do:
Run with:
Re-structure and write the output to a new file as below
Note:
sys.argv
for input/outputRun with: