Newbie - 1st Program

Ben Finney bignose-hates-spam at
Mon Nov 10 03:11:45 CET 2003

On Mon, 10 Nov 2003 02:03:02 GMT, Mark Smith wrote:
> I'm trying to learn to program and Python seems to be the best
> "Starter" language (I've sat through various C tutorials, but have
> never used the language "in anger").

Guido van Rossum is actively involved with promoting Python as a
language to use for teaching first-time programmers, so it's good to see
that you think it's appropriate.

> It seems to work - great - but how would you make this more 'elegant'
> - I'm sure it's horrible to an experienced hacker...

Looks fine to me.  Well-chosen names, basic sequential flow.

Probably the first improvement I'd make is to take advantage of the fact
that a Python program can be both a script (run as a command) or module
(imported to other programs) with a single file, heavily promoting code

Take the functionality that is potentially useful to other programs, and make
functions and/or classes that implement that.  (I've use examples that are
rather trivial for library functions here, but the principle is illustrated.)

Then, have the "main routine" only execute when the program is invoked as a

    # Cross-connect calculator

    def cross_connects( ports ):
        """ Calculate number of possible cross-connects
        return ( ports / 2 ) * ( ports - 1 )

    def get_ports():
        """ Get the number of ports from the user
        in_ports = input( "Number of Input Ports: " )
        out_ports = input( "Number of Output Ports: " )
        return ( in_ports, out_ports )

    def total_ports( in_ports, out_ports ):
        """ Calculate the total number of ports in the network
        return ( in_ports + out_ports )

    # Main routine
    if( __name__ == '__main__' ):
        ( input_ports, output_ports ) = get_ports()
        num_ports = total_ports( input_ports, output_ports )
        num_connects = cross_connects( num_ports )
        print "Total number of cross-connects:", num_connects

 \              "Whatever you do will be insignificant, but it is very |
  `\                     important that you do it."  -- Mahatma Gandhi |
_o__)                                                                  |
Ben Finney <>

More information about the Python-list mailing list