Skip to content

Commit a710c9a

Browse files
author
GeekTrainer
committed
Initial Upload
1 parent 5089ccb commit a710c9a

32 files changed

+497
-0
lines changed

Office Docs/1 Getting Started.pptx

771 KB
Binary file not shown.

Office Docs/10 Remembering lists.pptx

200 KB
Binary file not shown.
Binary file not shown.
129 KB
Binary file not shown.

Office Docs/13 Functions.pptx

170 KB
Binary file not shown.

Office Docs/14 Handling errors.pptx

206 KB
Binary file not shown.
Binary file not shown.

Office Docs/2 Displaying Text.pptx

138 KB
Binary file not shown.

Office Docs/3 String Variables.pptx

203 KB
Binary file not shown.

Office Docs/4 Storing numbers.pptx

145 KB
Binary file not shown.
Binary file not shown.
160 KB
Binary file not shown.
127 KB
Binary file not shown.

Office Docs/8 Repeating events.pptx

319 KB
Binary file not shown.
108 KB
Binary file not shown.
Binary file not shown.
712 KB
Binary file not shown.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
#Declare variables to hold the file name and access mode
3+
fileName = "GuestList.txt"
4+
accessMode = "w"
5+
6+
#Open the file for writing
7+
myFile = open(fileName, accessMode)
8+
9+
#Write the guest names and ages to the file
10+
for index in range(5) :
11+
name = input("Enter guest name: " )
12+
age = input("Enter guest age: " )
13+
myFile.write(name + "," + age + "\n")
14+
15+
#Close the file
16+
myFile.close()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
#Declare variables to hold the file name and access mode
3+
fileName = "GuestList.txt"
4+
accessMode = "w"
5+
6+
#Open the file for writing
7+
myFile = open(fileName, accessMode)
8+
9+
#Write the guest names and ages to the file
10+
11+
#I can write an entire record in one write statement
12+
myFile.write("Doyle McCarty,27\n")
13+
myFile.write("Jodi Mills,25\n")
14+
myFile.write("Nicholas Rose,32\n")
15+
#I could write the name and age in separate write statements
16+
myFile.write("Kian Goddard")
17+
myFile.write(",36\n")
18+
myFile.write("Zuha Hanania")
19+
myFile.write(",26\n")
20+
21+
#Close the file
22+
myFile.close()
23+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#import the csv library which contains functions to help you work with CSV files
2+
import csv
3+
4+
#Declare variables to hold the file name and access mode
5+
fileName = "GuestList.txt"
6+
accessMode = "r"
7+
8+
#open the file
9+
with open(fileName, accessMode) as myCSVFile:
10+
#Read the file contents
11+
#specify that we are using a comma to separate the values in the file
12+
dataFromFile = csv.reader(myCSVFile, delimiter =",")
13+
14+
#Create a for loop that will run once for each row in the list
15+
for row in dataFromFile :
16+
#print an entire row at a time in a list format
17+
print(row)
18+
19+
#print the entire row separating the values in the list with a comma
20+
print (', '.join(row))
21+
22+
#Print each indivudal value in each row
23+
for value in row :
24+
print(value + "\n")
25+
26+
#Close the file
27+
myCSVFile.close()

