[Tutor] programming newbie question

Jacob S. keridee at jayco.net
Fri Dec 3 03:50:20 CET 2004


> I am fairly new to programming and I have started to learn programming
> then stopped out of frustration several times in the past.  I guess my
> frustration stems from not being able to understand when to use certain
> aspects of programming such as functions or classes.

Use functions when you will execute a certain code block many, many times
during a script. Or if you want to make a code block simpler and more
generic. For example...

def rfill(stri,length,sep=" "):  # stri is short for string, and sep
(seperator) is defaulted to a space
    stri = str(stri) # This is to help make sure that what the user gives us
is a string
    if stri < length:
        stri = stri + sep*(length-len(stri)) # This fills the string to the
length with seperators
    return stri # This returns the string so we can assign it, print it etc.

Usage is as follows:

a = 'The'
b = 'Many'
c = 'Two'
e = 'Forty'
f = [a,b,c,e]
for i in range(4):
    print "%s%d" % (rfill(f[i],15),i)

yields

The            0
Many           1
Two            2
Forty          3

This is just one example. You can use functions over and over from anywhere
in your script.
Classes are just like defining new types. You have the usual types like
dictionary, list, tuple, integer, float, etc.  but with classes you can
define your own. Methods are just attributes of classes, or so I understand.
For example...

class MyClass:
    def __init__(self,pos=[0,1,0]):
        self.pos = pos
    def printpos(self):
        print self.pos

Which in turn can be used like this.

>>> a = MyClass()  ## pos defaults to [0,1,0] so I don't have to specify
explicitly
>>> print a.pos
[1,0,1]
>>> a.pos = [1,2,1]
>>> a.printpos()
[1,2,1]
>>>

The most interesting use of classes that I have seen is the VPython package
where they define new classes (again I think of them as types) as shapes
with attributes (or methods - like L.append() which refers to appending to
lists) like position, color, radius, axis, etc.
But I digress.

HTH,
Jacob Schmidt

> I have read enough
> books and tutorials to know the syntax of python and I understand most
> everything related to the concepts of programming, but I have never been
> able to put it all together and learn how and when to use specific
> features.  Can anyone suggest a method or some reading to help out with
> this?  I also struggle with finding projects to work on does anyone know
> of projects that a novice could contribute to?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list