logo

 

     
 
Home
Site Map
Search
 
:: Bitwise Courses ::
 
Bitwise Dusty Archives
 
 
 

rss

 
 

ruby in steel

learn aikido in north devon

Learn Aikido in North Devon

 


Section :: Python
- Format For Printing...

Get To Grips With Python

part one
Wednesday 2 July 2008.
 

Over the past few years I’ve been so involved with the Ruby language that I’ve been guilty of ignoring an important alternative, Python. The two languages have much in common - they are both dynamic, object oriented languages with a simple syntax far removed from the ‘curly-bracket’ C-like languages which are so dominant. In this new series, I plan to explore the basics of the Python language. If you are interested, you may want to follow my progress...

First you will need to grab a copy of a Python interpreter and an IDE or editor. The main Python site is here: http://www.python.org/. Here you can navigate to the download page and choose a version of Python for your operating system. Alternatively, you can download ActiveState’s ActivePython - a complete distribution with a number of useful extensions and documentation. ActiveState also has a multi-language editor, Komodo Edit, which is free and includes Python support. The screenshot below shows The Komodo IDE, which is a more powerful commercial alternative to Komodo Edit. More information and downloads can be found on the ActiveState site.

With Komodo, you can load all the source files as a single project and interact with the program in the window seen here at the bottom-right of the screen.
Zip - 3.7 kb
Source Code

I have previously written a free tutorial to the Ruby language, The Little Book Of Ruby, which is available for download from the SapphireSteel Software site. In this series, I shall follow the pattern of the first few chapters of The Little Book of Ruby to find out how to perform the same basic programming tasks using Python. I should say at the outset that I am no Python expert. When you follow this series, please bear in mind that you will be following the progress of somebody who is much more familiar with Ruby (and various other languages). It is quite possible, therefore, that I may sometimes miss out on some special Python ‘tricks’ - if so, please feel free to leave a comment to let me know!

Anyway, without more ado, let’s get coding.

Hello World

First, let’s get the obligatory ‘Hello world’ program out of the way. Create a new python file (for example, helloworld.py) and enter the following into it:

print "Hello World"

When you run this program (, at a command prompt, enter: python helloworld.py or, in Komodo, press CTRL+F7), you should see:

Hello World

No surprises so far!

Having displayed some output, the next step is to get some input. To do that we will use the raw_input() method to read in some data entered at the command line and this will then be assigned to the variable, name:

- helloname.py

name = raw_input( 'Enter your name: ' )
print( 'Hello ' + name )

Note, by the way, that each bit of sample code is provided in this article’s source code archive. You may either load the files one by one or, if you are using ActiveState’s Komodo, you may load them all at once as a single project - in this article, I’ll give the name of each file (as above) with each code fragment.

Python also has an input() method which could be used instead of raw_input(). However, input() requires that any data input should form valid Python. That would mean that you would have to include string delimiters around your name (e.g. “Fred”), whereas raw_input() automatically treats all input data as strings.

Note, incidentally, that Python is a case-sensitive language. So, in the above example, the variable name must be spelled in lowercase letters in both places. You could, if you prefer, spell variables in uppercase or a mix of cases such as Name but, if you do so, you must be sure to use the same case whenever you use the variable.

Python lets you delimit strings either with single or double quotes. This gives you a convenient way to embed quote characters in a string like this :

- stringdelims.py

print "It's hello from me!"
print 'And it is "Goodbye" from him!'

You can include non-printing characters in strings such as newlines \n and tabs \t. You may also assign values to variables and include those in strings. When a variable is included its position is marked by placing a % into the string followed by a type specifier such as %s for a string or %f for a floating point. A floating point value may also include ‘field widths’ before or after the point like this: %10.2f. The actual variable to be substituted into the string must be placed after the % character following the string. Here is an example. This...

- string_format.py

greeting = "Hello world"
print "\t%s\n!" % greeting

... prints out this:

    Hello world
!

If you want to print all characters including \n and \t literally, by the way, you can do so by preceding the string with ‘r’ to show that it is a ‘raw’ or unprocessed string. This...

print r"\t%s\n!" % greeting

...prints out this:

\tHello world\n!

Note: For a full list of string formatting specifiers, refer to the Python Language Reference at http://docs.python.org/dev/reference/index.html. You will find the relevant details under Lexical analysis/Literals. In this series I shall assume that you will refer to the Python documentation for full details of available options when necessary.

