[Tutor] Another Newbie question
bhaaluu at gmail.com
Tue Jun 24 13:39:09 CEST 2008
On Tue, Jun 24, 2008 at 6:23 AM, Danny Laya <danny_laya at yahoo.com> wrote:
> Hi I got some problem about writting convention in python. Some tutorial ask
> me to write this :
> a = 1
> s = 0
> print 'Enter Numbers to add to the sum.'
> print 'Enter 0 to quit.'
> while a != 0:
> print 'Current Sum:', s
> a = int(raw_input('Number? '))
> s = s + a
> print 'Total Sum =', s
> And the response must be like this :
> Enter Numbers to add to the sum.
> Enter 0 to quit.
> Current Sum: 0
> Number? 200
> Current Sum: 200
> Number? -15.25
> Current Sum: 184.75
> Number? -151.85
> Current Sum: 32.9
> Number? 10.00
> Current Sum: 42.9
> Number? 0
> Total Sum = 42.9
> But when I write until this :
>>>> a = 1
>>>> s = 0
>>>> print 'Enter Numbers to add the sum'
Try putting the program in a function.
A function is defined using: def functionName():
Everything inside the function is indented.
a = 1
s = 0
print 'Enter Numbers to add to the sum.'
print 'Enter 0 to quit.'
while a != 0:
print 'Current Sum:', s
a = int(raw_input('Number? '))
s = s + a
print 'Total Sum =', s
In this example, the function is called main()
and it is defined with with the keyword 'def'
followed by the name of the function, parentheses,
and finally a colon (:). Don't forget the colon!
The body of the function is indented. Make sure you
indent the lines inside the function when you are entering
it in the interactive interpreter. The while loop needs more
indentation with the function body! Look at it carefully!
Finally, call the function. In the above example, the function
is called by entering: main() on a line by itself. It is NOT a
part of the function body.
I hope this is helpful. I remember when I was first starting out
with the Python interactive interpreter. It wasn't easy. Good luck!
Stick with it. It won't be long before you look back on these
beginning days and laugh.
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
> I press enter, and alas my python response me :
> Enter Numbers to add the sum
> It didn't want waiting me until I finish writing the rest.
> I know there is some mistake about
> my writing convention,
> but what ??? Can you find it ??
> But you know it's not finish,I ignore the error message and
> writng the rest, but until i write this:
>>>> while a != 0:
> ... print 'Current Sum:', s
> ... a = int(raw_input('Number?'))
> ... s = s+a
> ... print 'Total Sum =', s
> Oh, man... another error message :
> File "<stdin>", line 5
> print 'Total Sum =', s
> Can you help me guys ??
> Tutor maillist - Tutor at python.org
More information about the Tutor