Solutions/Module13Function.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def writeText(data, filename):
2+
file = open(filename, mode = 'w')
3+
file.write(data)
4+
return
5+
6+
writeText('Hello, world.', 'c:\\users\\chharri\\documents\\hello.txt')
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#import libraries we will use
2+
import sys
3+
4+
#Declare variables
5+
filename = ""
6+
fileContents = ""
7+
8+
#Ask the user for the filename
9+
filename = input("PLease specify the name of the file to read ")
10+
11+
#open the file, since you may get an error when you attempt to open the file
12+
#For example the file specified may not exist
13+
#put a try except statement around the command
14+
try :
15+
myFile = open(filename, "r")
16+
17+
#I am using a boolean variable to determine if the file was found
18+
#That waythe code will only attempt to read the file if it was found succesfully
19+
fileFound = True
20+
21+
#Handle the FileNotFoundError
22+
except FileNotFoundError :
23+
print("Could not locate file " + filename)
24+
fileFound = False
25+
26+
#Other errors could occur, perhaps the file is coorupte, or I do not have permissions on the file
27+
except :
28+
error = sys.exc_info()
29+
print(error)
30+
fileFound = False
31+
32+
#if the file was opened successfully read the contents and display the contents to the user
33+
if fileFound :
34+
#Get the file contents into a string
35+
fileContents = myFile.read()
36+
print(fileContents)
37+
#print the results
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
#Import the libraries we need for the program
2+
import fileinput
3+
4+
#This is the main function, by declaring a main function and then calling it after all the function definitions
5+
#We can list the functions in our code in the order we want, if we didn't have a mainfunction() we would have needed to list all the functions
6+
#our code called first, which might be a bit hard to read.
7+
def mainFunction():
8+
9+
#Because this is a fairly long piece of code to write, we have broken up the work into a number of functions
10+
#To try and make it a little easier to read
11+
12+
#Step 1 - Ask the user to enter their text message
13+
#By using a print and then an input statement you give a fresh new line to type in their text message
14+
print("Please enter the message (no punctuation please):")
15+
txtMessage = input(">")
16+
17+
#Step 2 use the split function to get a list that contains all the words in the text message
18+
messageWords = txtMessage.split()
19+
20+
#The translationFileName should contain the name of the file that contains the list of Text message abbreviations
21+
#and their corresponding translations
22+
translationFileName = "Translations.txt"
23+
24+
#call the function we created below to make sure our translation file exists
25+
# If the file is found it will return a 0
26+
# If the file is not found it will return a 1
27+
fileFound = fileCheck(translationFileName)
28+
29+
if fileFound == 0 :
30+
31+
#Step 3 a) b) c) Call the function we created below to get back two lists, a list of the abbreviations and a list of the translations
32+
allAbbreviations, allTranslations = dictionaryList(translationFileName)
33+
34+
#Step 3 d) e) Call the function we created below to get back a string containing the translated text message
35+
translatedMessage = compare(messageWords, allAbbreviations, allTranslations) # the final list of words for the message
36+
37+
#Step 4) Print the translated message to the user
38+
print(translatedMessage)
39+
else :
40+
print("Could not translate message, file containing translation terms could not be located.")
41+
42+
#This function will check if a specified file exists.
43+
#If the file exists it will not display any error messages
44+
#If the file does not exist it will display an error message and restart the program.
45+
#Accepts one parameter
46+
# filename the name of the file to check exists
47+
#Returns one value
48+
# 0 indicates the file was succesfully located
49+
# 1 indicates the file could not be located
50+
def fileCheck(fileName):
51+
try:
52+
fileObj = open(fileName) #will try to open the file specified
53+
return 0
54+
except IOError: #will handle the exception
55+
print("Could not locate the file " + fileName)
56+
return 1
57+
58+
#This function accepts the name of a file that contains abbreviations and translations
59+
#It will return two lists - one containing all the abbreviations, the other containing the translations
60+
#Accepts one parameter
61+
# fileName the name of the file containing the abbreviations and translations
62+
#Returns two values
63+
# A list of abbreviations from the file
64+
# A list of translations from the file
65+
# This function assumes the file will have the format
66+
# abbreviation - definition
67+
def dictionaryList(fileName):
68+
69+
#Declare the lists to be populated and returned
70+
allAbbreviations = []
71+
allTranslations = []
72+
73+
#Step 3 a) open the file
74+
fileObj = open(fileName)
75+
76+
for line in iter(fileObj): #This for loop will read the file line by line
77+
#Take each line in the file and split it into a list of words
78+
#LOL - Laughing out Loud will return a list containing ["LOL","-","Laughing","Out","Loud"]
79+
wordsInTheLine = line.split()
80+
81+
#Step 3 b)The first word in the list is the abbreviation, add that to our list of allAbbreviations
82+
allAbbreviations.append(wordsInTheLine[0])
83+
84+
#Step 3 c) Now this is the tricky part because we need to take all the remaining words in the list and together they make up our translation
85+
# e.g. if the line in the file returned ["LOL","-","Laughing","Out","Loud"]
86+
# we need to combine the words "Laughing","Out","Loud" to get our translation
87+
#It would be easier if we just had one word translations then we could just add words[1] to our translations list
88+
#But solving problems isn't always easy!
89+
90+
translation = ""
91+
92+
#Find out how many words total are in the line read from the file
93+
totalNumberOfWords = len(wordsInTheLine)
94+
95+
#Start with the word at position 2 in the list, this allows us to skip the abbreviation and the hyphen
96+
for x in range(2,totalNumberOfWords):
97+
#now take each word starting with the third word (index 2) until the last word and concatentate them together
98+
#with a space between each word
99+
translation = translation + wordsInTheLine[x] + " "
100+
101+
#add the translation to our list of translations
102+
allTranslations.append(translation)
103+
104+
#return the two lists: the list of abbreviations and the list of translations
105+
return (allAbbreviations, allTranslations)
106+
107+
108+
#this function will go through each word in the message
109+
#And search for it in the list of abbreviations
110+
#If found in the list of abbreviations it will fetch the corresponding translation (same index number) from the list of translations
111+
#then it will concatenate each of the translations to create the translated text message
112+
#This function accepts three parameters
113+
# messageWords - this is the list of words in the text message to be translated
114+
# allAbbreviations - this is the list containing all possible text message abbreviations we can translate
115+
# allTranslations - this is the list containing all the translations for each text message abbreviation
116+
#This function returns one value
117+
# finalMessage - a string that is the translated text message
118+
def compare(messageWords, allAbbreviations, allTranslations):
119+
120+
finalMessage = ""
121+
122+
#Step 3 d) Create a loop that will execute once for each word in our list of words in the text message
123+
for wordPosition in range(0, len(messageWords)):
124+
#Fetch the next word from our list of words in the text message
125+
currentWord = messageWords[wordPosition]
126+
127+
try :
128+
#3 d) search the abbreviation list for the current word
129+
matchPosition = allAbbreviations.index(currentWord.upper())
130+
131+
#3 e) If you find a match get the translation from the list of definitions
132+
finalMessage = finalMessage + " " + allTranslations[matchPosition]
133+
except :
134+
#If no match is found by the index() search an exception is raised, which means no match was found
135+
#If no match was found just display the original word in the final message
136+
finalMessage = finalMessage + " " + currentWord
137+
138+
return (finalMessage)
139+
140+
mainFunction()
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
print('There once was a movie star icon')
2+
print('who preferred to sleep with the light on')
3+
print('They learned how to code')
4+
print('a device that sure glowed')
5+
print('and lit up the night using Python!')
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#initialize the variables
2+
girldescription = " "
3+
boydescription = " "
4+
walkdescription = " "
5+
girlname = " "
6+
boyname = " "
7+
animal = " "
8+
gift = " "
9+
answer = " "
10+
11+
#Ask the user to specify values for the variables
12+
girlname = input("Enter a girl's name: ")
13+
boyname = input("Enter a boy's name: " )
14+
animal = input("Name a type of animal: " )
15+
gift = input("Name something you find in the bathroom: ")
16+
girldescription = input("Enter a description of a flower: ")
17+
boydescription = input("Enter a description of a car: ")
18+
walkdescription = input("Enter a description of how you might dance: " )
19+
answer = input("What would you say to someone who gave you a cow: ")
20+
21+
#Display the story
22+
#Don't forget to format the strings when they are displayed
23+
print ("Once upon a time,")
24+
print("there was a girl named " + girlname.capitalize() + ".")
25+
print("One day, " + girlname.capitalize() + " was walking " + walkdescription.lower() + " down the street.")
26+
print("Then she met a " + boydescription.lower() + " boy named " + boyname.capitalize() + ".")
27+
print("He said, 'You are really " + girldescription.lower() + "!'")
28+
print("She said '" + answer.capitalize() + ", " + boyname.capitalize() + ".'")
29+
print("Then they both rode away on a " + animal.lower() + " and lived happily ever after.")
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
#Declare and initialize the variables
3+
monthlyPayment = 0
4+
loanAmount = 0
5+
interestRate = 0
6+
numberOfPayments = 0
7+
loanDurationInYears = 0
8+
9+
#Ask the user for the values needed to calculate the monthly payments
10+
strLoanAmount = input("How much money will you borrow? ")
11+
strInterestRate = input("What is the interest rate on the loan? ")
12+
strLoanDurationInYears = input("How many years will it take you to pay off the loan? " )
13+
14+
#Convert the strings into floating numbers so we can use them in teh formula
15+
loanDurationInYears = float(strLoanDurationInYears)
16+
loanAmount = float(strLoanAmount)
17+
interestRate = float(strInterestRate)
18+
19+
#Since payments are once per month, number of payments is number of years for the loan * 12
20+
numberOfPayments = loanDurationInYears*12
21+
22+
#Calculate the monthly payment based on the formula
23+
monthlyPayment = loanAmount * interestRate * (1+ interestRate) * numberOfPayments \
24+
/ ((1 + interestRate) * numberOfPayments -1)
25+
26+
#provide the result to the user
27+
print("Your monthly payment will be " + str(monthlyPayment))
28+
29+
#Extra credit
30+
print("Your monthly payment will be $%.2f" % monthlyPayment)
31+
32+
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#import the datetime class
2+
import datetime
3+
4+
#declare and initialize variables
5+
strDeadline = ""
6+
totalNbrDays = 0
7+
nbrWeeks = 0
8+
nbrDays = 0
9+
10+
#Get Today's date
11+
currentDate = datetime.date.today()
12+
13+
#Ask the user for the date of their deadline
14+
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")
15+
16+
deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()
17+
18+
#Calculate number of days between the two dates
19+
totalNbrDays = deadline - currentDate
20+
21+
#For extra credit calculate results in weeks & days
22+
23+
nbrWeeks = totalNbrDays.days / 7
24+
25+
#The modulo will return the remainder of the division
26+
#which will tell us how many days are left
27+
nbrDays = totalNbrDays.days%7
28+
29+
#display the result to the user
30+
31+
print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")
32+
33+
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#You may have written the solution very differently from the solution provided below.
2+
#As you get further into coding, you will find multiple ways to solve the same problem with code
3+
#If you coded it differently, than just compare your solution to this solution
4+
#You can decide which coding style you prefer
5+
6+
#Declare variables
7+
orderTotal = 0
8+
shippingCost = 0
9+
totalWithShipping = 0
10+
11+
#Ask user for their order total and convert the answer to a number
12+
orderTotal = float(input("What was the total for your order? " ))
13+
14+
#Calculate the shipping cost based on the order total
15+
if orderTotal >= 50 :
16+
shippingCost = 0
17+
else :
18+
shippingCost = 10
19+
20+
#Calculate order total including shipping
21+
totalWithShipping = orderTotal + shippingCost
22+
23+
#Tell the user their final total
24+
print("Your final total, including shipping, will be: $%.2f " % totalWithShipping)
25+
26+
27+
28+
29+

0 commit comments

Comments
 (0)