Plutonic Rainbows

More Functions

Another attempt at multiplication with slightly better output. Of course, it doesn't need to be math-based - you can use anything. That's the beauty of it.

#multiply two numbers and divide by the third.

def calc(value1, value2, value3):
    return value1 * value2 / value3

value1 = (float(raw_input("\nThe number: ")))

value2 = (float(raw_input("\nMultiplied by: ")))

value3 = (float(raw_input("\nDivided by: ")))

answer = calc(value1, value2, value3)

print "\n{0:.0f} multiplied by {1:.0f} and divided by {2:.0f} is: {3:.1f}\n".format (value1, value2, value3, answer)

Reading Files and Numbering Lines

Python can read other files (as we know) but it can also rewind and print the lines again. Just define a function called rewind and you're all set to go.

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First, let's print the whole file:\n"
print_all(current_file)

print "Now rewind."
rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

Creating Lists

Looking through lists again. How to create a simple list and assign it to a variable.

albums = ['Meddle', 'Atom Heart Mother', 'Dark Side of the Moon', 'Wish You Were Here', 'The Wall']

for albums in albums:
    print "An album by Pink Floyd: %s" % albums

String Length

Python's len() method can be used to easily find the length of a string. It's a simple and quick way to measure the length of a string (the number of characters) without having to write a lot of code. The syntax for using the len() method is fairly straightforward, and hard to mess up. Even I can manage it.

from sys import argv

script, file = argv

source = open(file)
indata = source.read()

print "The file called '%s' is %s bytes in length." % (file, len(indata))

Remember that len() calculates the string so it can be used for characters too. You could ask Python to count the letters in a word or sentence.

Music for Installations

Out next Friday (May 4th) is the long-awaited Brian Eno box set, featuring some previously unreleased music; despite what the PR machine might say. You can order it from Amazon or Bleep.