[Tutor] Loops and modules

richard west richardbwest at gmail.com
Thu Dec 6 14:38:26 CET 2007


 heres a partial solution. theres no error checking on the Raw Input and you
have to type in you last number and press return, before the loop will
break, but its a start!

#!/usr/bin/python
# Filename : math_test.py

import time
import threading
class Timer(threading.Thread):
    def __init__(self, seconds):
               self.runTime = seconds
               threading.Thread.__init__(self)
    def run(self):
        global running
        time.sleep(self.runTime)
        print " "
        print "Buzzz!!! Time's up!"
        running = False
t = Timer(30)
t.start()

import random
startNum = random.choice(range(1, 9))
newNum = startNum + 7 # im assuming you want the first number the user to
type as the startnum +7,its not too clear.
score = 0
running = True

print 'Start with the number ', startNum, '.  Then continuously add 7 to
that number until the timer runs out.  You have 30 seconds.'

while running:
    print running
    answer = int(raw_input('Enter your answer: '))
    if running == True:
         if answer == newNum:
               print 'That is correct!  Keep going.'
               score = score + 5
            newNum = newNum+7
               print 'Your score is ', score
        else:
               print 'That is incorrect.  Please try again.'
print ' '
print 'you total score was ', score

On Dec 6, 2007 6:15 PM, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: Best way of learning (bhaaluu)
>   2. Re: how to accept an integer? (Alan Gauld)
>   3. Mail? What's that? (Ricardo Ar?oz)
>   4. Re: Button 1 Motion Event (Luke Paireepinart)
>   5. While Loops and Modules (earlylight publishing)
>   6. Re: Mail? What's that? (Luke Paireepinart)
>   7. Re: Best way of learning (Remco Gerlich)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Wed, 5 Dec 2007 18:50:04 -0500
> From: bhaaluu <bhaaluu at gmail.com>
> Subject: Re: [Tutor] Best way of learning
> To: andy <geek_show at dsl.pipex.com>
> Cc: tutor at python.org
> Message-ID:
>        <ea979d70712051550j3339607bib59c17889a8d44cf at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On Dec 5, 2007 5:43 PM, andy <geek_show at dsl.pipex.com> wrote:
> > Dear Pythonistas
> >
> [snip]
> >
> > So, after this long-winded introduction, I was hoping to pick the wisdom
> > of this list to get some pointers of what to do/not to do to make the
> > most effective use of the few hours I have to learn how to program using
> > Python. So, any advice for someone in their mid-40s who would like to
> > learn Python in a more methodical and effective manner?
> >
> > Thanks in anticipation.
> >
> > Andy
>
> It sounds to me like a good book or two would be just the thing for you.
> May I suggest:
> Learning Python by Mark Lutz
> and
> Programming Python Third Edition by the same author.
>
> Happy Programming!
> --
> b h a a l u u at g m a i l dot c o m
> http://www.geocities.com/ek.bhaaluu/python/index.html
>
>
> ------------------------------
>
> Message: 2
> Date: Wed, 5 Dec 2007 23:51:59 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] how to accept an integer?
> To: tutor at python.org
> Message-ID: <fj7dj7$27h$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
> "Mahesh N" <mahesh.mach at gmail.com> wrote
>
> > More over i find python to be a little sluggish after having worked
> > with C
> > and Java.
>
> If you translate C or Java code into python you will usually
> get a less than optimal implementation. Python should be
> barely slower than Java and often faster. Compared to
> C - yes there is a slow-down.
>
> But even in C you can use tools like Psycho and Pyrex to
> speed up critical sections to near C speeds if the problem fits.
> Or rewrite the critical section in C and wrap it as a module
> using SWIG. Thats how most of the performance ritical modules
> in the library are written. Where the major bottleneck is I/O
> work like database disk access or GUI or network sockets
> then you should find Python fast enough.
>
> > can someone temme where python is most applicable?
> > server side scripting? am i guessing it right?
>
> Python has been used in almost every form of programming
> from image processing and database manipulation to games
> programming and web server development. Do a search on
> Source Forge for projects using Python for an example of
> the variety.
>
> I'd avoid operating systems, device drivers and hard real-time
> applications though.
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> Message: 3
> Date: Wed, 05 Dec 2007 23:09:05 -0300
> From: Ricardo Ar?oz <ricaraoz at gmail.com>
> Subject: [Tutor] Mail? What's that?
> To: tutor at python.org
> Message-ID: <475759C1.4010507 at bigfoot.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> So I eventually got to sending mail with python.
> Some articles, trying and google led me to this script:
>
> import smtplib
> import time
>
> date = time.ctime(time.time( ))
> >From = 'mymail at gmail.com'
> To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
> Subj = 'Hi'
> text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
>                         % (From, ';'.join(To), date, Subj))
>
> s = smtplib.SMTP('smtp.gmail.com')
> s.set_debuglevel(1)
> s.ehlo()
> s.starttls()
> s.ehlo()
> s.login('foo', 'bar')
> s.sendmail(From, To, text)
> s.close()
>
>
> So, if there's someone who really knows this stuff in the neighborhood
> I'd like to ask a couple of questions.
> What is ehlo and why do I have to call it twice? And set_debuglevel?
> If I where to connect through other smtp server the sequence would be
> the exactly the same, say yahoo or hotmail?
> Are From: To: Date: and Subject: mandatory in the contents of the
> email(text)?  Do I have to put "real" address in  From when calling
> sendmail()? And in the contents?
> Ok, if someone can answer these I'll be grateful.
>
> TIA
>
> Ricardo
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Wed, 05 Dec 2007 23:38:39 -0600
> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] Button 1 Motion Event
> To: Johnston Jiaa <oclbdk at gmail.com>, Tutor <tutor at python.org>
> Message-ID: <47578ADF.40108 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Johnston Jiaa wrote:
> >
> >> Just don't distinguish between quick and slow drags.  Just keep a
> >> temporary variable that has the previous mouse position, and draw
> >> ovals from there to the current mouse position every time your
> >> function is called.
> >
> > I now have the variable with the previous mouse position.  How would I
> > draw ovals from the current mouse position to that previous mouse
> > position?  I tried reasoning it out with a for-loop, but I couldn't
> > figure out how to do it.
> Well, try reasoning it out with mathematics.
> Suppose we have the points (0,0) and (100,100).
> What's the slope between these two points?
> well, delta-Y is 100 and delta-X is 100, and 100/100 == 1.
> This is also the same as 1/1.
> Therefore, for every new point we want to get, we'll add 1 to the x
> value and 1 to the y value.
>
> Now assume we have the points (23, 45) and (45, 80).
> This slope would be:
> 80 - 45
> ---------
> 45 - 23
> or  35 / 22.
> So as you can see, the number on the top is larger than the number on
> the bottom, so our Y-value is increasing more quickly.
> But it doesn't really matter which value is bigger, the numerator or the
> denominator.
> All we care about is the slope.  Because slope tells us: this is the
> change in Y for every change in X.
> The reason slope tells us this is because slope is the ratio between the
> change in Y between our 2 points
> and the change in X between our 2 points.
> Because it's a ratio, it can be applied to any measure, even to
> deltaX=1, which gives us what deltaY is.
> Since we don't care about any X-coordinates between integers, we don't
> care about any other deltaX measurement.
>
> So you'd do something like this:
> x = 23.0 # our first points
> y = 45.0 # they're float so we can add partial amounts to them.
> slope = 35/22.0 # this is float to force float division.
> for deltax in range(23, 45):
>    x += deltax
>    y += slope
>
> So in this case, each time through the loop, X will move 1 over, and Y
> will move slightly more than 1 up.
>
> This still has a problem if the slope is very great in the Y-direction.
> Given the case of the points (0,0) and (1,100),
> we get a slope of 100.  Thus, we will draw points at 0,0 and at 1,100
> and none in-between,
> when realistically we'd like at least a vertical line between them, or
> preferably one that shifts one pixel over halfway-up.
>
> Note that the poitns (0,0) and (100, 1) would not create a problem.
> This is because our delta-x is changing at a set rate,
> and our deltay is a smaller number.  It would work in this case.
>
> What's creating the problem is that our slope is greater than 1, and
> we're using delta-x as a fixed amount.
> If we add the condition that we affix delta-x to the value 1 for slopes
> less than 1, and delta-y to 1 when slopes are greater than 1,
> then everything should work out perfectly.  The case of slope == 1 will
> be correctly handled in either case, just make sure to include it in one
> of them.
>
> Thusly, our code would look something like this:
>
> point1x, point1y = raw_input("please input the first pair of coordinates
> separated by a space: ").split(' ')
> point2x, point2y = raw_input("please input the second pair of
> coordinates separated by a space: ").split(' ')
>
> slope = (point2y - point1y) / (float(point2x - point1x))
> if slope > 1:
>    deltax = 1 / slope # i assume we invert slope here?
>    deltay = 1
> else:
>    deltax = 1
>    deltay = slope
>
> currentx = float(point1x)
> currenty = float(point1y)
> for x in range(max((point2y - point1y), (point2x - point1x)) ):
>    #we choose our range as the larger of the two lengths.
>    #thus if delta-x is only 1px and delta-y is 100px, we'll
>    #still draw all those points in between.
>
>    # ..........
>    #  draw the currentx, currenty point here
>    # .........
>    currentx += deltax
>    currenty += deltay
>
> # and draw the point one more time here, to get your ending point.
>
>
>
>
> Note that I don't profess that either my code or my math is correct; I
> didn't test any of this, it's more to give you an idea of how to
> approach Computer Science problems.
>
> >
> > Also, I need to be able to save the canvas drawing.  Would it be
> > possible to write some sort of data to a file that could be used to
> > load the previously saved drawing back onto the canvas?
> You can just keep a cache of all points and redraw them on load, or you
> can dump it out to an image file.  I believe TKInter supports that, but
> I haven't used that library in a long time.
>
> Again, _please reply on-list_ unless you want a discussion to be
> private, in which case specify in the e-mail so we know it wasn't an
> accident.
> -Luke
>
>
>
> ------------------------------
>
> Message: 5
> Date: Wed, 5 Dec 2007 21:44:09 -0800 (PST)
> From: earlylight publishing <earlylightpublishing at yahoo.com>
> Subject: [Tutor] While Loops and Modules
> To: tutor at python.org
> Message-ID: <555764.37796.qm at web45105.mail.sp1.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello again to all the wonderfully helpful folks on this list.  Today I
> did my Google homework and I found this neat bit of code for a countdown
> timer.
>
>  import time
> import threading
> class Timer(threading.Thread):
>    def __init__(self, seconds):
>        self.runTime = seconds
>        threading.Thread.__init__(self)
>    def run(self):
>        time.sleep(self.runTime)
>        print "Buzzz!!! Time's up!"
>  t = Timer(30)
> t.start()
>
>  I don't understand large chunks of it (don't know what threading, self,
> or __init__ mean) but that's not important at the moment.  It works and I
> will learn the vocab eventually.
>
>  I also wrote this bit of code for a math challenge which comes in the
> next part of my game.
>
>  import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7
> score = 0
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> answer = int(raw_input('Enter your answer: '))
>  if newNum == answer:
>    print 'That is correct!  Keep going.'
>    score = score + 5
>    print 'Your score is ', score
> else:
>    print 'That is incorrect.  Please try again.'
>
>  I understand this part just fine 'cause I actually wrote it myself.
>
>  What I need to do now is put these two parts together so that the player
> will keep adding 7 to the starting number for 30 seconds then the loop
> breaks.  I know I need a loop of some sort and I'm guessing it's a 'while'
> sort of thing.  I couldn't find what I was looking for when I Googled.  I'm
> not even sure I knew the right search terms.  Does anyone know how I'd
> combine these two modules to make it work?
>
>
> ---------------------------------
> Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it
> now.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071205/e265b7d9/attachment-0001.htm
>
> ------------------------------
>
> Message: 6
> Date: Wed, 05 Dec 2007 23:47:32 -0600
> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] Mail? What's that?
> To: raraoz at bigfoot.com
> Cc: tutor at python.org
> Message-ID: <47578CF4.4040609 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Ricardo Ar?oz wrote:
> > So I eventually got to sending mail with python.
> > Some articles, trying and google led me to this script:
> >
> > import smtplib
> > import time
> >
> > date = time.ctime(time.time( ))
> > >From = 'mymail at gmail.com'
> > To = ['othermail at hotmail.com', 'YetOtherMail at yahoo.com']
> > Subj = 'Hi'
> > text = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n'
> >                          % (From, ';'.join(To), date, Subj))
> >
> > s = smtplib.SMTP('smtp.gmail.com')
> > s.set_debuglevel(1)
> > s.ehlo()
> > s.starttls()
> > s.ehlo()
> > s.login('foo', 'bar')
> > s.sendmail(From, To, text)
> > s.close()
> >
> >
> > So, if there's someone who really knows this stuff in the neighborhood
> > I'd like to ask a couple of questions.
> > What is ehlo and why do I have to call it twice? And set_debuglevel?
> > If I where to connect through other smtp server the sequence would be
> > the exactly the same, say yahoo or hotmail?
> > Are From: To: Date: and Subject: mandatory in the contents of the
> > email(text)?  Do I have to put "real" address in  From when calling
> > sendmail()? And in the contents?
> > Ok, if someone can answer these I'll be grateful.
> >
> > TIA
> >
> > Ricardo
> >
> Ricardo -
> I say this in the nicest way possible, but did you RTFM? :)
> Python has built-in help support on modules.
> You should start there, do some Googling, and if you're stumped, get
> some help.  Not for any other reason than it'll probably get you 1) more
> experience at navigating the docs, and 2) a quicker, probably more
> detailed response.
>
> So using Help, we get:
>
>
>  >>> import smtplib
>  >>> help(smtplib)
> Help on module smtplib:
>
> NAME
>    smtplib - SMTP/ESMTP client class.
>
> FILE
>    c:\python24\lib\smtplib.py
>
> [snip 10 pages of documentation]
>
>
>  >>> help(smtplib.SMTP.set_debuglevel)
> Help on method set_debuglevel in module smtplib:
>
> set_debuglevel(self, debuglevel) unbound smtplib.SMTP method
>    Set the debug output level.
>
>    A non-false value results in debug messages for connection and for all
>    messages sent to and received from the server.
>
>  >>> help(smtplib.SMTP.ehlo)
> Help on method ehlo in module smtplib:
>
> ehlo(self, name='') unbound smtplib.SMTP method
>    SMTP 'ehlo' command.
>    Hostname to send for this command defaults to the FQDN of the local
>    host.
>
>  >>> help(smtplib.SMTP.sendmail)
> Help on method sendmail in module smtplib:
>
> sendmail(self, from_addr, to_addrs, msg, mail_options=[],
> rcpt_options=[]) unbound smtplib.SMTP method
>    This command performs an entire mail transaction.
>
>    The arguments are:
>        - from_addr    : The address sending this mail.
>        - to_addrs     : A list of addresses to send this mail to.  A bare
>                         string will be treated as a list with 1 address.
>        - msg          : The message to send.
>        - mail_options : List of ESMTP options (such as 8bitmime) for the
>                         mail command.
>        - rcpt_options : List of ESMTP options (such as DSN commands) for
>                         all the rcpt commands.
>
>    If there has been no previous EHLO or HELO command this session, this
>    method tries ESMTP EHLO first.  If the server does ESMTP, message size
>    and each of the specified options will be passed to it.  If EHLO
>    fails, HELO will be tried and ESMTP options suppressed.
>
>    This method will return normally if the mail is accepted for at least
>    one recipient.  It returns a dictionary, with one entry for each
>    recipient that was refused.  Each entry contains a tuple of the SMTP
>    error code and the accompanying error message sent by the server.
>
>    This method may raise the following exceptions:
>
>     SMTPHeloError          The server didn't reply properly to
>                            the helo greeting.
>     SMTPRecipientsRefused  The server rejected ALL recipients
>                            (no mail was sent).
>     SMTPSenderRefused      The server didn't accept the from_addr.
>     SMTPDataError          The server replied with an unexpected
>                            error code (other than a refusal of
>                            a recipient).
>
>    Note: the connection will be open even after an exception is raised.
>
>    Example:
>
>     >>> import smtplib
>     >>> s=smtplib.SMTP("localhost")
>     >>>
> tolist=["one at one.org","two at two.org","three at three.org","four at four.org"]
>     >>> msg = '''\
>     ... From: Me at my.org
>     ... Subject: testin'...
>     ...
>     ... This is a test '''
>     >>> s.sendmail("me at my.org",tolist,msg)
>     { "three at three.org" : ( 550 ,"User unknown" ) }
>     >>> s.quit()
>
>    In the above example, the message was accepted for delivery to three
>    of the four addresses, and one was rejected, with the error code
>    550.  If all addresses are accepted, then the method will return an
>    empty dictionary.
>
>  >>>
>
>
>
>
> So mess around in the built-in docs, then check python.org's docs, and
> let us know what you find :)
> Also, try experimenting! pass it stuff that you don't think will work
> just to see if maybe it does :D
> -Luke
>
>
> ------------------------------
>
> Message: 7
> Date: Thu, 6 Dec 2007 10:15:02 +0100
> From: "Remco Gerlich" <remco at gerlich.nl>
> Subject: Re: [Tutor] Best way of learning
> To: andy <geek_show at dsl.pipex.com>
> Cc: tutor at python.org
> Message-ID:
>        <7ae3ca10712060115r34a7fa33q32a5902fdd0af1b at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> On Dec 5, 2007 11:43 PM, andy <geek_show at dsl.pipex.com> wrote:
>
> > So, after this long-winded introduction, I was hoping to pick the wisdom
> > of this list to get some pointers of what to do/not to do to make the
> > most effective use of the few hours I have to learn how to program using
> > Python. So, any advice for someone in their mid-40s who would like to
> > learn Python in a more methodical and effective manner?
> >
>
> In my opinion, the best way to learn _anything_ is to try to do it, and
> then
> look around for tips every now and then in the mean time. You'll connect
> much more easily with the information when it's something you've recently
> struggled with. And practice is the most important part of any learning
> anyway.
>
> So, what do you want to do with Python? Any other hobbies you can connect
> it
> with? Perhaps ideas for a dynamic web site or something?
>
> In my experience, learning something just for abstract knowledge can be
> fun
> for a while, but it's hard to stay committed. And there's nothing wrong
> with
> that, there's only so many hours in a day, and the things you actually use
> in life should probably take precedence :-)
>
> So if you've written small tools, feel like expanding them? Used modules
> in
> them that you don't entirely understand yet, perhaps dive into their docs?
>
> Perhaps the Python Challenge ( http://www.pythonchallenge.com/ ) is
> something for you? It's at least sideways a little into the hacking
> spirit,
> it's fun, and it's a tour of what Python can do - but you'll have to find
> the way yourself :-)
>
> Remco Gerlich
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20071206/8eafc022/attachment.htm
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 46, Issue 15
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071206/e6fff891/attachment-0001.htm 


More information about the Tutor mailing list