Solved

Python 2.5 Hello Word - how to use imports for goto

Posted on 2012-04-06
9
501 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
Comment Utility
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
Comment Utility
This can help: goto
but I'm agree with pepr
0
 
LVL 41

Author Comment

by:dlmille
Comment Utility
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
 
LVL 28

Expert Comment

by:pepr
Comment Utility
:) The goto module is great!  Actually, it is even more complex than the above Python FAQ. (Don't use it for anything serious!)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 41

Author Comment

by:dlmille
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks for your thoughtful responses.

Dave
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Pyhon with Oracle encoding issue 8 74
looping 11 27
Use of python .format to prefill  form. 5 55
Merge lists using index in Python 1 61
The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
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…

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now