Day 7: “Save our Souls” – we build a Morse Code Generator

Not only a Morse Code Generator but we also allow the user to store his morse code into a txt-file – if he asks nicely.

 

The terminal output looks like this

 

 

The saved file looks like this:

 

 

This program takes the topic of yesterday “Dictionaries” to a new level, since the Morse Code is saved in a dictionary.

 

This is the program. We have two functions: One generates the code and the other handles the writing and saving to a file.

 

from morse_dictionary import morse # this is where the morse dictionary is stored

# we give the user the chance to save their morse code to a text file
def save_txt(txt_morse):
    if (input("Do you want to save your text to a file? (y/n)")=="y"):
        filename = input("Give the file a name: ")
        
        if (filename==""): # if user enters no file name we called it "morse.txt" by default
            filename = "morse"
            
        file = open(filename+".txt","w") #opens or creates a txt-file
        file.write(txt_morse) # write the morse code to the file
        file.close() # close the file again

# the function takes in the plain text and converts it to morse code with the morse dictionary        
def morse_gen(text):
    txt_upper = text.upper() # since our dictionary only undertands capital letters
    txt_morse = ""
    for x in (txt_upper):
        # we get the morse code for every letter and add it to txt_morse
        # we also include two spaces after every letter to make the formatting clearer
        txt_morse += morse.get(x, x) + "  " 

    print(txt_morse)   # print the morse code
     
    save_txt(txt_morse) # call the save to file function
    
    if (input("Do you want to enter another message? (y/n)")=="y"):
        morse_gen(input("Enter the sentence you want to translate (A-Z,a-z,0-9): "))
    else:
        raise SystemExit #proper program exit
    
    
    
print("*****************************************")
print("**** Morse Code Generator 1912 Model ****")
print("*****************************************")
morse_gen(input("Enter the sentence you want to translate (A-Z,a-z,0-9): "))

This is the Morse Dictionary:

 

morse = {
"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" : "----.", 
"." : ".-.-.-", 
"," : "--..--"
}

Day 6: Olympic Medals – have fun(?) with dictionaries

This program sorts the number of Olympic Medals won by each nation in descending order.

Countries and numbers of Medals are stored in a dictionary

This is what the output looks like (the screenshot shows only half of the list, but you get the picture):

 

 

Considered that this program basically only needed four lines of code it took me a long while to figure it out.

 

I wanted to sort the dictionary by its value: The number of medails. In the beginning the numbers in the

dictionary (that I got from Wikipedia) were stored as strings like this:

 

medails = {
     "Country A" = "1",
     "Country B" = "8",
     "Country C" = "11
}

 

It turned out that it would sort “1, “11” and than “8” – well because it is a string and not a number.

So I tried to store one medail number as an Integer, just to try it out but that throwed me an error. It turned out I had to turn all strings

into Integers first and then it would sort properly – even though the Python-Docs say you can mix any sort of values in a dictionary.

 

The program itself looks like this:

from medails_dictionary import medails # thats where I stored the dictionary

# sort the dictionary by its number values in decending order
c = sorted(medails.items(),key=lambda x: x[1], reverse=True)

# go through every key and print the key-value-pair
for x in c:
    print (x)

 

The dictionary looks like this:

 

medails = {
"Afghanistan" : 2,
"Algeria" : 17,
"Argentina" : 74,
"Armenia" : 14,
"Australasia" : 12,
"Australia" : 509,
"Austria" : 305,
"Azerbaijan": 43,
"Bahamas" : 14,
"Bahrain" : 3,
"Barbados" : 1,
"Belarus" : 93,
"Belgium" : 153,
"Bermuda" : 1,
"Bohemia" : 4,
"Botswana" : 1,
"Brazil" : 128,
"British West Indies" : 2,
"Bulgaria" : 224,
"Burundi" : 2,
"Cameroon" : 6,
"Canada" : 472,
"Chile" : 13,
"China" : 599,
"Chinese Taipei" : 24,
"Colombia" : 28,
"Costa Rica" : 4,
"Croatia" : 44,
"Cuba" : 225,
"Cyprus" : 1,
"Czech Republic" : 80,
"Czechoslovakia" : 168,
"Denmark" : 195,
"Djibouti" : 1,
"Dominican Republic" : 7,
"East Germany" : 519,
"Ecuador" : 2,
"Egypt" : 32,
"Eritrea" : 1,
"Estonia" : 41,
"Ethiopia" : 53,
"Fiji" : 1,
"Finland" : 464,
"France" : 825,
"Gabon" : 1,
"Georgia" : 33,
"Germany" : 824,
"Ghana" : 4,
"Great Britain" : 875,
"Greece" : 116,
"Grenada" : 2,
"Guatemala" : 1,
"Guyana" : 1,
"Haiti" : 2,
"Hong Kong" : 3,
"Hungary" : 497,
"Iceland" : 4,
"Independent Olympic Athletes" : 2,
"Independent Olympic Participants" : 3,
"India" : 28,
"Indonesia" : 32,
"Iran" : 69,
"Iraq" : 1,
"Ireland" : 31,
"Israel" : 9,
"Italy" : 691,
"Ivory Coast" : 3,
"Jamaica" : 77,
"Japan" : 484,
"Jordan" : 1,
"Kazakhstan" : 69,
"Kenya" : 102,
"Kosovo" : 1,
"Kuwait" : 2,
"Kyrgyzstan" : 4,
"Latvia" : 26,
"Lebanon" : 4,
"Liechtenstein" : 9,
"Lithuania" : 25,
"Luxembourg" : 4,
"Macedonia" : 1,
"Malaysia" : 11,
"Mauritius" : 1,
"Mexico" : 69,
"Mixed Team" : 17,
"Moldova" : 5,
"Mongolia" : 26,
"Montenegro" : 1,
"Marocco" : 23,
"Mozambique" : 2,
"Namibia" : 4,
"Netherlands Antilles" : 1,
"Netherlands" : 395,
"New Zealand" : 118,
"Nigeria" : 25,
"Niger" : 2,
"North Korea" : 56,
"Norway" : 481,
"Pakistan" : 10,
"Panama" : 3,
"Paraguay" : 1,
"Peru" : 4,
"Philippines" : 10,
"Poland" : 304,
"Portugal" : 24,
"Puerto Rico" : 9,
"Qatar" : 5,
"Romania" : 307,
"Russian Empire" : 8,
"Russia" : 537,
"Samoa" : 1,
"Saudi Arabia" : 3,
"Senegal" : 1,
"Serbia and Montenegro" : 9,
"Serbia" : 15,
"Singapore" : 5,
"Slovakia" : 33,
"Slovenia" : 38,
"South Africa" : 86,
"South Korea" : 320,
"Soviet Union" : 1204,
"Spain" : 152,
"Sri Lanka" : 2,
"Sudan" : 1,
"Suriname" : 2,
"Sweden" : 638,
"Switzerland" : 330,
"Syria" : 3,
"Tajikistan" : 4,
"Tanzania" : 2,
"Thailand" : 33,
"Togo" : 1,
"Tonga" : 1,
"Trinidad and Tobago" : 19,
"Tunisia" : 13,
"Turkey" : 91,
"Uganda" : 7,
"Ukraine" : 128,
"Unified Team" : 135,
"United Arab Emirates" : 2,
"United States" : 2804,
"United Team of Germany" : 137,
"Uruguay" : 10,
"Uzbekistan" : 32,
"Venezuela" : 15,
"Vietnam" : 4,
"Virgin Islands" : 1,
"West Germany" : 243,
"Yugoslavia" : 87,
"Zambia" : 2,
"Zimbabwe" : 8
}

