Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 533
  • Last Modified:

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
0
dlmille
Asked:
dlmille
  • 4
  • 4
4 Solutions
 
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.
0
 
Hamed ZaghaghiProgrammerCommented:
This can help: goto
but I'm agree with pepr
0
 
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
0
A proven path to a career in data science

At Springboard, we know how to get you a job in data science. With Springboard’s Data Science Career Track, you’ll master data science  with a curriculum built by industry experts. You’ll work on real projects, and get 1-on-1 mentorship from a data scientist.

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

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

Dave
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now