Python 2.5 Hello Word - how to use imports for goto

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
LVL 42
dlmilleAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hamed ZaghaghiMachine Learning EngineerCommented:
This can help: goto
but I'm agree with pepr
dlmilleAuthor Commented:
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
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

peprCommented:
:) The goto module is great!  Actually, it is even more complex than the above Python FAQ. (Don't use it for anything serious!)
dlmilleAuthor Commented:
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
peprCommented:
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.
peprCommented:
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

dlmilleAuthor Commented:
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
dlmilleAuthor Commented:
Thanks for your thoughtful responses.

Dave
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.