[Tutor] programming newbie question
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)
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.
self.pos = pos
Which in turn can be used like this.
>>> a = MyClass() ## pos defaults to [0,1,0] so I don't have to specify
>>> print a.pos
>>> a.pos = [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.
> 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
More information about the Tutor