3.6 and 3.7 Homework Hacks
3.6 Hacks
Hack 1:
str1 = "hello"
str2 = "bye" #define the strings using the assignment operator
if str1 == str2: #if the strings are the exact same
print("The strings are equal")
else: # if the strings are not the exact same (different)
print("The strings are different")
The strings are different
Hack 2:
str1 = "monday"
str2 = "sunday" #define the strings
if str1 == str2: #if the strings are the exact same
print("We are the same") #print statements to give output
elif len(str1) == len(str2): #if the lengths of the strings are the same
print("We are the same length!") #print statement to give output
else: # if none of the above conditions are met
print("We are not that similar :( ") #print statement to give output
We are the same length!
Hack 3:
for i in range(1, 11): #iterate through the numbers 1-10
var = input("Enter the number " + str(i) + " : ") #ask the user to input a number
if var == str(i):
continue #go to next iteration
else:
print("You entered the wrong number") #print statement to give output
break
print("You entered all the numbers correctly!") #print statement to give output
You entered the wrong number
3.7
Hack 1:
def leapyear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return year, "is a leap year."
else:
return year, "is not a leap year."
else:
return year, "is a leap year."
else:
return year, "is not a leap year."
print(leapyear(2000)) #call the function with the year 2000
print(leapyear(2001)) #call the function with the year 2004
(2000, 'is a leap year.')
(2001, 'is not a leap year.')
Extra Credit: Morse Code Encoder
char_to_dots = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', ' ': ' ', '0': '-----',
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.',
'&': '.-...', "'": '.----.', '@': '.--.-.', ')': '-.--.-', '(': '-.--.',
':': '---...', ',': '--..--', '=': '-...-', '!': '-.-.--', '.': '.-.-.-',
'-': '-....-', '+': '.-.-.', '"': '.-..-.', '?': '..--..', '/': '-..-.'
}
def encode_morse(message):
if len(message) == 0:
return "Message is too short"
result=""
for i in message.upper():
result += char_to_dots[i]+" "
return result[0:-1]
encode_morse("Howdy") #call the function with the string "Howdy"