In addition to variables you can also evaluate expressions and substitute these into a string. When multiple variables or expressions are substituted they must be enclosed by brackets. This...

xxx = "Diamond"
yyy = 10000
print "The %s costs $%.2f. Two will cost $%.2f." % (xxx,yyy,yyy*2-150)

...prints out this:

The Diamond costs $10000.00. Two will cost $19850.00.

If you need to divide a string over multiple lines you may add the line continuation character \ at the end of a line. This...

print "I wandered lonely as a cloud, \
That floats on high o'er vale and hill"

...prints out this:

I wandered lonely as a cloud, That floats on high o'er vale and hill

In order to preserve the line breaks in a string, use three string delimiters - that is either ’’’ and ’’’ or """ and """. This...

print """I wandered lonely as a cloud,
That floats on high o'er vale and hill"""

...prints out this:

I wandered lonely as a cloud,
That floats on high o'er vale and hill

String Operations and Method Calling

Now let’s see what other things we can do with strings. Being a Ruby programmer, I am now already feeling so at home with Python that I feel confident enough simply to copy my Ruby code to put a string in upper case. Strings, like all other bits of data, are objects and they have their own methods one of which is called upper. So here is my code to display “hello world” in uppercase:

- uppercase.py

print( "hello world".upper )

Oops! It seems my confidence may have been misplaced. This is what Python displays...

<built-in method upper of str object at 0x01602728>

In Ruby, I can call methods with or without a pair of brackets after the method name. Python is not so permissive. If I omit the brackets, it considers that I am referring to the method itself. If I want to call the method, I must use brackets. This...

print( "hello world".upper() )

...prints this:

HELLO WORLD

So what is the point of allowing the syntax that omits brackets? Well, it turns out that this gives you the possibility of assigning methods (that is method objects) to variables - just as you would assign any other type of data. You can then, if you wish, execute those method variables, like this:

x = "hello world".upper
print( x() )

Or you could even pass those variables to other functions or methods like this:

def myFunction( aFuncVar ):
   print( aFuncVar() )         # call the method!
   
myFunction( x )

Comments: Note that any part of a line following a # character is treated as a comment (and will be ignored by the Python interpreter):

# This is a comment

Methods and Functions

In the last example, I wrote a function called myFunction. Python distinguishes between functions (free-standing subroutines) and methods (subroutines that are bound into objects). Functions may take 0 or more arguments placed between brackets. Methods take 1 or more arguments, the first of which is a reference (self) to the object to which the methods belong.

A method is so called because it provides a method (that is, ‘a way’) for an object to respond to messages. In OOP terminology, you send a message to an object by asking it to do something. So let’s imagine that you have an object called ob which has a method called saysomething(); this is how you would send it a saysomething() message:

- object.py

ob.saysomething()

Let’s suppose that the saysomething() method looks like this:

def saysomething(self):
        print( "Hello" )

Notice that a method is defined by preceding its name with the def keyword. The result is, that when you send ob a saysomething() message it responds with the saysomething() method and displays ‘Hello’.

Methods are defined as part of a ‘class’ definition where the class acts as a blueprint for new objects. Here is the definition for a class named MyClass with a method called saysomething():

class MyClass:
   def saysomething(self):
       print( "Hello" )

To create an object based on this class, I just call the class constructor (in the simplest version this will be the class name itself followed by a pair of brackets) and assign the resulting object to a variable: ob = MyClass(). Here then, is the full code needed to define a class, create an object from it and call a method:

class MyClass:
   def saysomething(self):
       print( "Hello" )

ob = MyClass()
ob.saysomething()

Pay attention to the colon : that follows both the class name and the method name. This is Python’s way of marking the start of the class and method code. So if the colon is the ‘begin marker’, where is the ‘end marker’? In Python, the end of a code is indicated by indentation. Anything that is indented more than the thing above it ‘belongs’ to the thing beneath which it is indented. So the method saysomething() belongs to MyClass - and so would any other methods placed at the same level of indentation.

When we come to the line ob = MyClass we are back at a lower level of indentation so this does not ‘belong’ to MyClass. Put simply, the colon is like a C/Java opening curly bracket or a Pascal ‘Begin’. The closing curly bracket (or ‘end’ keyword) is not needed since the end of a code block is indicated by indentation (that is, when any code is indented to the left of the code above it, the code above it implicitly has an ‘end’ marker).