Day 5: Calcutron 3000 – a simple shell calculator with validation

Our calculator takes in two numbers (float) and a type (sum, substract, multiplication and division). The Output looks like this

 

The program is pretty self explaining. We put all the logic into the calc-function. When the User has finished his calculation we ask him if he wants to make another calculation or exit the program.

def calc():
    print("******************************")
    print("******* Calcutron 3000 *******")
    print("******************************")
    val1 = (input("Enter first value: "))
    val2 = (input("Enter second value: "))
    type = (input("Choose your operation: 1 = sum, 2 = substract, 3 = multiplication, 4 = division: "))
    val1 = float(val1)  #change input string to float
    val2 = float(val2)  #change input string to float
    type = int(type) #change input string to int
    
    #check if both val1/val2 are valid float numbers and if type is in the range between 1 and 4
    if (isinstance(val1, float)) and (isinstance(val2, float)) and (1 <= type <= 4):
        if (type==1):
            print(val1 + val2)
        elif (type==2):
            print(val1 - val2)
        elif (type==3):
            print(val1 * val2)
        elif (type==4):
            print(val1 / val2)
        else:
            print("Error")
    else:
        print("Please enter valid numbers!") # handle wrong inputs
        
    if (input("Another calculation? (y/n) " )=="y"):
        calc()
    
    
calc()

Day 4: Using Lists

We are checking out how to include input-strings to a list. Interestingly the append()-function for the list only takes one argument/variable at a time.

This program would also not be possible with a tuple – because tuples can’t be changed after initialization.

 

data = []

name = input("Enter your name: ")
age = input("Your age please: ")
city = input("The city you live in: ")

data.append(name)
data.append(age)
data.append(city)

print("Hello " + data[0] + "! You are " + data[1] + " years old and live in " + data[2] + ".")

Day 3: One Of A Kind – painting with ASCII Code and Python

Today we are building a program that writes a random “painting” in the terminal. We use a list of ASCII-Symbols as our paint. The output looks like this:

Our “art” will win no prizes but we use a function with two for-i-in-range-loops.

 

from random import randint # so we can use random/randint


def get_artsy(size):
    line = ""
    ascii = ["█","$","≡","╬","¿","▒","░"] # our ascii canvas-symbols
    for i in range(0,int(size)):
        line = line + ascii[randint(0,6)] # building the random line of ascii-symbils

    for x in range(0,int(size)):
        print(line*2) # double the line before printing so we get a more square canvas


get_artsy(input("Enter the size of the painting: "))

Day 2: A real classic – guess a number with Python

Today we code a little app that will take in a users number between 1 and 10. The program will generate a random number between 1 and 10 and will compare the two. If the user guessed right, he will get a friendly message and vice versa.

The Code:

from random import randint #so we can use randint

def guess_number(your_guess):
    random_nr = randint(1,10) # generate a random number between 1 and 10
    if (int(your_guess)==random_nr):
        print("You guessed right!")
    else:
        print("Sorry,you guessed wrong.")
    return

guess_number(input("Guess a number between 1 and 10: "))

 

Day 1: How many days, minutes and seconds does the year have?

For New Years we are writing a Python program that calculates days, hours and seconds of a given year. It also checks if the year is a leap year and adds a day.

The result looks like this

 

The code is pretty straight forward and looks like this:

def day_hours(year, is_leap_year):
    if (is_leap_year):
        days = 366
    else:
        days = 365
    print ("The year " + str(year) + " has:")
    print ("Days: " + str(days))
    print ("Hours: " + str(int(days)*24))
    print ("Minutes: " + str((int(days)*24)*60))
    print ("Seconds: " + str(((int(days)*24)*60)*60))


day_hours(2018, False)