Tags

, , , , , , , , , , ,

Following on from my last post on Python scripting, this looks at text manipulation, branching statements, and functions.

Pyg Latin Translator
One of the CodeAcademy projects was to create a Pyg Latin translator (download here), which took a bit of problem solving to complete.
To start with, at least two variables are needed: one for the word to be translated, and another for the ‘ay‘ to be appended to certain words after translation. The other variables are added along the way. Sometimes it’s a good idea to draw concept diagrams before writing code.

pyg = 'ay'
original = raw_input('Enter word: ')
word = original.lower()
first = word[0]
new_word = str(word) + pyg
length = len(word)

The stuff below is mainly for validating the input, to check the input string has at least one character, and no numbers or symbols. The program then braches, depending on whether the first character is a vowel or consonent.
What’s stored in the new_word buffer is the original word with the first character shifted to the end, and with ‘ay‘ appended.

if len(original) > 0 and original.isalpha():
if first == 'a' or first == 'e' or first == 'i' or first == 'o' or first == 'u':
print original
else:
new_word = word[1:length] + word[0] + pyg
print new_word
else:
print 'Incorrect - Cannot translate'

Functions
When code reaches a certain level of complexity, it’s a good idea to break it down into discrete modules, or functions. This provides several advantages: if it’s known what each function does individually, the program as a whole becomes easier to understand, test and debug. A modular approach also allows makes it possible for multiple developers to work on the same project, each developer having a clear boundary. In theory, developers can also re-use functions across different projects, as we would with Python modules.

Functions are defined with the def (define) statement, usually before the main code that ties them all together. e.g.
def function_name(parameter)

Parameters are a bit like local variables, the difference being they’re passed between a function and the main program, or possibly between functions. A function may also be called from an existing Python module, as with square(), str() and string.lower() in the examples posted here last week.
"""Since we're not importing the math module, we can define our own
function called square(), with 'n' as a variable"""

def square(n):
squared = n**2
print "%d squared is %d." % (n, squared)
return squared

#Call the square() function and pass the value '50' as input
square(50)

And an example of passing values between two functions:
def cube(cubenum):
cubenum = n**3

def by_three(n):
#Check in n is perfectly divisible by three
if n % 0 is True:
cube()
else:
return False

by_three(11)
by_three(12)
by_three(13)

Taking it one stage further still, the main program can have an if/then branching statement that calls whatever function:
def really_shut_down():
print "Shutting down..."

def abort_shutdown():
print "Shutdown aborted!"

def error_msg():
print "Wrong input."

#Main function with 'snum' as variable
def shut_down(snum):
snum = raw_input('Really shut down?')
if snum = "yes" or snum = "YES" or snum = "Yes":
return really_shut_down()
if snum = "no" or snum = "NO" or snum = "No":
return abort_shutdown()
else:
return error_msg()

Message Hashing with MD5, SHA1 and SHA2
After experimenting a bit with stuff outside the CodeAcademy tutorials, I made a little script that hashes messages using the MD5, SHA1 and SHA2 algorithms. Getting the module and function names was a case of trial and error, but there’s documentation to help.
import hashlib

MessageIn = raw_input('Message: ')

MD5Digest = hashlib.md5(MessageIn)
SHADigest1 = hashlib.sha1(MessageIn)
SHADigest2 = hashlib.sha256(MessageIn)

print "MD5 HASH: " + MD5Digest.hexdigest()
print "SHA1 HASH: " + SHADigest1.hexdigest()
print "SHA2 HASH: " + SHADigest2.hexdigest()

Advertisements