Incidentally, when indenting, do not mix spaces and tabs! A tab indent may look like (for example) 4 spaces but the Python interpreter will only consider it to be one character, not four. It is possible that your editor may ‘correct’ these potential errors - but don’t rely upon it. Either use all tabs or all spaces, not a mix of both. Here is a slightly more complex example:

- method.py

class MyClass:
           
   def showstring( ):
       print( "Hello"  )
   
   def showname( aName ):
       print( "Hello %s" % (aName))

ob = MyClass()
ob.showstring()
ob.showname("Fred")

Numbers

Numbers are just as easy to use as strings. For example, let’s suppose you want to calculate the selling price or ‘grand total’ of some item based on its ex-tax value or ‘subtotal’. To do this you would need to multiply the subtotal by the applicable tax rate and add the result to the value of the subtotal. Assuming the subtotal to be $100 and the tax rate to be 17.5%, this Python code would do the calculation and display the result:

- numbers.py

subtotal = 100
taxrate = 0.175
tax = subtotal * taxrate
print "Tax on $%.2f is $%.2f, so grand total is $%.2f" % (subtotal, tax, subtotal + tax)

Obviously, it would be more useful if it could perform calculations on a variety of subtotals rather than calculating the same value time after time! Here is a simple version of a Tax Calculator that prompts the user to enter a subtotal:

- numbers2.py

taxrate = 0.175
s = raw_input( "Enter price (ex tax): " )
subtotal = float(s)
tax = subtotal * taxrate
print "Tax on $%.2f is $%.2f, so grand total is $%.2f" % (subtotal, tax, subtotal + tax)

In the above example, we’ve included the prompt as an argument to raw_input() and converted the string entered by the user to a floating point value using float() (this assumes that the user will enter a valid number otherwise an error will occur).

Testing a Condition: if

The problem with the simple tax calculator code shown above is that it accepts minus subtotals and calculates minus tax on them – a situation upon which the Government is unlikely to look favourably! I therefore need to check for minus figures and, when found, set them to zero. This is my new version of the code:

- tax_calculator.py

taxrate = 0.175
s = raw_input( "Enter price (ex tax): " )
subtotal = float(s)
if (subtotal < 0.0) :
   subtotal = 0.0
tax = subtotal * taxrate
print "Tax on $%.2f is $%.2f, so grand total is $%.2f" % (subtotal, tax, subtotal + tax)

Notice that the code of the if test once again is delimited by a colon to begin and the final lines at its indentation level to end. The brackets around the if conditional are optional and some Python programmers don’t like them. I have no such anti-bracket prejudice (quite the contrary, in fact) and so I shall use them.

There is still the problem of dealing with non-numeric input, of course. One way of dealing with this is to write an exception-handling block. If you try entering a string such as “XXX” when prompted by the tax calculator program, you will see that a ‘ValueError’ occurs - so this tells me the type of exception which I need to trap. Exception-handling is a bit beyond the scope of this article but you can find a simple example in the file, value_error.py.

AddThis Social Bookmark Button

Forum

  • Commodo has IDE?
    11 August 2008, by Ali

    hello. You show a screen shot of commode. I want to know does it have an IDE to create and design the element of my forms. Thanks

    • Commodo has IDE?
      11 August 2008

      Komodo doesn’t have a visual designer, I’m afraid :-(

  • Get To Grips With Python
    8 July 2008, by Mike Woodhouse

    I use Python from time to time - it’s a decent enough language, although I remain happier with Ruby where possible. I really hate the colon though - either denote structure with indentation, in which case the colon is superfluous, or don’t.

    It just seems like whatever the opposite of "syntactic sugar" would be. Syntactic vinegar?

    Or am I missing something?

    • Get To Grips With Python
      10 July 2008, by Brad

      Although a lot of people hate Python because of using indentation delimiters, I dont think anyone can argue its makes extremely readable syntax over end delimiters. Ruby has even more cleaner syntax than Python, especially where OOP is concerned, and I often wish Ruby had an option to use indentation as a delimiter more than it does currently with its newline seperated loop structure. Maybe someone could make an IDE that will allow programmers to use indentation delimiters in the IDE, but adds the end delimiters when saving.

      One other thing that should be pointed out is that Lua gets a lot of attention for its functional programming features like first order functions and lamba expressions. But all that stuff is in Python, so you are wasting your time with Lua if that is your only reason for learning that language.


Home