Day 23: Dir, Help And Pdb – Make Use Of Pythons Little Helpers

 

The shell command dir lists all attributes an object has – and remember everything in Python is an object.

Start your terminal and enter „python“ to start the IDLE mode. Then type for example dir(‚linus‘) and you will

get all the attributes for „linus“ which in this case is a string.

 

 

Pretty neat isn’t it? But that’s not all Python will do for you. The help-function will deliver even deeper information

about other functions. We can use it on the command ‚linus‘.lower for example like this:

 

help(‚linus‘.lower)

 

Here is the output:

 

 

The help-function returns information about virtually everything in Python.

 

Your Python comes with its own Docs installed – amazing!

 

And there is even more you say? Yes indeed! With pdb Python has its own integrated debugger!

 

With the debugger you can go through your code line by line and look up any possible bugs!

 

To use pdb you will have to include the following lines in the code.

 

import pdb

pdb.set_trace()

 

Once you run the program the execution will stop once the interpreter comes across the pdb.set_trace() command.

You will be redirected to the shell where you can go through every line manually and see how your

code behaves. With „n“ or „next“ you can jump to the next line of code.

 

pdb can do a lot more for you actually. You find the complete documentation here

 

 

 

Day 21: A String Of Events – Some Basic String Consideration

 

Just some basic string paradigms. Explanation in comments

 

name =  "Robert"
age = 42

print("{} is {}".format(name, age))   # Output: Robert is 42


print("Name: {:*^22}".format("Ringo"))  # Output: ********Ringo*********

(5).conjugate()         # 5 needs to be in parantheses. Otherwise Python confuses the . with a float

filename = "hello.py"

# fyi: we use lower() to catch unformated user input
print(filename.lower().endswith(".java"))     # returns False
print(filename.lower().endswith(".py"))       # returns True

print(filename.lower().startswith("world"))   # return False
print(filename.lower().startswith("hello"))   # return True

print(filename.find("py"))                    # returns 6 - the index of "p"

print(filename.find("java"))                  # returns -1

Day 20: A Very Simple Music Player In Python

 

We use pyglet to play an mp3-file – this is a very simple example.

The player has no controls – I just wanted to make a point and play a Music-File from the Shell

We need AVBin installed on the computer to decode the MP3-File

 

#! A very simple Music player
# Pyglet handles the playing of the audio files
# we need AVBin to decode the mp3 file 
# otherwise we get an error

import pyglet           

music = pyglet.resource.media('music.mp3')  # get the media file
music.play()

pyglet.app.run()

Day 19: Count the Raven how many words?

This little script delivers the number of words in a text-file.

Our example uses the poem „The Raven“ by Edgar Allen Poe

but the program works for any .txt-File.

 

#! Count words in a .txt file
# open a given txt-file and read it line by line
# split the words from the string with line.split()

import os
num_words = 0

with open("the_raven.txt", 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)

print("Number of words:")           # Output: Number of words:
print(num_words)                    # Output: 1067

Day 13/14: Cracking the Code – the string maketrans function

 

In this episode we are cracking one challenge from the amazon Python Challenge

 

In entry two there is a encrypted code that needs some cracking!

If you look closely at the string you notice that all letters are shifted by two. Instead of „abc“ its „cde“ and so on.

To crack this code we use the maketrans-function.

 

Here is the code:

import string

raw = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle grgl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."

# the maketrans function transforms our coded string with a new set of letters
table = string.maketrans(
    "abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab"
)

# setting up the decoded string for printing.
result = raw.translate(table)

print(result)

The output looks like this:

 

Day 12: Do It Like The Greeks – Basic Arithmetic Operations In Python

 

Today just some samples of basic operation and their output on the shell.

 

print(type(1))      # class "int"
print(type(2.45))   # class "float"

#ADDITION
print(2 + 3.5)      # 5.5 <-- int gets converted to float auto


number = 5
number += 4         # 9 <-- number =  number + 4

print(number)

print(.4+.01)       # 0.4100000000003 <-- float will have some rounding error

#SUBSTRACTION
print(2 - 3.5)      # -1.5

#MULTIPLICATION
print(6 * 2)        # 12
print(6 * .25)      # 1.5
print(4.5 * 2.3)    # 10.35

