Solved

Python 2.5 Hello Word - how to use imports for goto

Posted on 2012-04-06
9
508 Views
Last Modified: 2012-04-06
My 13 year old son is learning Python.  I was talking through an algorithm and before using if then else control, I chatted up goto.  Turns out it wasn't available.  I wanted him to do it with goto, then use the if then else as a better construct.

The Hello World book doesn't document goto, but via Google, it appears you can use imports to add the goto capability for flow control.

Any thoughts on how to get this construct working?

Dave
0
Comment
Question by:dlmille
  • 4
  • 4
9 Comments
 
LVL 28

Accepted Solution

by:
pepr earned 300 total points
ID: 37815390
There is no goto in Python and it can be confusing for a beginner to show/explain how to simulate the goto as it is much more complex.  Have a look at http://docs.python.org/faq/design.html#why-is-there-no-goto.  It may be better to show the goto command in another language.
0
 
LVL 9

Assisted Solution

by:zaghaghi
zaghaghi earned 200 total points
ID: 37815414
This can help: goto
but I'm agree with pepr
0
 
LVL 41

Author Comment

by:dlmille
ID: 37815529
So is it an April Fools Joke or can it be imported re: your post?  that's the post I found and didn't catch the "joke"

Dave
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 28

Expert Comment

by:pepr
ID: 37815552
:) The goto module is great!  Actually, it is even more complex than the above Python FAQ. (Don't use it for anything serious!)
0
 
LVL 41

Author Comment

by:dlmille
ID: 37815553
Another one if you don't mind.

We were doing looping tonite, and we did a for loop using a range, and a while loop with an increment variable.  It evolved to this:

import datetime

whileStartTime = datetime.datetime.now()
print "We are starting while!", whileStartTime
x = 0
while x < 90000000 :
    x = x+1

whileEndTime = datetime.datetime.now()
whileTime = whileEndTime - whileStartTime
print "We are done!", x, whileEndTime, "net time: ", whileTime
        

forStartTime = datetime.datetime.now()
print "We are starting for!", forStartTime

for x in range (1,90000000) :
    x = x+1

forEndTime = datetime.datetime.now()
forTime = forEndTime - forStartTime
print "We are done!", x, forEndTime, "net time: ", forTime

if forTime == whileTime:
    print "for time is the same as while time"
elif forTime > whileTime:
    print "while time is superior than for time by " + str(forTime - whileTime)
else:
    print "for time is superior than for while by " +  str(whileTime - forTime)

Open in new window


What was interesting to both of us (as we thought the for loop would naturally be faster) is that the while loop was faster by about 25%.  Is this because the range() is inefficient?

Anyway, that's my last question hopefully its worth your thought on top of the first.  I certainly wasn't going to encourage GoTo and while I use it in VBA quite a bit (for On Error, mostly, and appropriate - to quote rorya, "leverage what the language gives you")).  I was trained enough 2+5 years ago in Data Structures that there are better constructs to control flow.  In fact, I was so averse to it that I would create functions to loop through lists to determine what I was about to connect wouldn't error - though time and effort pulled me back to the OnError statement to trap a miss-assignment.

Cheers,

Dave
0
 
LVL 28

Assisted Solution

by:pepr
pepr earned 300 total points
ID: 37815684
The range() function in Python 2.x generates a list of the values into memory.  This way, your range(1, 90000000) is quite consuming on its own.  Only after the list was generated, the loop starts.  In that sense, the range() is not inefficient.  It does something different than you expected.  Try to use xrange(1, 90000000) instead.  It generates the values on-the-fly.  (By the way, the line 18 does not make too much sense, but you probably know).  Python 3.x redefined range() so that it behaves the same way as xrange() in Python 2.x.

The more important for the for-loop in Python is that the loop is not based on counting (as in C-family languages or in many other languages).  It is more general (more modern) and it is the equivalent of the for-each like loops in other languages.  It is based on using iterators.  You usually do not use counted loops in Python.

There is a timeit module for measuring docs.python.org/library/timeit.html

I also sugges to read Mark Pilgrim's "Dive Into Python 3", Chapter 4. Strings (http://diveintopython3.ep.io/strings.html) in advance (the problem with strings and encodings).  It will help you also with other things to avoid re-learning later.
0
 
LVL 28

Assisted Solution

by:pepr
pepr earned 300 total points
ID: 37815744
Try the following example

b.py
import timeit

# Empty function to determine compare a function call cost.
def fn0():
    pass


def fnWhileLoop():
    x = 0
    while x < 90000000:
        x = x + 1


def fnRangeLoop():
    for x in range(1, 90000000):
        x = x + 1


def fnXrangeLoop():
    for x in xrange(1, 90000000):
        x = x + 1


print 'One time 90 000 000...'

t = timeit.Timer('fn0()', 'from __main__ import fn0')
print 'Function call: ', t.timeit(number=1), 'seconds'

t = timeit.Timer('fnWhileLoop()', 'from __main__ import fnWhileLoop')
print 'The while loop:', t.timeit(number=1), 'seconds'

t = timeit.Timer('fnRangeLoop()', 'from __main__ import fnRangeLoop')
print 'The range()   :', t.timeit(number=1), 'seconds'

t = timeit.Timer('fnXrangeLoop()', 'from __main__ import fnXrangeLoop')
print 'The xrange()  :', t.timeit(number=1), 'seconds'


# The more usual for timeit is to test shorter function many times.
# Here the "inefficiency" of the range() may be not so visible.
# The functions are redefined here (because I am lazy and did only
# copy/paste.

def fnWhileLoop():
    x = 0
    while x < 900:
        x = x + 1


def fnRangeLoop():
    for x in range(1, 900):
        x = x + 1


def fnXrangeLoop():
    for x in xrange(1, 900):
        x = x + 1

print '-' * 70  # just 70 dashes as the separator line
print '100 000 times 900...'

t = timeit.Timer('fn0()', 'from __main__ import fn0')
print 'Function call: ', t.timeit(number=100000), 'seconds'

t = timeit.Timer('fnWhileLoop()', 'from __main__ import fnWhileLoop')
print 'The while loop:', t.timeit(number=100000), 'seconds'

t = timeit.Timer('fnRangeLoop()', 'from __main__ import fnRangeLoop')
print 'The range()   :', t.timeit(number=100000), 'seconds'

t = timeit.Timer('fnXrangeLoop()', 'from __main__ import fnXrangeLoop')
print 'The xrange()  :', t.timeit(number=100000), 'seconds'

Open in new window


It prints on my console:
c:\tmp\___python\dlmille\Q_27664992>python b.py
One time 90 000 000...
Function call:  1.91995883608e-06 seconds
The while loop: 6.20929039281 seconds
The range()   : 10.3124329814 seconds
The xrange()  : 5.1691046944 seconds
----------------------------------------------------------------------
100 000 times 900...
Function call:  0.0155281470765 seconds
The while loop: 5.93527434772 seconds
The range()   : 6.03774831068 seconds
The xrange()  : 5.0528123077 seconds

Open in new window

0
 
LVL 41

Author Comment

by:dlmille
ID: 37815762
I know from VBA experience the for each is not as efficient.  Interesting xRange is faster will remember that.

Thanks for your considered response and I got the go-to emulation to work and you're right, its a bit complicated and works with negative thinking - at least the way I set it up, I had to do the negative - e.g., NOT integer to go to the floating point comparison label.

Thanks again!

Dave
0
 
LVL 41

Author Closing Comment

by:dlmille
ID: 37815767
Thanks for your thoughtful responses.

Dave
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question