#DIVISION
print(12 / 4)       # 3
print(3 / 4)        # 0.75 <-- output is a float
print(3 // 6)       # 0 integer division

#MODULO
print(4 % 3)        # 1
print(3 % 2)        # 1 <-- odd number
print(6 % 3)        # 0 <-- even number

#POWER
print(4 ** 2)       # 16
print(4 ** 6)       # 4096

#ORDER OF OPERATION
print(3 + 6 * 2)    # 15 <-- * and / before + and -
print((3 + 6) * 2)  # 18 <-- paranthesises come before * and /
print(((3 / 2) + 6 * .5) * 2)   # 9.0

Day 10/11: 99 In The Shade – we’re building a Fahrenheit-Converter with Python

Its a simple function that converts Celsius to Fahrenheit.

 

 

We only have exception and thats when the user enters a number below absolute zero (-273.15 degree celsius).

 

def fahrenheit(celsius):
    convToFahrenheit = 9.0/5.0 * celsius + 32
    return convToFahrenheit

celsius = (float(input("Enter Celsius: ")))

if celsius >= -273.15:
    print ("Fahrenheit: " + str(fahrenheit(celsius)))
else:
    print ("Sorry the lowest possible temperature in Celsius is -273.15 degrees.")

Day 9: Pythons Safe Words – dont use Keywords and Built-ins!

Python has a number of Keywords that you are not allowed to use as class, function or variable names.

and

as

assert

break

class

continue

def

del

elif

else

except

exec

finally

for

from

global

if

import

in

is

lambda

while

with

yield

print

raise

return

try

Python has also a variety of build-in-functions like print() and object(). While you are not allowed to use keywords
in any other context, you can name a variable or a function „print“ or „object“ without getting an error. But you really
shouldn’t do this since your own object will override or shadow the build-in-function – at least name wise.

If you write a function „def print(x):“ it will work just fine as long as you don’t want to use the buld-in print-method.

So it is really not recommended to use any of these build-ins

Day 8: Identity, Type & Value – a coming of age story about objects.

Everything from a string to a class is an object in Python. And every Object is defined by Identity, Type and Value.

 

Identity – refers to the location of the object in the computers memory (ie. id: 4358658568)

Type – is it a number or a string or a function? (possible types in Python include: str, int, float, list, tuple, dict, class, type, function)

Value – is the value of the object (ie. a string could be „Hello“ or a number could be 3.14)

 

The id or the memory-location is not particularly useful in Python compared to other languages where you might have to

free the memory manually. When a Python program exits it clears all the used memory by itself – Python is a good sport so to speak.

Memory Management in other languages can be a bit of a pain in the elbow.

 

But you can learn a lot about the lifespan and behavior of objects such as strings when you know their ID –  just look at the following code:

 

name = "robb"       # name gets a value "robb"

name2 = name        # name2 gets the value of name which is "robb"

# even though they are two different variables, they share the same id or memory slot
print(id(name))     # id: 4374158280
print(id(name2))    # id: 4374158280

name2 = "adrian"    # change name2 to "adrian"

# the id of name stays the same, while name2 gets a new id as expected
print(id(name))     # id: 4374158280
print(id(name2))    # id: 4375412952

name = name2        # change name to the value of name2, which is "adrian"

#they both have the same id again 
print(id(name))     # id: 4375412952
print(id(name2))    # id: 4375412952

name = "robb"       # changing name back to its original value

print(id(name))     # id: 4374158280 <--It's the same ID again as it was in the first place (line 6) - crazy!
print(id(name2))    # id: 4375412952

I would have assumed that name gets a new id in the end, since we re-change the value to „robb“
but Python apparently remembers „Aha – we had that value before and gives the id of the memory
location back to the name-variable – it’s a neat way of managing memory space…

 

The above only works for immutable types though – a new or changed value changes the id.
(Immutable types are strings, integers, floats and tuples.)

 

Mutables types on the other hand, like lists or dictionaries, can change their value and
will still keep their original id. Just look at this:

 

a_list = ["robb", "adrian"] # we generate a list that holds two values

print(id(a_list))           # id: 4383824392

a_list.append("linus")      # we include another value to the list

print(id(a_list))           # id: 4383824392 <-- the value stays the same

del a_list[:]               # clear the list of all values

a_list.append("sara")       # enter a new value

print(id(a_list))           # id: 4383824392 <-- still the same.

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