Re: [Tutor] decision loops

2015-02-01 Thread Steven D'Aprano
Hello Daniel, and welcome! 

On Sat, Jan 31, 2015 at 08:54:48PM -0500, Daniel M wrote:

 Hello. I'm a complete beginner and I’m trying to write a very basic script
 to convert temperatures, just for some practice. I have that part down, but
 I can’t figure out how to make the script switch between the two. What I
 would like it to do is let the user go back to the “What do you wish to
 convert?” part when a character is entered instead of a number for
 “temperature?”. I tried using
 
 elif m == *char*
 
 print (*What do you wish to convert to?*)
 
 temp = raw_input(* *)

Why are there asterisks around parts of your code? That's a syntax 
error in Python. I'm guessing that you didn't type them yourself, and 
that your email program is doing it. You should set your email 
program to only send plain text, not Rich Text or formatted text or 
HTML or whatever silly thing it is trying to do.


 but it seems useless regardless of where I put it. It gives me the error “
 return eval(raw_input(prompt))

In the code you show below, there is no mention of eval. So that is your 
first mistake: whether you intended to or not (I'm pretty sure it wasn't 
deliberate!) you are telling us falsehoods. The code you say you are 
running is not the code you are actually running. How can we tell what 
you are doing wrong when we cannot see what you are doing?

Mistake number two is using eval. As a beginner, there are three rules 
you should remember about eval:

(1) If you think you might need to use eval, you don't.
(2) If you are positive that you really do need to use eval, 
you probably don't.
(3) For experts only -- if you are sure that you need to use 
eval, you might.


The problems with eval are:

- its slow
- its tricky to use right except for the simplest cases
- it can be dangerous and introduce serious security holes 
  in your code if you aren't careful


   File string, line 1, in module
 
 NameError: name 't' is not defined” when I enter a character.

Mistake number three: I'm guessing that you didn't enter any old 
character. I'm guessing you entered 't' rather than 's' or '3' or '.' or 
some other character. Your mistake is to make us guess: when asking for 
help, you should tell us what you did specifically, not vaguely.

In this case, I think I can reproduce your problem:

py eval(raw_input(Enter a character: ))
Enter a character: t
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1, in module
NameError: name 't' is not defined


I don't get that error from any random character, only from t. If I type 
a different character, I get a different error. Why? Because of eval. 
You're telling Python to evaluate what you typed as if it were code: 

py eval(raw_input(Enter a character: ))
Enter a character: len([1, 2, 3]) + 1000
1003

You don't need eval here. It does nothing useful. What you want is 
simply raw_input(prompt).

Hope that helps.

-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] decision loops

2015-02-01 Thread Daniel M
Hello. I'm a complete beginner and I’m trying to write a very basic script
to convert temperatures, just for some practice. I have that part down, but
I can’t figure out how to make the script switch between the two. What I
would like it to do is let the user go back to the “What do you wish to
convert?” part when a character is entered instead of a number for
“temperature?”. I tried using

elif m == *char*

print (*What do you wish to convert to?*)

temp = raw_input(* *)



but it seems useless regardless of where I put it. It gives me the error “
return eval(raw_input(prompt))

  File string, line 1, in module

NameError: name 't' is not defined” when I enter a character. I’m sure I’m
missing something very obvious but I can’t seem to figure it out. Where am
I going wrong?







def *ftoc*(x): #Fahrenheit to Celsius

x == float

y = x-32.0

z = y * 5.0

return z //9.0



def *ctof*(x):  #Celsius to Fahrenheit

x == float

y = x * 9.0

z = y // 5.0

return z + 32.0



print (*What do you wish to convert to?*)

temp = raw_input(* *)



while  temp == *c* or temp == *f* and not temp == *q*:

if temp == *c*:

m = float(input(*temperature?*))

print ftoc(m)

print *Celcius*

elif temp == *f*:

m = float(input(*temperature?*))

print ctof(m)

print (*Farenheit*)

elif temp == *q*:

break
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decision loops

2015-02-01 Thread Alan Gauld

On 01/02/15 01:54, Daniel M wrote:


I can’t figure out how to make the script switch between the two. What I
would like it to do is let the user go back to the “What do you wish to
convert?” part when a character is entered instead of a number for
“temperature?”. I tried using


That's quite a complex task you've set yourself. You need to 
differentiate numbers and characters even though you read

them all as characters from the users. It might be simpler
just to keep the numeric and character processing separate
for now. And maybe for good.

Also your subject says 'decision loops'
Those are two completely separate things.

decisions are made using if/elif/else constructs
loops are repetitions involving 'for' or 'while'
constructs (and a few more advamced ones later)

You probably need both to solve your problem but do not confuse
or merge the two ideas in your mind. At this stage we appear to only be 
dealing with decisions. The loops can wait till later.



elif m == *char*
 print (*What do you wish to convert to?*)
 temp = raw_input(* *)


The asterisks don't make sense, I'm guessing your mail program put them 
in because you made it bold or some-such? Please always use plain text 
when sending code.


However, we can't really make much sense of it even without asterisks 
because we have no context. We don't know what 'm' is, where it comes 
from etc.
Also m == char only makes sense if you have defined a variable called 
char somewhere, again we can't see it. Or are you simply trying to 
explain that you want to test m to see if it is a character?

Its not clear. Don't make us guess.


but it seems useless regardless of where I put it. It gives me the error “
return eval(raw_input(prompt))


And that line doesn't seem to appear in your code anywhere?
And its only a bit of an error message, please always send us
the whole error because its full of useful information.



   File string, line 1, in module

NameError: name 't' is not defined” when I enter a character.


This suggests that you passed a 't' to eval. The 't' must have come from 
the raw_input() but again you didn't tell us that we have

to guess. I assume you get a slightly differnt error if you enter,
say, a 'v' or a 'w'?


missing something very obvious but I can’t seem to figure it out.


Probably but you aren't giving us enough specific detail to be
able to help you reliably.



def *ftoc*(x): #Fahrenheit to Celsius
 x == float
 y = x-32.0
 z = y * 5.0
 return z //9.0


x = float doesn't do anything useful here. It assigns a
new name (x) to the float type convertion function.
I'm guessing(again) that what you really meant was

x = float(x)

to force x to be a floating point number?

Also // produces integer division. I'm pretty sure
you want regular float division z/9.0


def *ctof*(x):  #Celsius to Fahrenheit
 x == float
 y = x * 9.0
 z = y // 5.0
 return z + 32.0


Pretty much the same comments as above


print (*What do you wish to convert to?*)
temp = raw_input(* *)



while  temp == *c* or temp == *f* and not temp == *q*:
 if temp == *c*:
 m = float(input(*temperature?*))
 print ftoc(m)
 print *Celcius*
 elif temp == *f*:
 m = float(input(*temperature?*))
 print ctof(m)
 print (*Farenheit*)
 elif temp == *q*:
 break


OK, Now we see where 'm' fits in, although your char test above is missing.

Also we see you using input() instead of raw_input()
That's nearly always a mistake. Its better to use raw_input() and then 
explicitly convert to the type you want(which you do here anyway)


So use:

  m = float(raw_input(temperature?))

Finally you probably want the unit selection inside the while loop
so try something like this skeleton code:

while  True:
 temp = raw_input(What do you wish to convert to?)
 if temp == 'q': break
 if temp == c:
  m = float(raw_input(temperature?))
  print ftoc(m)
  print Celcius
 elif temp == f:
  m = float(raw_input(temperature?))
  print ctof(m)
  print (Farenheit)


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] While loops

2012-07-07 Thread myles broomes

I am currently coding a 'text-based adventure game', and im having a bit of 
trouble with while loops. Here is my code so far: #Text-based Adventure RPG
#The player travels through different towns and dungeons
#The overall goal of the game is simple; the player must make it to the final 
town,
#Battling various monsters and overcoming several challenges along the 
wayimport timeplayer_name = None
player_invent = [30]
emb_town_visit=None
YES='yes'
NO='no'
user_choice=None
plyr_location='Embark'
shopkeep_mny=100
shopkeep_invent=['Bronze Sword (10)','Steel Sword (100)','Rounded Shield 
(10)','Kite Shield (50)','Medicine (5)','Mana Potion (5)'] class 
Main_char(object):
A class for the main character object.
def __init__(self,name,invent,level=1,health=30,mana=15):
self.name=name
self.level=level
self.invent=invent
self.hp=health
self.mana=mana
print(\nYour journey begins here in Embark town,+self.name)   
 def __str__(self):
print(\nName: ,self.name, \nLevel: ,self.level, \nYour 
inventory: ,self.invent)def town_chcklist(self):
A checklist showing a list of the towns the player has 
already visited.
self.checklist=[]
if town1==YES:
self.checklist.append(town1) def use_item(item):
Allows the player to use an item in their inventory.
if item in ('Medicine','Mana Potion'):
Hero.invent.delete(item)
if item=='Medicine':
Hero.hp+20
elif item=='Mana Potion':
Hero.mana+10class Shopkeep(object):
A blueprint for the shopkeeper objects.
def __init__(self,inv,money):
self.inv=inv
self.money=moneydef __str__(self):
print(Shopkeeper: Here are my wares: \n\n,self.inv+. \nI 
currently have,self.money,gold.) #Create the towns/ dungeons/ areas in 
different functionsdef Embark():
The town in which the player begins there journey.
if emb_town_visit==None:
print(Welcome to Embark Town,player_name+!)while 
True:
print(\n,hero)
print(
\n\t\tPress '1' to exit the town...
\n\t\tPress '2' to enter the local shop...)
user_choice=input('What would you like to do?: ')
if user_choice=='1':
shop()
continue
elif user_choice=='2':
if emb_town_visit==None:
print(\n\t\t\tAs you leave your home of Embark 
Town, you look back with a smile, then proceed North.)
break
else:
print(\n\t\t\tThat is not a valid choice...)
continue
 
#The player has visited Embark Town
if emb_town_visit==None:
emb_town_visit=YES#Exit the function and change the 
players location variable
return 'Left Embark Town',emb_town_visit def shop():
A generic shop that is placed in each town.
while True:
print(
\nWhat would you like to do?
\nPress '1' to buy an item...
\n...Press '2' to exit the shop...
\n...Or press '3' to ask about the town...)
user_choice=input()
if user_choice=='1':
print(Shopkeeper: Goodbye.)
break
elif user_choice=='2':
print(emb_shopkeep)
user_choice=None
print(Enter the name of the item you would like to 
purchase.)
user_choice=title(input())
for item in emb_shopkeep.inv:
if user_choice in emb_shopkeep.inv:
message=handle_pur(user_choice)
print(message)
emb_shopkeep.inv.delete(user_choice)
else:
print(\n\t\t\tThat is not a valid 
choice!)def handle_pur(item):
Handles purhchases made by the player in the shop.
if item=='Bronze Sword':
if Hero.invent[0] = 10:
Hero.invent[0]-10
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent[0]  10:
msg='You cannot afford that item.'
elif item=='Steel Sword':
if Hero.invent[0] = 100:
Hero.invent[0] - 100
Hero.invent.append(item)
msg='You now own a',item

Re: [Tutor] While loops

2012-07-07 Thread Emile van Sebille

On 7/7/2012 5:57 AM myles broomes said...


I am currently coding a 'text-based adventure game', and im having a bit
of trouble with while loops. Here is my code so far:


Please paste in the traceback you're getting, and please set your mail 
client program for plain text when posting.  What I see here has the 
indentation stripped out of your script so that before I can even test 
your code I'll have to guess at how you have it indented, and I'm more 
likely than you to get it right and may inadvertently fix your bug and 
never know it even before getting a chance to see the bug.


Emile




#Text-based Adventure RPG
#The player travels through different towns and dungeons
#The overall goal of the game is simple; the player must make it to the
final town,
#Battling various monsters and overcoming several challenges along the way
import time
player_name = None
player_invent = [30]
emb_town_visit=None
YES='yes'
NO='no'
user_choice=None
plyr_location='Embark'
shopkeep_mny=100
shopkeep_invent=['Bronze Sword (10)','Steel Sword (100)','Rounded Shield
(10)','Kite Shield (50)','Medicine (5)','Mana Potion (5)']

class Main_char(object):
A class for the main character object.
def __init__(self,name,invent,level=1,health=30,mana=15):
self.name=name
self.level=level
self.invent=invent
self.hp=health
self.mana=mana
print(\nYour journey begins here in Embark town,+self.name)
def __str__(self):
print(\nName: ,self.name, \nLevel: ,self.level, \nYour inventory:
,self.invent)
def town_chcklist(self):
A checklist showing a list of the towns the player has already
visited.
self.checklist=[]
if town1==YES:
self.checklist.append(town1)

def use_item(item):
Allows the player to use an item in their inventory.
if item in ('Medicine','Mana Potion'):
Hero.invent.delete(item)
if item=='Medicine':
Hero.hp+20
elif item=='Mana Potion':
Hero.mana+10
class Shopkeep(object):
A blueprint for the shopkeeper objects.
def __init__(self,inv,money):
self.inv=inv
self.money=money
def __str__(self):
print(Shopkeeper: Here are my wares: \n\n,self.inv+. \nI currently
have,self.money,gold.)

#Create the towns/ dungeons/ areas in different functions
def Embark():
The town in which the player begins there journey.
if emb_town_visit==None:
print(Welcome to Embark Town,player_name+!)
while True:
print(\n,hero)
print(
\n\t\tPress '1' to exit the town...
\n\t\tPress '2' to enter the local shop...)
user_choice=input('What would you like to do?: ')
if user_choice=='1':
shop()
continue
elif user_choice=='2':
if emb_town_visit==None:
print(\n\t\t\tAs you leave your home of Embark Town, you look back with
a smile, then proceed North.)
break
else:
print(\n\t\t\tThat is not a valid choice...)
continue

#The player has visited Embark Town
if emb_town_visit==None:
emb_town_visit=YES
#Exit the function and change the players location variable
return 'Left Embark Town',emb_town_visit

def shop():
A generic shop that is placed in each town.
while True:
print(
\nWhat would you like to do?
\nPress '1' to buy an item...
\n...Press '2' to exit the shop...
\n...Or press '3' to ask about the town...)
user_choice=input()
if user_choice=='1':
print(Shopkeeper: Goodbye.)
break
elif user_choice=='2':
print(emb_shopkeep)
user_choice=None
print(Enter the name of the item you would like to purchase.)
user_choice=title(input())
for item in emb_shopkeep.inv:
if user_choice in emb_shopkeep.inv:
message=handle_pur(user_choice)
print(message)
emb_shopkeep.inv.delete(user_choice)
else:
print(\n\t\t\tThat is not a valid choice!)
def handle_pur(item):
Handles purhchases made by the player in the shop.
if item=='Bronze Sword':
if Hero.invent[0] = 10:
Hero.invent[0]-10
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent[0]  10:
msg='You cannot afford that item.'
elif item=='Steel Sword':
if Hero.invent[0] = 100:
Hero.invent[0] - 100
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent[0]  100:
msg='You cannot afford that item.'
elif item =='Rounded Shield':
if Hero.invent[0] = 10:
Hero.invent[0] - 10
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent  10:
msg='You cannot afford that item.'
elif item=='Kite Shield':
if Hero.invent[0] = 50:
Hero.invent[0] - 50
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent  50:
msg='You cannot afford that item.'
elif item=='Medicine':
if Hero.invent[0] = 5:
Hero.invent[0] - 5
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent[0]  5:
msg='You cannot afford that item.'
elif item=='Mana Potion':
if Hero.invent[0] = 5:
Hero.invent[0] - 5
Hero.invent.append(item)
msg='You now own a',item
elif Hero.invent[0]  5:
msg='You cannot afford that item.'
#Informs the program of which message to tell the player
return msg

emb_shopkeep=Shopkeep(shopkeep_invent,shopkeep_mny)

#Player creation loop
while True:
print(
\nValiant hero, your quest begins here in Embark Town.,
time.sleep(200),
\nWhere you will go is up to you...,
time.sleep(200),
\nHow your adventure will pan out is up to you...,

Re: [Tutor] While loops

2012-07-07 Thread Alan Gauld

On 07/07/12 13:57, myles broomes wrote:


I am currently coding a 'text-based adventure game', and im having a bit
of trouble with while loops. Here is my code so far:


What kind of trouble? You have lots of while loops, which loop?
And do you get an error message? If so please post it - all of it!

And looking through the code I see lots of potential problems, I have 
highlighted a few below...




class Main_char(object):
 def __init__(self,name,invent,level=1,health=30,mana=15):
 def __str__(self):
 def town_chcklist(self):
 self.checklist=[]
 if town1==YES:
 self.checklist.append(town1)


This method always resets the list to empty and then appends town1.
You should move the initialisation of the list into __init__.
But I see no variable defined anywhere called 'town1' so you would
get an error... Fortunately you don't seem to call this method
so no error is ever produced...


def use_item(item):
 Allows the player to use an item in their inventory.
 if item in ('Medicine','Mana Potion'):
 Hero.invent.delete(item)
 if item=='Medicine':
 Hero.hp+20


Here you add 20 to the value of Hero.hp but then throw thecresult away.
I suspect you mean:

Hero.hp += 20


 elif item=='Mana Potion':
 Hero.mana+10


What is Hero.mana? It does not appear in the MainChar class definition?
And as above I suspect you mean += 10?


class Shopkeep(object):
 def __init__(self,inv,money):
 self.inv=inv
 self.money=money
 def __str__(self):
 print(Shopkeeper: Here are my wares: \n\n,self.inv+.
\nI currently have,self.money,gold.)

#Create the towns/ dungeons/ areas in different functions
def Embark():


Its usual practice to keep names startingt with a captial letter for 
Clas names. It gets confusing for the reader(whio might be you!)  otherwise.




 The town in which the player begins there journey.
 if emb_town_visit==None:
 print(Welcome to Embark Town,player_name+!)
 while True:
 print(\n,hero)
 print(
 \n\t\tPress '1' to exit the town...
 \n\t\tPress '2' to enter the local shop...)
 user_choice=input('What would you like to do?: ')
 if user_choice=='1':
 shop()
 continue


You don't need 'continue' here because the loop drops out here anyway.
But it won't do any harm.


 elif user_choice=='2':
 if emb_town_visit==None:
 print(\n\t\t\tAs you leave your home
of Embark Town, you look back with a smile, then proceed North.)
 break
 else:
 print(\n\t\t\tThat is not a valid choice...)
 continue


same here. You only need continue if you are jumping out of the code 
block back to the start of the loop. It should be a relatively rare 
event in well structured code!




 #The player has visited Embark Town
 if emb_town_visit==None:
 emb_town_visit=YES
 #Exit the function and change the players location variable
 return 'Left Embark Town',emb_town_visit


This is broken due to some bad use of variable names.

You define emb_town_visit as a global with value None.
First time into Embark you test the global and if its set to None you 
*create a new local variable* of the same name. You then return it to 
main which sets *yet another local variable* of the same name to YES.
But this does not change the global so next time you visit Embark the 
global is still None and you go through the same routine. If you want to 
use the global value (and especially if you want to change it) you must 
specify it as global in each function . But frankly it should probably 
not be global anyhow since you want to track that per player so it 
should really be part of your character class.



def shop():
 A generic shop that is placed in each town.


In that case it should probably be a class and you create an instance in 
each town.



 while True:
 print(
 \nWhat would you like to do?
 \nPress '1' to buy an item...
 \n...Press '2' to exit the shop...
 \n...Or press '3' to ask about the town...)
 user_choice=input()
 if user_choice=='1':
 print(Shopkeeper: Goodbye.)
 break
 elif user_choice=='2':
 print(emb_shopkeep)
 user_choice=None
 print(Enter the name of the item you would
like to purchase.)
 

[Tutor] while loops

2011-12-14 Thread rog capp
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know  if the guess is to high, to low
# or right on the money

import random

print(\tWelcome to 'Guess My Number'!)
print(I'm thinking of a number between 1 and 100.)
print(Try to guess it in as few attempts as possible.\n)

# set the initial values
the_number = random.randint(1,100)
guess = int(input(Take a guess: ))
tries = 1

# Guessing loop
while  guess != the_number:

if guess  the_number:
print(Lowere...)
else:
print(Higher...)

guess = int(input(Take a guess: ))
tries += 1

print(good job)

input(\n\nPress the enter key to exit.)



This is a program from Python for the absulute beginner(which I am).
End of the chapter is a challenge that asks me to limit the number of
guesses the player gets.
If he/she fails to guess the number after a certain number of attempts
then it displays a message
about his failure.It needs to be a while loop cause it the topic I'm
at.Can anyone give me some help
on where to put the loop.When i put it in with the if
guessthe_number loop, the program either
prints higher or lower continuously(continuous loop I imagine) or it
gives me the answer whether its
right or wrong after a couple guesses.Any help will be appreciated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2011-12-14 Thread Steven D'Aprano

rog capp wrote:
[...]

# Guessing loop
while  guess != the_number:
if guess  the_number:
print(Lowere...)
else:
print(Higher...)
guess = int(input(Take a guess: ))
tries += 1

print(good job)
input(\n\nPress the enter key to exit.)



This is a program from Python for the absulute beginner(which I am).
End of the chapter is a challenge that asks me to limit the number of
guesses the player gets.
If he/she fails to guess the number after a certain number of attempts
then it displays a message
about his failure.It needs to be a while loop cause it the topic I'm
at.Can anyone give me some help


You need a counter to count how many guesses are made. You already have a 
variable counting the number of tries, so you are half-way there.


The loop condition currently is:

while guess != the_number

or in English:

while the guess is not equal to the number: loop

Still in English, you want to change the condition to:

while the guess is not equal to the number and the number of
 tries is less than the maximum number of tries: loop

Translate that loop condition from English to Python, and you've got it.

Then, once you have the loop fixed, the final change needed is to change the 
message printed at the end, outside the loop. Currently it unconditionally 
prints good job. You need to change that to only print good job if the 
guess is equal to the number, otherwise print something else.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2011-12-14 Thread Dave Angel

On 12/14/2011 05:41 PM, rog capp wrote:

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know  if the guess is to high, to low
# or right on the money

import random

print(\tWelcome to 'Guess My Number'!)
print(I'm thinking of a number between 1 and 100.)
print(Try to guess it in as few attempts as possible.\n)

# set the initial values
the_number = random.randint(1,100)
guess = int(input(Take a guess: ))
tries = 1

# Guessing loop
while  guess != the_number:

 if guess  the_number:
 print(Lowere...)
 else:
 print(Higher...)

 guess = int(input(Take a guess: ))
 tries += 1

print(good job)

input(\n\nPress the enter key to exit.)



This is a program from Python for the absulute beginner(which I am).
End of the chapter is a challenge that asks me to limit the number of
guesses the player gets.
If he/she fails to guess the number after a certain number of attempts
then it displays a message
about his failure.It needs to be a while loop cause it the topic I'm
at.Can anyone give me some help
on where to put the loop.When i put it in with the if
guessthe_number loop, the program either
prints higher or lower continuously(continuous loop I imagine) or it
gives me the answer whether its
right or wrong after a couple guesses.Any help will be appreciated.
_

You already have a while-loop.  So add another condition to it:
   while guess != answer   and tries 10:

then outside the loop, write an if-test conditional on whether guess == 
number


If so, tell him good job, if not, tell him he took too many tries.

--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2011-12-14 Thread Alan Gauld

On 14/12/11 22:41, rog capp wrote:


# Guessing loop
while  guess != the_number:

 if guess  the_number:
 else:

 guess = int(input(Take a guess: ))
 tries += 1

If he/she fails to guess the number after a certain number of attempts
then it displays a message about his failure.It needs to be a while

 loop cause it the topic I'm at.

Can anyone give me some help on where to put the loop.


You already have one. Look at the code above, see the while?
You do not need another one.

And you are already counting how many times round the loop you go.

So all you need to do is use that counter to stop the while
loop when it reaches a given value.

Currently the loop stops when guess == the_number
You would like it to also stop when your counter reaches the limit.

Do you know how to do that? Have a go and tell us how you get on.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2011-12-14 Thread Prasad, Ramit
-Original Message-
From: tutor-bounces+ramit.prasad=jpmorgan@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmorgan@python.org] On Behalf Of rog 
capp
Sent: Wednesday, December 14, 2011 4:41 PM
To: tutor@python.org
Subject: [Tutor] while loops

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know  if the guess is to high, to low
# or right on the money

import random

print(\tWelcome to 'Guess My Number'!)
print(I'm thinking of a number between 1 and 100.)
print(Try to guess it in as few attempts as possible.\n)

# set the initial values
the_number = random.randint(1,100)
guess = int(input(Take a guess: ))
tries = 1

# Guessing loop
while  guess != the_number:

if guess  the_number:
print(Lowere...)
else:
print(Higher...)

guess = int(input(Take a guess: ))
tries += 1

print(good job)

input(\n\nPress the enter key to exit.)



This is a program from Python for the absulute beginner(which I am).
End of the chapter is a challenge that asks me to limit the number of
guesses the player gets.
If he/she fails to guess the number after a certain number of attempts
then it displays a message
about his failure.It needs to be a while loop cause it the topic I'm
at.Can anyone give me some help
on where to put the loop.When i put it in with the if
guessthe_number loop, the program either
prints higher or lower continuously(continuous loop I imagine) or it
gives me the answer whether its
right or wrong after a couple guesses.Any help will be appreciated.
=

If you want to stop after a certain number of attempts, then your 
loop should compare the number of tries (you are storing this correctly)
against the number of max allowed attempts (you are not 
storing this part so that needs to be done first). You can use the 
current loop, just change the conditions (this part is
second)d. Hopefully that makes sense to you.


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] nested loops

2011-02-07 Thread Michael M Mason

Alan Gauld wrote:-
 Wayne Werner waynejwer...@gmail.com wrote 
 found = False
  highscore = 0
  alignment = somealignment
  for x in something and not found:
  for y in somethingelse and not found:
for z in evenmoresomething:
if x+y+z  highscore:
highscore = x+y+z
alignment = newalignment
 found = True
 break

 HTH,

That's going to exit first time through, isn't it?

-- 
Michael


This mail was sent via Mail-SeCure System.



 
 

This footnote confirms that this email message has been scanned by
PineApp Mail-SeCure for the presence of malicious code, vandals  computer 
viruses.




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] nested loops

2011-02-07 Thread Steven D'Aprano

Alan Gauld wrote:


Wayne Werner waynejwer...@gmail.com wrote
You probably want to add a sentinel to break out of the outer
loops too:


I don't think you want to break out of *any* of the loops. Otherwise you 
will skip testing combinations. In your example, the first time you set 
highscore and alignment, you break out of all three loops and only test 
the first triple x,y,z.



  found = False

highscore = 0
alignment = somealignment
for x in something and not found:
 for y in somethingelse and not found:
  for z in evenmoresomething:
  if x+y+z  highscore:
  highscore = x+y+z
  alignment = newalignment

found = True
break


That's the equivalent of a return in the innermost loop. If you're 
looking for the *first* matching highscore, that's fine, but not if you 
want the biggest.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] nested loops

2011-02-07 Thread Alan Gauld


Steven D'Aprano st...@pearwood.info wrote

I don't think you want to break out of *any* of the loops. Otherwise 
you will skip testing combinations.


In that case I misread the OP. I thought he specifically wanted
to avoid testing all the options and exit when he reached his target.

In your example, the first time you set highscore and alignment, you 
break out of all three loops


Yep, thats what I thought was being asked for.
It seems I mistook the intent. reading too quickly I suspect.

Alan G 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] for loops when there is only one row in the result - is there an alternative?

2010-11-25 Thread Rance Hall
Im using the py-postgresql module (docs here:
http://python.projects.postgresql.org/docs/1.0/)

in a python 3.1 environment to connect to my database.

so far everything is working, but I'm having trouble understanding the
structure of the variable returned by a select statement

Generally you have something like this:

clientlist = get_clients()  # where get_clients is a prepared sql statement.

normally you would get the individual rows like this:

for row in clientlist:
   do stuff


which is great for a long list of results.  But I'm running into
issues when there are only 0 or 1 results in the set.

if there are zero rows then I can do something like:

if len(clientlist) == 0:
   do stuff

I'm looking for a better way to access the row when there is just one
row in the result.

Say from a user login attempt, or a request to edit an existing client record.

Is there a decent way to get direct access to the single row in the
result set without having to go through the for loop for just one
item?

It likely helps to know exactly what variable type clientlist would
be.  I have no idea.

What I can say is that once you do get the row result, you can refer
to values in the row with syntax like row[columnname], but I'm
honestly not sure if this is helpful information.

Ive read the module docs looking for something interesting, but I
can't seem to find this particular tidbit.

If I have to do the for loop fine, but I just thought it looked a little ugly.

Rance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops when there is only one row in the result - is there an alternative?

2010-11-25 Thread Steven D'Aprano

Rance Hall wrote:


Generally you have something like this:

clientlist = get_clients()  # where get_clients is a prepared sql statement.

normally you would get the individual rows like this:

for row in clientlist:
   do stuff


which is great for a long list of results.  But I'm running into
issues when there are only 0 or 1 results in the set.


If clientlist is empty, you don't need to explicitly test for it:

 clientlist = []  # nothing there
 for row in clientlist:
... print(Hello world)
...


Notice that nothing gets printed.


if there are zero rows then I can do something like:

if len(clientlist) == 0:
   do stuff



Generally one merely needs to check the list itself:

if clientlist:
...


although be warned that lazy lists, or iterators, are slightly 
different -- but if len(clientlist) works, then this should also work.




I'm looking for a better way to access the row when there is just one
row in the result.


This should work:

row, = clientlist  # if one row only -- note the comma!
row1, row2 = clientlist  # if two rows
row1, row2, row3 = clientlist  # three rows

If the comma in the first example is too subtle, try this:

[row] = clientlist

Another way which should work:

row = clientlist[0]



Say from a user login attempt, or a request to edit an existing client record.

Is there a decent way to get direct access to the single row in the
result set without having to go through the for loop for just one
item?

It likely helps to know exactly what variable type clientlist would
be.  I have no idea.


type(clientlist) will tell you.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-16 Thread Nithya Nisha
Hi there,

This is the Code. Please check it.It is working fine.

import random
headsCount = 0
tailsCount = 0
count = 1

while count = 100:
   coin = random.randrange(2)
   if coin == 0:
 headsCount += 1
   else:
 tailsCount += 1
   count += 1

print The number of heads was, headsCount
print The number of tails was, tailsCount

raw_input(\n\nPress the enter key to exit.)


*
Your Description *:

On Tue, Nov 16, 2010 at 1:25 PM, Dave Angel da...@ieee.org wrote:

 When I run this code (I'm also a noob) I get this result:-

  [evaluate lines 1-22 from untitled-1.py]

 The number of heads was 73
 The number of tails was 100

 Press the enter key to exit.

 # Surely, if flipping a single coin 100 times your total number of heads
 and
 tails should add up to 100
 # not 173 or am I missing the point?


  No, you're missing an indentation.  If you check the code you're running,
 I think you'll find that you didn't unindent the line incrementing count.

 Of course, it's less error prone to simply use
 for count in xrange(100):

 instead of while count  100:

 and you wouldn't need to increment count.

 DaveA




-- 
With Regards,
Nithya S
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-16 Thread Nithya Nisha
Thankyou..!!!


Regards,
Nithya

On Tue, Nov 16, 2010 at 1:51 PM, Luke Pettit petl...@gmail.com wrote:

 Arrr thats better Nithya it works fine now. I had it working fine before
 it was just coming up with that strange result of 73 and 100
 when I copied the code into wing to check it out in order to understand it.
 Wing picked up the spacing and I had already corrected
 that Dave as I was simply looking at Nithya code.


 On 16 November 2010 19:10, Nithya Nisha nithyakarpa...@gmail.com wrote:

 Hi there,

 This is the Code. Please check it.It is working fine.

 import random
 headsCount = 0
 tailsCount = 0
 count = 1
 
 while count = 100:
coin = random.randrange(2)
if coin == 0:
  headsCount += 1
else:
  tailsCount += 1
count += 1
 
 print The number of heads was, headsCount
 print The number of tails was, tailsCount
 
 raw_input(\n\nPress the enter key to exit.)


 
 *
 Your Description *:

 On Tue, Nov 16, 2010 at 1:25 PM, Dave Angel da...@ieee.org wrote:

  When I run this code (I'm also a noob) I get this result:-

  [evaluate lines 1-22 from untitled-1.py]

 The number of heads was 73
 The number of tails was 100

 Press the enter key to exit.

 # Surely, if flipping a single coin 100 times your total number of heads
 and
 tails should add up to 100
 # not 173 or am I missing the point?


  No, you're missing an indentation.  If you check the code you're
 running, I think you'll find that you didn't unindent the line incrementing
 count.

 Of course, it's less error prone to simply use
 for count in xrange(100):

 instead of while count  100:

 and you wouldn't need to increment count.

 DaveA




 --
 With Regards,
 Nithya S




 --
 Luke Pettit

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-16 Thread Stephanie Dawn Samson

Greetings,
As a thread starter, I thought I should write the rewritten code I got that 
others helped me get to, since this thread is still going on.

# Coin Flips# The program flips a coin 100 times and then# tells you the number 
of heads and tailsimport random
print \aprint \tWelcome to 'Coin Flipper!'print \nI will flip a coin 100 
times and then tell youprint the number of heads and tails!\n
# set the coinheadsCount = 0tailsCount = 0count = 1
while count = 100:coin = random.randrange(2)if coin == 0:
headsCount += 1else:tailsCount += 1count += 1

print The number of heads was, headsCountprint The number of tails was, 
tailsCount
raw_input(\n\nPress the enter key to exit.)
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-16 Thread Alan Gauld


Stephanie Dawn Samson sd...@live.ca wrote

 thought I should write the rewritten code I got that others helped 
me get to


By applying a couple of other ideas that have been suggested you get
something shorter and arguably slightly clearer:

# Coin Flips
# The program flips a coin 100 times and then
# tells you the number of heads and tails

import random

print 
   Welcome to 'Coin Flipper!'
I will flip a coin 100 times and then tell you
the number of heads and tails!

headsCount = 0

for count in range(100):
   if random.randrange(2):  # returns 1/0 = true/False
  headsCount += 1

print The number of heads was, headsCount
print The number of tails was, 100-headsCount
raw_input(\n\nPress the enter key to exit.)


And you could replace the whole for loop with a generator expression
if you really wanted to, but I suspect that is getting into advanced
territory for you at this stage...

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-16 Thread bob gailer

Just for the heck of it:

heads = sum(random.randrange(2) for i in range(100))

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-15 Thread Nithya Nisha
Hi Tom,

Your code is almost correct. Little mistake is there.The random number
generate should be in while loop.

 import random

 # set the coin

 headsCount = 0
 tailsCount = 0
 count = 0

 # the loop
 while count  100:   #If
you declare count = 0. The while loop condition should be  less than
100.Else you will get 101 counts.
 *coin = random.randrange(2)*
 if coin == 0:
 headsCount += 1
else:   #Becase We
already declared randrange(2).So the coin value is 0 or 1.So we can use else
condition.
 tailsCount += 1
 count += 1


 print The number of heads was, headsCount
 print The number of tails was, tailsCount

 raw_input(\n\nPress the enter key to exit.)

Regards,
Nithya

_
*
Your Description*:

On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks para...@pobox.com wrote:

 On Sun, 14 Nov 2010 17:16:36 -0500
 Dawn Samson sd...@live.ca wrote:

  Greetings,
 
  I'm a Python beginner and working my way through Michael Dawson's
  Python Programming for the Absolute Beginner. I'm stuck in a
  particular challenge that asks me to write a program that flips a
  coin 100 times and then tells you the number of heads and tails.
  I've been trying to work on this challenge for a while now and can't
  get it to work (either it has 100 heads or 100 tails). I've been
  reworking this code many times and currently what I have does not do
  anything at all at IDLE. Please take a look at my code below:
 
  import random
 
  # set the coin
  coin = random.randrange(2)
  headsCount = 0
  tailsCount = 0
  count = 0
 
  # the loop
  while count = 100:
  coin
  if coin == 0:
  headsCount += 1
  if coin == 1:
  tailsCount += 1
  count += 1
 
 
  print The number of heads was, heads
  print The number of tails was, tails
 
  raw_input(\n\nPress the enter key to exit.)
 
  Thanks,
  S. Dawn Samson

 From one beginner to another - it looks to me like you set the value of
 coin once then checked it 100 times.  If you want to reset the value of
 coin maybe it (i.e. setting the value of coin, not just calling
 the value of coin) should be in the loop too?

 tom
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-15 Thread Luke Pettit
When I run this code (I'm also a noob) I get this result:-

 [evaluate lines 1-22 from untitled-1.py]
The number of heads was 73
The number of tails was 100

Press the enter key to exit.

# Surely, if flipping a single coin 100 times your total number of heads and
tails should add up to 100
# not 173 or am I missing the point?



On 16 November 2010 15:08, Nithya Nisha nithyakarpa...@gmail.com wrote:

 Hi Tom,

 Your code is almost correct. Little mistake is there.The random number
 generate should be in while loop.

  import random
 
  # set the coin

  headsCount = 0
  tailsCount = 0
  count = 0
 
  # the loop
  while count  100:   #If
 you declare count = 0. The while loop condition should be  less than
 100.Else you will get 101 counts.
  *coin = random.randrange(2)*
  if coin == 0:
  headsCount += 1
 else:   #Becase We
 already declared randrange(2).So the coin value is 0 or 1.So we can use else
 condition.
  tailsCount += 1
  count += 1
 
 
  print The number of heads was, headsCount
  print The number of tails was, tailsCount
 
  raw_input(\n\nPress the enter key to exit.)

 Regards,
 Nithya


 _
 *
 Your Description*:

 On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks para...@pobox.comwrote:

 On Sun, 14 Nov 2010 17:16:36 -0500
 Dawn Samson sd...@live.ca wrote:

  Greetings,
 
  I'm a Python beginner and working my way through Michael Dawson's
  Python Programming for the Absolute Beginner. I'm stuck in a
  particular challenge that asks me to write a program that flips a
  coin 100 times and then tells you the number of heads and tails.
  I've been trying to work on this challenge for a while now and can't
  get it to work (either it has 100 heads or 100 tails). I've been
  reworking this code many times and currently what I have does not do
  anything at all at IDLE. Please take a look at my code below:
 
  import random
 
  # set the coin
  coin = random.randrange(2)
  headsCount = 0
  tailsCount = 0
  count = 0
 
  # the loop
  while count = 100:
  coin
  if coin == 0:
  headsCount += 1
  if coin == 1:
  tailsCount += 1
  count += 1
 
 
  print The number of heads was, heads
  print The number of tails was, tails
 
  raw_input(\n\nPress the enter key to exit.)
 
  Thanks,
  S. Dawn Samson

 From one beginner to another - it looks to me like you set the value of
 coin once then checked it 100 times.  If you want to reset the value of
 coin maybe it (i.e. setting the value of coin, not just calling
 the value of coin) should be in the loop too?

 tom
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
Luke Pettit
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-15 Thread Nithya Nisha
Hi Tom,

Your code is almost correct. Little mistake is there.The random number
generate should be in while loop.


 import random

 # set the coin

 headsCount = 0
 tailsCount = 0
 count = 0

 # the loop
 while count  100:
 #If you declare count = 0. The while loop condition
should be  less than 100.Else you will get 101 counts.
 *coin = random.randrange(2)*

 if coin == 0:
 headsCount += 1
else:   #Becase We
already declared randrange(2).So the coin value is 0 or 1.So we can use else
condition.
 tailsCount += 1
 count += 1


 print The number of heads was, headsCount
 print The number of tails was, tailsCount


 raw_input(\n\nPress the enter key to exit.)

Regards,
Nithya

__
*Your Description*

On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks para...@pobox.com wrote:

 On Sun, 14 Nov 2010 17:16:36 -0500
 Dawn Samson sd...@live.ca wrote:

  Greetings,
 
  I'm a Python beginner and working my way through Michael Dawson's
  Python Programming for the Absolute Beginner. I'm stuck in a
  particular challenge that asks me to write a program that flips a
  coin 100 times and then tells you the number of heads and tails.
  I've been trying to work on this challenge for a while now and can't
  get it to work (either it has 100 heads or 100 tails). I've been
  reworking this code many times and currently what I have does not do
  anything at all at IDLE. Please take a look at my code below:
 
  import random
 
  # set the coin
  coin = random.randrange(2)
  headsCount = 0
  tailsCount = 0
  count = 0
 
  # the loop
  while count = 100:
  coin
  if coin == 0:
  headsCount += 1
  if coin == 1:
  tailsCount += 1
  count += 1
 
 
  print The number of heads was, heads
  print The number of tails was, tails
 
  raw_input(\n\nPress the enter key to exit.)
 
  Thanks,
  S. Dawn Samson

 From one beginner to another - it looks to me like you set the value of
 coin once then checked it 100 times.  If you want to reset the value of
 coin maybe it (i.e. setting the value of coin, not just calling
 the value of coin) should be in the loop too?

 tom
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
With Regards,
Nithya S
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-15 Thread Dave Angel

When I run this code (I'm also a noob) I get this result:-


[evaluate lines 1-22 from untitled-1.py]

The number of heads was 73
The number of tails was 100

Press the enter key to exit.

# Surely, if flipping a single coin 100 times your total number of heads and
tails should add up to 100
# not 173 or am I missing the point?


No, you're missing an indentation.  If you check the code you're 
running, I think you'll find that you didn't unindent the line 
incrementing count.


Of course, it's less error prone to simply use
for count in xrange(100):

instead of while count  100:

and you wouldn't need to increment count.

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Hugo Arts
On Sun, Nov 14, 2010 at 11:16 PM, Dawn Samson sd...@live.ca wrote:
 Greetings,
 I'm a Python beginner and working my way through Michael Dawson's Python
 Programming for the Absolute Beginner. I'm stuck in a particular challenge
 that asks me to write a program that flips a coin 100 times and then tells
 you the number of heads and tails. I've been trying to work on this
 challenge for a while now and can't get it to work (either it has 100 heads
 or 100 tails). I've been reworking this code many times and currently what I
 have does not do anything at all at IDLE. Please take a look at my code
 below:

When you, as you say it, set the coin, you call the randrange
function. This picks a random number between 0 and 1 and returns it.
You then assign that number to the coin variable. So at this point,
coin contains either 0 or 1.

In the while loop, you have a line that simply says coin. You
probably think that this calls the function again, but it doesn't.
What it actually does is nothing. You simply mention the variable to
the interpreter, which retrieves its value (0 or 1). Since you don't
do anything with that value, it is simply immediately discarded again.

You need to change your code so that the coin isn't set only once, but
every iteration of the loop. Hope that helps

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Steven D'Aprano

Dawn Samson wrote:


I've been trying to work on this challenge for a while now and can't
get it to work (either it has 100 heads or 100 tails). 


Unfortunately your code has been mangled in the email, but I can guess 
your problem: you need to set


coin = random.randrange(2)

each time through the loop, not just once outside the loop.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Stephanie Dawn Samson





Thanks everyone!
I should be using algorithms for even such programs at my level. The solution 
to reiterate the coin flip every time in the loop works. Thanks a lot!
Dawn
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Adam Bark

On 14/11/10 22:16, Dawn Samson wrote:

Greetings,

I'm a Python beginner and working my way through Michael Dawson's 
Python Programming for the Absolute Beginner. I'm stuck in a 
particular challenge that asks me to write a program that flips a 
coin 100 times and then tells you the number of heads and tails. I've 
been trying to work on this challenge for a while now and can't get it 
to work (either it has 100 heads or 100 tails). I've been reworking 
this code many times and currently what I have does not do anything at 
all at IDLE. Please take a look at my code below:


import random

# set the coin
coin = random.randrange(2)
headsCount = 0
tailsCount = 0
count = 0

# the loop
while count = 100:
coin
if coin == 0:
headsCount += 1
if coin == 1:
tailsCount += 1
count += 1

print The number of heads was, heads
print The number of tails was, tails

raw_input(\n\nPress the enter key to exit.)

Thanks,
S. Dawn Samson
You try to print two variables, heads and tails which don't exist. 
The other replies covered the other main problems.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Robert Berman
From: tutor-bounces+bermanrl=cfl.rr@python.org
[mailto:tutor-bounces+bermanrl=cfl.rr@python.org] On Behalf Of Dawn Samson
Sent: Sunday, November 14, 2010 5:17 PM
To: tutor@python.org
Subject: [Tutor] While Loops: Coin Flip Game

Greetings,

I'm a Python beginner and working my way through Michael Dawson's Python
Programming for the Absolute Beginner
import random

# set the coin
coin = random.randrange(2)
headsCount = 0
tailsCount = 0
count = 0

# the loop
while count = 100:
    coin
    if coin == 0:
        headsCount += 1
    if coin == 1:
        tailsCount += 1
    count += 1

    
print The number of heads was, heads
print The number of tails was, tails

raw_input(\n\nPress the enter key to exit.)

Thanks,
S. Dawn Samson


Hi,

Think in terms of logical steps. You need to generate the results of a random
coin toss for every toss of the coin. Therefore, if you are tossing 100
tosses, you need to generate 100 results based on a probability of zero or
one.

Since this is your homework assignment you write the code, but in terms of a
logical frame work you would have something like the following.
Tossknt = 1
Generate a random toss ; results being either one or 0. Further , assume 0 is
tail; heads is one.
If toss = 1 headcount = headcount + 1
Else tailcount = tailcount + 1
Tossknt = Tossknt + 1
If Tossknt  100 Continue loop
Else print ‘nbr of heads tossed = ‘, headcount
Print ‘nbr of tails tossed = ‘, tailcount

Obviously, this is not valid python code but it should give you enough
information to solve your problem.

Good luck,

Robert


--
I am using the free version of SPAMfighter.
We are a community of 7 million users fighting spam.
SPAMfighter has removed 53 of my spam emails to date.
Get the free SPAMfighter here: http://www.spamfighter.com/len

The Professional version does not have this message


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops: Coin Flip Game :p:

2010-11-14 Thread Thomas C. Hicks
On Sun, 14 Nov 2010 17:16:36 -0500
Dawn Samson sd...@live.ca wrote:

 Greetings,
 
 I'm a Python beginner and working my way through Michael Dawson's
 Python Programming for the Absolute Beginner. I'm stuck in a
 particular challenge that asks me to write a program that flips a
 coin 100 times and then tells you the number of heads and tails.
 I've been trying to work on this challenge for a while now and can't
 get it to work (either it has 100 heads or 100 tails). I've been
 reworking this code many times and currently what I have does not do
 anything at all at IDLE. Please take a look at my code below:
 
 import random
 
 # set the coin
 coin = random.randrange(2)
 headsCount = 0
 tailsCount = 0
 count = 0
 
 # the loop
 while count = 100:
 coin
 if coin == 0:
 headsCount += 1
 if coin == 1:
 tailsCount += 1
 count += 1
 
 
 print The number of heads was, heads
 print The number of tails was, tails
 
 raw_input(\n\nPress the enter key to exit.)
 
 Thanks,
 S. Dawn Samson

From one beginner to another - it looks to me like you set the value of
coin once then checked it 100 times.  If you want to reset the value of
coin maybe it (i.e. setting the value of coin, not just calling
the value of coin) should be in the loop too?

tom
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-07 Thread Alan Gauld

Alex Hall mehg...@gmail.com wrote


I am not sure how else to explain it. I want to loop until the value
of a variable changes, but while that loop is taking place, the user
should be able to perform actions set up in a wx.AcceleratorTable.


And here we have the critical clue. You are trying to write this
loop in a GUI application. GUIs and long running loops don't
mix. GUIs are driven by events and if you write a long loop
the GUI cannot receive any events until the loop finishes
and so locks up

In a GUI environment you simulate a long loop with
1) A Timer event that does someting then sets up another timer
2) The null event (if the framework suipports it) whereby
when no other events are present the framework calls your code.

for a listener, which will sit in the background and only perform 
an

action when it detects a certain thing. In this case, a listener to
watch for a variable to turn from False to True, then to act when it
sees that change.


The listener sits inside a Timer that fires every, say, 1/10 sec.
That should leave plenty time to respond to the variable change
and give wx time to process any mouse clicks, key presses etc.

BTW. If you are doing any significant GUI work in wxPython
it will be helpful to buy the wxPython in Action book. It is very
clear and includes examples of using Timers etc.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-07 Thread Walter Prins
On 7 June 2010 02:37, Alex Hall mehg...@gmail.com wrote:

 I am not sure how else to explain it. I want to loop until the value
 of a variable changes, but while that loop is taking place, the user
 should be able to perform actions set up in a wx.AcceleratorTable.
 Looping, though, causes Windows to tell me that python.exe is not
 responding, so I have to close the entire thing. I guess I am looking
 for a listener, which will sit in the background and only perform an
 action when it detects a certain thing. In this case, a listener to
 watch for a variable to turn from False to True, then to act when it
 sees that change.


Notwithstanding what everyone else have said I'll add the following for what
it's worth:

You need to do some research into how GUI systems typically work,
particularly the message queue and each applications magic and hidden
message processing loop etc.  Basically in a GUI app there's a hidden loop
that continually checks for messages (calls) to your application and
dispatches those calls to the handlers defined in your application.
However, if your handlers do not complete quickly, then while they run,
control obviously does not return to this loop again, and consequently no
further events can/will be processed by your app.  Some OS's flag up
applications which do not process their event queues for a while as not
responding or similar.

However, in most windowing systems there's a way to process pending messages
that have built up in the queue without actually returning from the handler
that you're in.  In Delphi the call is Application.ProcessMessages, in VB
it's DoEvents.  In WxPython it's Yield().  (You can google each of those
to see the same issue in different languages/platforms if you like, it might
be instructive.)

So bottom line, in theory you can call Yield() in your loop and you should
be OK -- your app should suddenly be responsive again even while in the
loop.   This type of solution is however the more cheap and dirty
alternative and can introduce it's own set of problems and downsides.  (What
if for example another call/message is processed to the same event handler
from which you called Yield() alrady?  The point is you may open yourself up
to re-entrancy issues if you're not careful.  Also if the loop is very tight
you might end-up consuming a lot of CPU doing nothing, so a sleep() type
call might also be advisable in the loop to prevent spending more time
calling Yield() than doing anything else. )

Anyway, I've done a quick google and the following page seems to be a good
discussion of the above thoughts:
http://wiki.wxpython.org/LongRunningTasks

HTH,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-07 Thread Mark Lawrence

On 07/06/2010 01:44, Alex Hall wrote:

Further to the other comments that you've had, could you please refer to 
the following, thanks.


http://www.catb.org/~esr/faqs/smart-questions.html

Kindest regards.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops / listeners

2010-06-07 Thread Francesco Loffredo

Hi all,
I think that simply erasing those continue statements will let Python 
respond again. Those statements are both useless and damaging, because 
the following time.sleep(.1) statements will NEVER be executed. And 
this, in turn, is IMHO the reason why Python stops responding: it lacks 
the time to do so.

Hope that helps
Francesco

Il 07/06/2010 5.09, Alex Hall wrote:

Hi all,
First off, I apologize to the list for my previous thread; somehow,
despite my having written the post, it ended up blank ()

I have a main loop which will continue for as long as neither player1
nor player2 has won. Inside that loop I have a call to a function
which should basically wait until the user completes a turn, then
return, exiting this loop and returning to the main loop, the one
looping until there is a winner. Once back there, the second player's
idling function is called; once that user completes a turn, the main
loop switches back to the first user, and so on. Here is the main
loop:
  player1.takeTurn() #someone has to start off the game

  #now loop until someone wins...
  while not player1.isWinner and not player2.isWinner:
   if player1.grid.turnOver: #player1 is done for this turn
player1.grid.speak(player 2 is going.)
#lock p1 out of the window, unlock p2, and then loop p2 until s/he
does something
player1.lock(); player2.unlock(); player2.takeTurn()
   else: #player2 has completed a turn
player2.grid.speak(player 1 is going.)
#opposite of above - lock p2, unlock p1, loop until p1 is done
player2.lock(); player1.unlock(); player1.takeTurn()
   #end if
   continue #is this doing anything?
   time.sleep(.1) #again, is this important?
  #end while

The lock and unlock functions are simply there to disable and enable
keyboard/mouse commands, respectively, so lock causes the player's
screen to stop responding to input while unlock unfreezes the screen.
This way, if you and I are playing a game, I can't keep shooting even
if my turn is over.
TakeTurn() is that smaller loop I was talking about:
  def takeTurn(self):
   while not self.grid.turnOver: #turnOver is true once a turn-ending
function is called in grid
continue
time.sleep(.1)
   #end while
  #end def

That is inside the Player class. Grid is just another object that is
really the most important part of all the game logic; Grid holds the
wx frame on which everything is drawn, the boolean to tell if the turn
is over, the ships, and more. That is why the function checks
self.grid.turnOver, instead of just self.turnOver; turnOver tells if
the player has performed a move that ends a turn or not. Firing ends a
turn, while just moving around does not.

The question, then, is this: when I run the code, Windows says
python.exe has stopped responding. I know that this is because it is
getting stuck, probably in the takeTurn() loop. Ordinarily, a
situation like this would probably call for:
while ok:
  ok=#program logic

The hard part with my program, though, is that all input is set up
with a wx.AcceleratorTable object, so I cannot just dump everything
into a huge while loop and have it process that way. What I am looking
for is some kind of listener object, so that I can just monitor
self.grid.turnOver and call a function, or perform a few lines of
code, when the listener detects a change in turnOver. On the other
hand, there may be something simple that I am missing in my while loop
that would cause the problem of python.exe crashing to not happen
(well, not crashing, but rather not responding). I hope it is the
latter problem, but I am not sure what else I could add to the loop(s)
to stop this problem. Thanks, and sorry again for the blank message;
still not sure how that happened. Hopefully this one works!





Nessun virus nel messaggio in arrivo.
Controllato da AVG - www.avg.com
Versione: 9.0.829 / Database dei virus: 271.1.1/2921 -  Data di rilascio: 
06/06/10 08:25:00


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread bob gailer

On 6/6/2010 8:44 PM, Alex Hall wrote:

--
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com;http://www.facebook.com/mehgcap

   

What is your question?


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
On 6/6/10, bob gailer bgai...@gmail.com wrote:
 On 6/6/2010 8:44 PM, Alex Hall wrote:
 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap


 What is your question?


 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC


Why would that code cause Windows to consider the process not
responding, and how can I fix this so I can have a sort of listener
in place, awaiting a change in the grid.turnOver variable inside
Player.takeTurn() so that the main while loop can switch to the other
player once the one player's turn is over? I thought while loops would
do it, but Windows sees them as making python.exe unresponsive.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Lie Ryan
On 06/07/10 11:08, Alex Hall wrote:
 On 6/6/10, bob gailer bgai...@gmail.com wrote:
 On 6/6/2010 8:44 PM, Alex Hall wrote:
 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap


 What is your question?


 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC


 Why would that code cause Windows to consider the process not
 responding, and how can I fix this so I can have a sort of listener
 in place, awaiting a change in the grid.turnOver variable inside
 Player.takeTurn() so that the main while loop can switch to the other
 player once the one player's turn is over? I thought while loops would
 do it, but Windows sees them as making python.exe unresponsive.

Would you buy me a crystal ball to foresee what you're talking about?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
On 6/6/10, Lie Ryan lie.1...@gmail.com wrote:
 On 06/07/10 11:08, Alex Hall wrote:
 On 6/6/10, bob gailer bgai...@gmail.com wrote:
 On 6/6/2010 8:44 PM, Alex Hall wrote:
 --
 Have a great day,
 Alex (msg sent from GMail website)
 mehg...@gmail.com;http://www.facebook.com/mehgcap


 What is your question?


 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC


 Why would that code cause Windows to consider the process not
 responding, and how can I fix this so I can have a sort of listener
 in place, awaiting a change in the grid.turnOver variable inside
 Player.takeTurn() so that the main while loop can switch to the other
 player once the one player's turn is over? I thought while loops would
 do it, but Windows sees them as making python.exe unresponsive.

 Would you buy me a crystal ball to foresee what you're talking about?
I am not sure how else to explain it. I want to loop until the value
of a variable changes, but while that loop is taking place, the user
should be able to perform actions set up in a wx.AcceleratorTable.
Looping, though, causes Windows to tell me that python.exe is not
responding, so I have to close the entire thing. I guess I am looking
for a listener, which will sit in the background and only perform an
action when it detects a certain thing. In this case, a listener to
watch for a variable to turn from False to True, then to act when it
sees that change.

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread bob gailer

On 6/6/2010 9:37 PM, Alex Hall wrote:

On 6/6/10, Lie Ryanlie.1...@gmail.com  wrote:
   

On 06/07/10 11:08, Alex Hall wrote:
 

On 6/6/10, bob gailerbgai...@gmail.com  wrote:
   

On 6/6/2010 8:44 PM, Alex Hall wrote:
 

--
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com;http://www.facebook.com/mehgcap


   

What is your question?


--
Bob Gailer
919-636-4239
Chapel Hill NC


 

Why would that code


What code. I don't see any!

cause Windows to consider the process not
responding, and how can I fix this so I can have a sort of listener
in place, awaiting a change in the grid.turnOver variable inside
Player.takeTurn() so that the main while loop can switch to the other
player once the one player's turn is over? I thought while loops would
do it, but Windows sees them as making python.exe unresponsive.
   

Would you buy me a crystal ball to foresee what you're talking about?
 

I am not sure how else to explain it. I want to loop until the value
of a variable changes, but while that loop is taking place, the user
should be able to perform actions set up in a wx.AcceleratorTable.
Looping, though, causes Windows to tell me that python.exe is not
responding, so I have to close the entire thing. I guess I am looking
for a listener, which will sit in the background and only perform an
action when it detects a certain thing. In this case, a listener to
watch for a variable to turn from False to True, then to act when it
sees that change.
   


We are complaining because you first send a post with no content, then 
one with a question but no code.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loops / listeners

2010-06-06 Thread Alex Hall
Hi all,
First off, I apologize to the list for my previous thread; somehow,
despite my having written the post, it ended up blank ()

I have a main loop which will continue for as long as neither player1
nor player2 has won. Inside that loop I have a call to a function
which should basically wait until the user completes a turn, then
return, exiting this loop and returning to the main loop, the one
looping until there is a winner. Once back there, the second player's
idling function is called; once that user completes a turn, the main
loop switches back to the first user, and so on. Here is the main
loop:
 player1.takeTurn() #someone has to start off the game

 #now loop until someone wins...
 while not player1.isWinner and not player2.isWinner:
  if player1.grid.turnOver: #player1 is done for this turn
   player1.grid.speak(player 2 is going.)
   #lock p1 out of the window, unlock p2, and then loop p2 until s/he
does something
   player1.lock(); player2.unlock(); player2.takeTurn()
  else: #player2 has completed a turn
   player2.grid.speak(player 1 is going.)
   #opposite of above - lock p2, unlock p1, loop until p1 is done
   player2.lock(); player1.unlock(); player1.takeTurn()
  #end if
  continue #is this doing anything?
  time.sleep(.1) #again, is this important?
 #end while

The lock and unlock functions are simply there to disable and enable
keyboard/mouse commands, respectively, so lock causes the player's
screen to stop responding to input while unlock unfreezes the screen.
This way, if you and I are playing a game, I can't keep shooting even
if my turn is over.
TakeTurn() is that smaller loop I was talking about:
 def takeTurn(self):
  while not self.grid.turnOver: #turnOver is true once a turn-ending
function is called in grid
   continue
   time.sleep(.1)
  #end while
 #end def

That is inside the Player class. Grid is just another object that is
really the most important part of all the game logic; Grid holds the
wx frame on which everything is drawn, the boolean to tell if the turn
is over, the ships, and more. That is why the function checks
self.grid.turnOver, instead of just self.turnOver; turnOver tells if
the player has performed a move that ends a turn or not. Firing ends a
turn, while just moving around does not.

The question, then, is this: when I run the code, Windows says
python.exe has stopped responding. I know that this is because it is
getting stuck, probably in the takeTurn() loop. Ordinarily, a
situation like this would probably call for:
while ok:
 ok=#program logic

The hard part with my program, though, is that all input is set up
with a wx.AcceleratorTable object, so I cannot just dump everything
into a huge while loop and have it process that way. What I am looking
for is some kind of listener object, so that I can just monitor
self.grid.turnOver and call a function, or perform a few lines of
code, when the listener detects a change in turnOver. On the other
hand, there may be something simple that I am missing in my while loop
that would cause the problem of python.exe crashing to not happen
(well, not crashing, but rather not responding). I hope it is the
latter problem, but I am not sure what else I could add to the loop(s)
to stop this problem. Thanks, and sorry again for the blank message;
still not sure how that happened. Hopefully this one works!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: loops

2009-12-08 Thread Richard Hultgren




- Forwarded Message 
From: Richard Hultgren hultgren1...@yahoo.com
To: tutor@python.org
Sent: Mon, December 7, 2009 2:53:40 PM
Subject: loops
I'm quite new but determined.  Can you explain to me, step by step, what is 
going on in the computer in this loop.  I hope I am not being too dumb!


a = 0
b = 1
count = 0
max_count = 20
while count  max_count:
    count = count + 1
    # we need to keep track of a since we change it
    old_a = a# especially here
    old_b = b
    a = old_b
    b = old_a + old_b
    # Notice that the , at the end of a print statement keeps it
    # from switching to a new line
    print old_a,


  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: loops

2009-12-08 Thread Serdar Tumgoren
 - Forwarded Message 
 From: Richard Hultgren hultgren1...@yahoo.com
 To: tutor@python.org
 Sent: Mon, December 7, 2009 2:53:40 PM
 Subject: loops
 I'm quite new but determined.  Can you explain to me, step by step, what is
 going on in the computer in this loop.  I hope I am not being too dumb!


Hmm...that still seems like quite a broad question. Can you be more
specific about which portion you find confusing or unclear?

If not, you might do better by starting with a general programming
text. The top one is a list of texts for beginning programmers,
followed by a few specific links to online texts:

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
http://www.freenetpages.co.uk/hp/alan.gauld/
http://swaroopch.com/notes/Python

HTH,
Serdar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: loops

2009-12-08 Thread christopher . henk
You should probably read some of the links sent to you earlier but here is 
a stab at an explanation.


Richard Hultgren wrote on 12/08/2009 10:36:08 AM:

 - Forwarded Message 
 From: Richard Hultgren hultgren1...@yahoo.com
 To: tutor@python.org
 Sent: Mon, December 7, 2009 2:53:40 PM
 Subject: loops
 I'm quite new but determined.  Can you explain to me, step by step, what 
is going on in the computer in this loop.  I 
 hope I am not being too dumb!

 a = 0
 b = 1
 count = 0
 max_count = 20

The above steps are initialization of your variables.  'a' points to the 
value 0, 'b' points to 1, etc.
Since the values of the variables are used within the loop we need to give 
it somewhere to start, otherwise we will get an error. 

 while count  max_count:

The while loop will continue until 'count  max_count' evaluates to False 
(20 loops, due to line below)
the loop is defined as everything that is indented below this line.

 count = count + 1

Increase the value of count by one each loop iteration, otherwise the 
statement 'count  max_count' will never change value, and the loop will 
never end.

 # we need to keep track of a since we change it
 old_a = a# especially here
 old_b = b

Keep the old values of the variables since we want to add them together 
for the new value of b and will change the values in the next steps. 

 a = old_b
 b = old_a + old_b

reassign 'a' to the value of 'old_b'.  If we didn't save the value of 'a' 
into 'old_a' above we wouldn't know what it was anymore.
reassign 'b' to the sum of 'old_a' and 'old_b'

 # Notice that the , at the end of a print statement keeps it
 # from switching to a new line
 print old_a,
prints the value of old_a followed by a space.  Without the comma at the 
end the print statement each loop would print on a new line.


The best way to follow what is happening is to trace the variables through 
the program.  you would get a table that loops something like :

max_count   count   a   b   old_a   old_b 
countmax_count OUTPUT
20  0   0   1   no ValueNo Value  
T   No output yet 
20  1   1   1   0   1   T  
0 
20  2   1   2   1   1   T  
0 1
20  3   2   3   1   2   T  
0 1 1
20  4   3   5   2   3   T  
0 1 1 2
20  5   5   8   3   5   T  
0 1 1 2 3
20  6   8   13  5   8   T  
0 1 1 2 3 5
.
.
.
20  19  2584676541812584T 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
20  20  2584676541812584F 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 
(You might want to check the last two rows, not guaranteeing the values 
are right)

In the last row countmax_count is False the loop won't run and therefore 
nothing will change. 

Hope this helps some, but would recommend you try following some of the 
tutorials online for beginning programming to help explain some of the 
concepts, feel free to ask here whenever you get confused.

 
Chris
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: loops

2009-12-08 Thread Alan Gauld


Serdar Tumgoren zstumgo...@gmail.com wrote 


http://www.freenetpages.co.uk/hp/alan.gauld/

Note the new URL in my sig. Freenet are due to close this site soon.
Its been locked for over a year.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-07 Thread Lie Ryan
On Tue, 02 Dec 2008 01:17:41 +, Alan Gauld wrote:

 while loops are used much less in Python than in other languages because
 for loops are so powerful.

Actually, I think python's for-loop is so powerful that while loop could 
be removed from the language and no power would be lost (although many 
idioms are much better (and faster) written in while loop). This is 
because python allows infinite-length iterable, you can emulate while 
True loop with something like this:

eternity = __import__('itertools').count()
for ever in eternity:
print can't stp

# the code above is slightly obfuscated, 
# I wouldn't normally write it like that
# ...
# [1]

 while lops are generally used in cases where you don't know how many
 times you need to loop or you want to loop 'forever'.
 
 while True:
 print 'Can't stop me now!'
 
 will keep on looping until you close the program
 
 c = 0
 while c != -1:
 c = int(raw_input('Enter a number(-1 to stop) ')) 
 print c
 
 will keep looping until the user enters -1

while that can be turned into something like this:

for ever in eternity:
c = int(raw_input('Enter a number(-1 to stop) ')) 
print c

OR

from itertools import repeat
from functools import partial
def ask():
def stop(): raise StopIteration
asker = partial(raw_input, 'Enter a number(-1 to stop) ')
for n in repeat(asker):
n = n()
yield n if n != '-1' else stop()

for c in ask():
print c

 More info and a comparison with JabaScript and VBScript can be found in
 my tutor in the looping topic.

[1] I cheated slightly, there is a while loop in the C code for itertools
[2] I'm not suggesting that while loop should go away, I'm illustrating 
the power of the for(ce).

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 'for' loops

2008-12-01 Thread WM.
I recently asked a question about 'for' loops, expecting them to be 
similar to 'for-next' loops. I have looked at several on-line tutors but 
 am still in the dark about what 'for' loops do.

Does anyone have a plain English about the use of 'for' loops?
Are 'while' loops the only way Python runs a sub-routine over  over?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-01 Thread Steve Willoughby
On Mon, Dec 01, 2008 at 04:44:02PM -0800, WM. wrote:
 I recently asked a question about 'for' loops, expecting them to be 
 similar to 'for-next' loops. I have looked at several on-line tutors but 
  am still in the dark about what 'for' loops do.
 Does anyone have a plain English about the use of 'for' loops?
 Are 'while' loops the only way Python runs a sub-routine over  over?

No, both 'while' and 'for' loops are for running a block of code
(whether subroutine calls or whatever) over and over.  The difference
between the two is that 'while' will continue repeating the block
for however many iterations it takes until the condition is satisfied
('while x is true, for some expression x'), a 'for' loop will run the
block of code a set number of times ('once for each element of some
set of values').

So if you want to execute 'print' for every line of a file, you
would do this:

  for line in file:
print line

If you wanted to double a value until it exceeded 100, you would
use a while loop:

  while x = 100:
x *= 2

If you just want something executed a specific number of times,
(like print hello 10 times), you can use a for loop:

  for i in range(10):
print hello

This is, just like any 'for' loop, executing the block once per
element of a list.  The list in this case is range(10) which is
an expression that generates the list (0, 1, 2, ..., 9), so you
get one run through the code for each of those.

Does that help?

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

-- 
Steve Willoughby|  Using billion-dollar satellites
[EMAIL PROTECTED]   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-01 Thread W W
On Mon, Dec 1, 2008 at 6:44 PM, WM. [EMAIL PROTECTED] wrote:

 I recently asked a question about 'for' loops, expecting them to be similar
 to 'for-next' loops. I have looked at several on-line tutors but  am still
 in the dark about what 'for' loops do.
 Does anyone have a plain English about the use of 'for' loops?
 Are 'while' loops the only way Python runs a sub-routine over  over?


For loops are mainly used when you want a specific number of iterations,
such as looping over the elements of a list. In C/C++ you would do something
like this:

int myarray[] = {1, 2, 3, 4, 5};
for(int x = 0; x  5; x++)
printf(%d, myarray[x])

In python it would be much cleaner:

myarray = [1, 2, 3, 4, 5]
for x in myarray:
print x

HTH,
Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn't. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-01 Thread John Fouhy
On 02/12/2008, WM. [EMAIL PROTECTED] wrote:
 I recently asked a question about 'for' loops, expecting them to be similar
 to 'for-next' loops. I have looked at several on-line tutors but  am still
 in the dark about what 'for' loops do.
  Does anyone have a plain English about the use of 'for' loops?
  Are 'while' loops the only way Python runs a sub-routine over  over?

I'm not sure exactly what you understand by a for-next loop.

A for loop, essentially, iterates over a list [1].  e.g.

for fruit in ['apple', 'pear', 'banana', 'tomato']:
print fruit

The loop will set the variable 'fruit' to be 'apple', 'pear', etc. on
each pass through the loop.

If you just want to do something n times, the usual idiom is:

for i in range(n):
# do something, possibly involving i

range(n) is a function that will produce the list [0, 1, 2, ..., n-1].

Tutorials should cover this, so I'm not sure if I'm telling you
anything new.  If there's something particular you're stuck on, ask
:-)

-- 
John.

[1] Technically, it iterates over an iterator, which you can think of
as an object that behaves like a list when you throw it at a for loop.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-01 Thread Alan Gauld


WM. [EMAIL PROTECTED] wrote

I recently asked a question about 'for' loops, expecting them to be 
similar to 'for-next' loops. I have looked at several on-line tutors 
but am still in the dark about what 'for' loops do.


Python for loops are like foreach loops in other languages.
A Python for loop executes a bit of code for each element
in a sequence (list, string, dictionary, set, file etc)
It will keep looping until it runs out of items in the
sequence.

Thus to print each letter in a string:

mystring = 'foobar'
for ch in mystring:
  print ch

Or to print each element of a list:

mlist = [1,'2,'a',45, True]
for item in mylist:
   print item

And if you want to loop for a fixed number of iterations simply 
construct
a list with that number of elements. The range() function does that 
for

us, thus:

for n in range(12):
   print 'hi'

will print 'hi' 12 times.


Does anyone have a plain English about the use of 'for' loops?
Are 'while' loops the only way Python runs a sub-routine over  
over?


while loops are used much less in Python than in other languages
because for loops are so powerful.
while lops are generally used in cases where you don't know how
many times you need to loop or you want to loop 'forever'.

while True:
   print 'Can't stop me now!'

will keep on looping until you close the program

c = 0
while c != -1:
   c = int(raw_input('Enter a number(-1 to stop) '))
   print c

will keep looping until the user enters -1

More info and a comparison with JabaScript and VBScript can be
found in my tutor in the looping topic.


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'for' loops

2008-12-01 Thread Kent Johnson
On Mon, Dec 1, 2008 at 7:56 PM, John Fouhy [EMAIL PROTECTED] wrote:

 [1] Technically, it iterates over an iterator, which you can think of
 as an object that behaves like a list when you throw it at a for loop.

The object of the 'in' must be an iterable, which is an object that
can produce an iterator when asked. A list is an iterable, not an
iterator.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-28 Thread Eric Abrahamsen
I finally got my iterator-based version working, only to discover that  
it's nearly four times slower than the brute-force multiple-loops  
version I started with! Then I tried just adding an incrementing index  
to the loop, so that each loop only ran through  
self.events[last_index:], but that was still twice as slow as without  
the index. I suppose it's the overhead of incrementing the variable,  
or maybe some optimization in Python's internals, but the take home  
lesson was definitely 'leave well enough alone'. Anyway, thanks again  
for the advice, it's been a learning experience...


E


On Aug 27, 2008, at 2:22 AM, Kent Johnson wrote:


On Tue, Aug 26, 2008 at 1:24 PM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:

On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote:



If all you want to do with the nested Month, etc is to iterate the
events in them, you could probably use a shared iterator. It would
have to be able to push-back items so that when you hit the
out-of-range item you could push it back on the iterator.


Is a 'shared iterator' something special, or do you mean all the  
instances
would draw their events from a single iterator? I'm not sure what  
this would

look like.


It's nothing special, I just mean that all instances would share an
iterator. You would pass the iterator to the iteration function.


Just for the sake of argument, here's the principle I'm working from:

#

lst = range(10)
iterlst = iter(lst)
iterlst.next()

0

for x in iterlst:

...   if x  5:
... print x
...   else:
... break
...
1
2
3
4

for x in iterlst:

...   print x
...
6
7
8
9
#

So that's why I'm creating the iterator outside of the while loop  
in the
original code, and then using a repeated for loop with a break to  
step
through all the events only once. Of course, the fact that 5 isn't  
in there

probably points to the source of my problems! The solution might be
assigning iterlist.next() to a variable, and advancing the variable.


The problem is that the first loop consumes the 5 from the iterator
but doesn't actually process it. That is why you need an iterator with
push-back - so you can put the 5 back in the iterator and get it out
again in the next loop.
http://code.activestate.com/recipes/502304/
Though working with indices directly might be simpler.

Kent


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-28 Thread Lie Ryan

 
  Just for the sake of argument, here's the principle I'm working
 from:
 
  #
  lst = range(10)
  iterlst = iter(lst)
  iterlst.next()
  0
  for x in iterlst:
  ...   if x  5:
  ... print x
  ...   else:
  ... break
  ...
  1
  2
  3
  4
  for x in iterlst:
  ...   print x
  ...
  6
  7
  8
  9
  #

If that contrived case is the case, you could change the code a bit to
make 5 appears:

for x in iterlst:
print x
if x = 5: break
for x in iterlst:
print x

 
  So that's why I'm creating the iterator outside of the while loop in
 the
  original code, and then using a repeated for loop with a break to
 step
  through all the events only once. Of course, the fact that 5 isn't
 in there
  probably points to the source of my problems! The solution might be
  assigning iterlist.next() to a variable, and advancing the variable.
 
 The problem is that the first loop consumes the 5 from the iterator
 but doesn't actually process it. That is why you need an iterator with
 push-back - so you can put the 5 back in the iterator and get it out
 again in the next loop.
 http://code.activestate.com/recipes/502304/
 Though working with indices directly might be simpler.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-26 Thread Kent Johnson
On Tue, Aug 26, 2008 at 1:36 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:

 So my test case: a Month has a 'child' attribute pointing at Week, which has
 a 'child' attribute pointing at Day, so they all know what kind of child
 instances iteration should produce. With nested loops, a Month produces one
 Week, that Week produces seven Days, then the next Week is produced, it
 makes seven more Days, etc. That much is easy.

If all you want to do with the nested Month, etc is to iterate the
events in them, you could probably use a shared iterator. It would
have to be able to push-back items so that when you hit the
out-of-range item you could push it back on the iterator.

 Then there's self.events. My original code looped over all of self.events
 for each child produced. A Month loops over its events four times, a Week
 seven times. This was the straightforward implementation, but it seemed
 inefficient. (I also, as you point out, might have been wrong about the way
 django QuerySets work). My thought was that only one loop over self.events
 should be necessary, in theory, since they're sorted by date.

Instead of direct use of the list iterator, you could pass the list
and the starting index around. Then you don't have to keep finding
your place.

 A for loop creates an iterator from a sequence and calls next() on it, and
 it creates an entirely new iterator each time you start a new for loop:

I still don't understand your code but you may have another
misconception. Calling iter() on an iterator returns the same
iterator; it does not make a new iterator that holds the same place.
You can use itertools.tee() to split an iterator if that is what you
want to do.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-26 Thread Eric Abrahamsen


On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote:


On Tue, Aug 26, 2008 at 1:36 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:

So my test case: a Month has a 'child' attribute pointing at Week,  
which has
a 'child' attribute pointing at Day, so they all know what kind of  
child
instances iteration should produce. With nested loops, a Month  
produces one
Week, that Week produces seven Days, then the next Week is  
produced, it

makes seven more Days, etc. That much is easy.


If all you want to do with the nested Month, etc is to iterate the
events in them, you could probably use a shared iterator. It would
have to be able to push-back items so that when you hit the
out-of-range item you could push it back on the iterator.


Is a 'shared iterator' something special, or do you mean all the  
instances would draw their events from a single iterator? I'm not sure  
what this would look like.





Then there's self.events. My original code looped over all of  
self.events
for each child produced. A Month loops over its events four times,  
a Week
seven times. This was the straightforward implementation, but it  
seemed
inefficient. (I also, as you point out, might have been wrong about  
the way
django QuerySets work). My thought was that only one loop over  
self.events

should be necessary, in theory, since they're sorted by date.


Instead of direct use of the list iterator, you could pass the list
and the starting index around. Then you don't have to keep finding
your place.


That's a definite possibility, I'll try it out. Itertools.tee is also  
something I've yet to look at closely. Thanks for these hints.





A for loop creates an iterator from a sequence and calls next() on  
it, and
it creates an entirely new iterator each time you start a new for  
loop:


I still don't understand your code but you may have another
misconception. Calling iter() on an iterator returns the same
iterator; it does not make a new iterator that holds the same place.
You can use itertools.tee() to split an iterator if that is what you
want to do.


Just for the sake of argument, here's the principle I'm working from:

#
 lst = range(10)
 iterlst = iter(lst)
 iterlst.next()
0
 for x in iterlst:
...   if x  5:
... print x
...   else:
... break
...
1
2
3
4
 for x in iterlst:
...   print x
...
6
7
8
9
#

So that's why I'm creating the iterator outside of the while loop in  
the original code, and then using a repeated for loop with a break to  
step through all the events only once. Of course, the fact that 5  
isn't in there probably points to the source of my problems! The  
solution might be assigning iterlist.next() to a variable, and  
advancing the variable.


Thanks,
Eric

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-26 Thread Alan Gauld

Eric Abrahamsen [EMAIL PROTECTED] wrote

So that's why I'm creating the iterator outside of the while loop in 
the original code, and then using a repeated for loop with a break 
to  step through all the events only once. Of course, the fact that 
5  isn't in there probably points to the source of my problems! The 
solution might be assigning iterlist.next() to a variable, and 
advancing the variable.


In that case wouldn't it be simpler to just use the index and
manually control its value? Iterators are wonderful things but
when I have to start bending things too far from vanilla I tend
to go back to first principles.

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-26 Thread Kent Johnson
On Tue, Aug 26, 2008 at 1:24 PM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:
 On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote:

 If all you want to do with the nested Month, etc is to iterate the
 events in them, you could probably use a shared iterator. It would
 have to be able to push-back items so that when you hit the
 out-of-range item you could push it back on the iterator.

 Is a 'shared iterator' something special, or do you mean all the instances
 would draw their events from a single iterator? I'm not sure what this would
 look like.

It's nothing special, I just mean that all instances would share an
iterator. You would pass the iterator to the iteration function.

 Just for the sake of argument, here's the principle I'm working from:

 #
 lst = range(10)
 iterlst = iter(lst)
 iterlst.next()
 0
 for x in iterlst:
 ...   if x  5:
 ... print x
 ...   else:
 ... break
 ...
 1
 2
 3
 4
 for x in iterlst:
 ...   print x
 ...
 6
 7
 8
 9
 #

 So that's why I'm creating the iterator outside of the while loop in the
 original code, and then using a repeated for loop with a break to step
 through all the events only once. Of course, the fact that 5 isn't in there
 probably points to the source of my problems! The solution might be
 assigning iterlist.next() to a variable, and advancing the variable.

The problem is that the first loop consumes the 5 from the iterator
but doesn't actually process it. That is why you need an iterator with
push-back - so you can put the 5 back in the iterator and get it out
again in the next loop.
http://code.activestate.com/recipes/502304/
Though working with indices directly might be simpler.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-25 Thread Eric Abrahamsen
Okay I think I'm onto something, more iterator-related stuff. If I can  
make self.events an iterator, then run a for loop on it, breaking out  
of the loop when the events' date attributes get too high. Then on the  
next run through, that same for loop should pick up where it left off,  
right? Here's my next version of the function. It doesn't quite work  
right: when I test it each child instance receives the correct events,  
but when it passes those events onto its children, they get consumed  
(or something) and are never actually output. To test I'm  
instantiating a Month m, filling it with events, then looping like so:


for w in m:
print w.event_count()
for d in w:
print d.events

w.event_count() produces the right event count, but d.events is always  
empty. If anyone can see what's wrong with this function...


##

def _iter_children(self, child, require_events=False):

Iterate through an object's 'child' items.

If require_events == True, only return children with
events, otherwise return all children.

iterevents = iter(self.events)
while self.sentinel  self.stop:
c = child([], self.sentinel, self.start_attr,  
rolling=self.rolling, counts_only=self.counts_only)

for e in iterevents:
if getattr(e, self.start_attr)  c.stop:
c.events.append(e)
else:
break
self.sentinel += c.dt_range
if not require_events or c.has_events():
# if require_events == True, omit empty children.
yield c



On Aug 25, 2008, at 11:49 AM, Eric Abrahamsen wrote:



On Aug 24, 2008, at 7:20 PM, Kent Johnson wrote:

Forwarding to the list with my reply. Please use Reply All to reply  
to the list.


Grr, sorry, I keep forgetting...




On Sun, Aug 24, 2008 at 1:02 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:


On Aug 23, 2008, at 11:22 PM, Kent Johnson wrote:


On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:


At first I thought the bisect module was the way to go, but it  
is too
tightly tied to integer list indices, and works very awkwardly  
when

bisecting on datetime attributes.


I'm not sure what the problem is with bisect (to find the starting
point). Your list of model elements has integer indices. I think  
you
have to write a __cmp__ method for your model class that compares  
on

the datetime attribute, then it should work. You can also create a
list of (key, model) and sort/search that.
http://www.mail-archive.com/[EMAIL PROTECTED]/msg189443.html


The __cmp__ trick is very nice, and would do it, except I won't  
have access
to the events model classes. I could get bisect to work by feeding  
it a list
comprehension, but making the high and low parameters work  
required integer

indices, which seemed like one half-hack too many...


I don't understand the issue. *All* lists have integer indices. If  
you

make a list of (key, model) pairs, the keys only need to be
comparable, not integers.


The main problem is that I don't have any control over the list of  
models, and all I've got is the name of a datetime attribute to  
filter by. The only way I could get bisect to work was like this:


index = bisect([getattr(x, attr_name) for x in model_list],  
sentinel_date)


But that loops over the whole list, which is what I was trying to  
avoid. And the only way I could provide high and low parameters to  
bisect is by calling event_list.index(event), which doesn't work on  
django querysets. I also experimented with itertools.groupby to  
produce groups of events, but that turned out to be far slower than  
simply looping over the whole event list and extracting events which  
test true for c.start = getattr(event, attr_name)  c.stop.


Ideally I could create a kind of concurrent iterator, that steps  
through children's blocks of time and the object's event list in  
tandem, rather than going over the whole events list once for every  
child produced. Maybe that's not possible... I'm pasting the whole  
function down below, just for the hell of it.


Thanks again,
Eric


def _iter_children(self, child, require_events=False):
   
   Iterate through an object's 'child' items.

   If require_events == True, only return children with
   events, otherwise return all children.
   
   while self.sentinel  self.stop:
   c = child([], self.sentinel, self.start_attr,  
rolling=self.rolling, counts_only=self.counts_only)

   for e in self.events:
   if c.start = getattr(e,self.start_attr)  c.stop:
   c.events.append(e)
   self.sentinel += c.dt_range
   if not require_events or c.has_events():
   yield c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org

Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-25 Thread Kent Johnson
I'm not following your code very well. I don't understand the
relationship between the first loop and the iter_children() function.

A couple of things that might help:
- Django QuerySets can be qualified with additional tests, so you
could have each of your month/week/etc classes have its own correctly
qualified QuerySet. This will result in one database query for each
event class, and multiple copies of the actual events.
- When you start iterating a QuerySet, it fetches all the model
instances into a list. I think you are trying to use iterators to
prevent this fetch but Django doesnt' work that way. You might as well
just use the list.
- Iterators can't be restarted, I think that is why your latest
iter_children() doesn't work as you expect.

Can you say some more about why you are doing this? Where do all the
initial constraints come from? Do you really have to be so careful to
protect against a 'madman' user? Perhaps you could set a limit on the
number of events you will retrieve and use a count() on the QuerySet
to ensure that not too many records have been fetched. Maybe you
should try a straightforward implementation and when you have
something working you can worry about making it better.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-25 Thread Eric Abrahamsen
I do apologize for the large quantities of confusing description –  
articulating the problem here has helped me understand exactly what it  
is I'm after (though it hasn't improved my code!), and I've got a  
better grasp of the problem now than I did when I first asked.


It isn't so much that I need to protect against crazy users, but that  
the pattern I'm making is very flexible, and could be used in vastly  
different ways. I want to make sure that it operates on efficient  
principles, so that people will get the best performance out of it no  
matter how they use it.


So my test case: a Month has a 'child' attribute pointing at Week,  
which has a 'child' attribute pointing at Day, so they all know what  
kind of child instances iteration should produce. With nested loops, a  
Month produces one Week, that Week produces seven Days, then the next  
Week is produced, it makes seven more Days, etc. That much is easy.


Then there's self.events. My original code looped over all of  
self.events for each child produced. A Month loops over its events  
four times, a Week seven times. This was the straightforward  
implementation, but it seemed inefficient. (I also, as you point out,  
might have been wrong about the way django QuerySets work). My thought  
was that only one loop over self.events should be necessary, in  
theory, since they're sorted by date.


A for loop creates an iterator from a sequence and calls next() on it,  
and it creates an entirely new iterator each time you start a new for  
loop: each for loop starts from the beginning of the sequence. But if  
you create your own iterator from the sequence and run a for loop on  
it, then using break to jump out of the for loop should leave the  
iterator just where you left it, since it maintains state. Doing  
another for loop on it (the next time through the date-based while  
loop), should pick up where it left off. That's why the line  
iterevents = iter(self.events) is outside of the while loop: it is  
only created once, and the loops later in the function all make use of  
the same iterator, instead of creating a new one every time.


I'm pretty sure this works in theory, because calling event_count() on  
the Weeks as they come out returns the correct number of events. But,  
for some reason, those events are not making it into the Day children.


I had originally assumed that a QuerySet pulled objects out of the  
database in a rolling fashion – ie iterating on a Month would first  
draw a Week's worth of events from the database, then another Week,  
then two more. But if it loads them all at first access, then I might  
as well just call list() on the QuerySet at object instantiation, and  
save myself some trouble.


I hope that's a little clearer. My central issue is maintaining my  
place in the self.events loop, and only advancing it as far as the  
date-based while loop advances. Whether that's possible or not...



Thanks again,
Eric

On Aug 26, 2008, at 1:12 AM, Kent Johnson wrote:


I'm not following your code very well. I don't understand the
relationship between the first loop and the iter_children() function.

A couple of things that might help:
- Django QuerySets can be qualified with additional tests, so you
could have each of your month/week/etc classes have its own correctly
qualified QuerySet. This will result in one database query for each
event class, and multiple copies of the actual events.
- When you start iterating a QuerySet, it fetches all the model
instances into a list. I think you are trying to use iterators to
prevent this fetch but Django doesnt' work that way. You might as well
just use the list.
- Iterators can't be restarted, I think that is why your latest
iter_children() doesn't work as you expect.

Can you say some more about why you are doing this? Where do all the
initial constraints come from? Do you really have to be so careful to
protect against a 'madman' user? Perhaps you could set a limit on the
number of events you will retrieve and use a count() on the QuerySet
to ensure that not too many records have been fetched. Maybe you
should try a straightforward implementation and when you have
something working you can worry about making it better.

Kent


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-24 Thread Eric Abrahamsen


On Aug 24, 2008, at 7:20 PM, Kent Johnson wrote:

Forwarding to the list with my reply. Please use Reply All to reply  
to the list.


Grr, sorry, I keep forgetting...




On Sun, Aug 24, 2008 at 1:02 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:


On Aug 23, 2008, at 11:22 PM, Kent Johnson wrote:


On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:


At first I thought the bisect module was the way to go, but it is  
too

tightly tied to integer list indices, and works very awkwardly when
bisecting on datetime attributes.


I'm not sure what the problem is with bisect (to find the starting
point). Your list of model elements has integer indices. I think you
have to write a __cmp__ method for your model class that compares on
the datetime attribute, then it should work. You can also create a
list of (key, model) and sort/search that.
http://www.mail-archive.com/[EMAIL PROTECTED]/msg189443.html


The __cmp__ trick is very nice, and would do it, except I won't  
have access
to the events model classes. I could get bisect to work by feeding  
it a list
comprehension, but making the high and low parameters work required  
integer

indices, which seemed like one half-hack too many...


I don't understand the issue. *All* lists have integer indices. If you
make a list of (key, model) pairs, the keys only need to be
comparable, not integers.


The main problem is that I don't have any control over the list of  
models, and all I've got is the name of a datetime attribute to filter  
by. The only way I could get bisect to work was like this:


index = bisect([getattr(x, attr_name) for x in model_list],  
sentinel_date)


But that loops over the whole list, which is what I was trying to  
avoid. And the only way I could provide high and low parameters to  
bisect is by calling event_list.index(event), which doesn't work on  
django querysets. I also experimented with itertools.groupby to  
produce groups of events, but that turned out to be far slower than  
simply looping over the whole event list and extracting events which  
test true for c.start = getattr(event, attr_name)  c.stop.


Ideally I could create a kind of concurrent iterator, that steps  
through children's blocks of time and the object's event list in  
tandem, rather than going over the whole events list once for every  
child produced. Maybe that's not possible... I'm pasting the whole  
function down below, just for the hell of it.


Thanks again,
Eric


def _iter_children(self, child, require_events=False):

Iterate through an object's 'child' items.

If require_events == True, only return children with
events, otherwise return all children.

while self.sentinel  self.stop:
c = child([], self.sentinel, self.start_attr,  
rolling=self.rolling, counts_only=self.counts_only)

for e in self.events:
if c.start = getattr(e,self.start_attr)  c.stop:
c.events.append(e)
self.sentinel += c.dt_range
if not require_events or c.has_events():
yield c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] __iter__ loops, partitioning list among children

2008-08-23 Thread Eric Abrahamsen

Hi,

I've got a problem that takes a bit of explaining, but it's relatively  
simple when you get down to it. This is another django-related thing,  
but the issue itself is pure python.


I made a custom class, called an EventEngine, which represents a span  
of time. You initialize it with a queryset/list of django model  
instances, and the resulting EventEngine object has an 'events'  
attribute, which is a queryset/list of model instances that fall  
within that span of time, according to a datetime attribute on the  
django model.


Next come EventEngine subclasses, representing commonly used spans of  
time – Month, Week, Day, etc. The EventEngine __iter__ method is  
overridden so that each of these subclasses, when iterated over,  
produces child instances of the next smallest EventEngine subclass.  
Iterating on a Month produces Weeks, iterating on a Week produces Days  
and so on.


As each parent produces its children, the events in the 'events'  
attribute get partitioned out to the children as appropriate to their  
date ranges. Right now I'm doing this as stupidly as possible: for  
each child 'c' in the parent, I loop over all the parent events, and  
append them to c.events if their date attribute falls within the  
child's date range:


for e in self.events:
  if c.start = getattr(e,self.start_attr)  c.stop:
  c.events.append(e)

This is stupid for (at least) two reasons: 1) it evaluates the entire  
queryset and sticks it in memory with the first child instance,  
obviating the whole point of an iterable, and 2) it loops over the  
entire event list for every child, even though the list is already  
properly sorted by date, and we could break from the loop with the  
first event that falls outside the child's date range. Performance is  
important, as some madman could initialize a Year with a huge  
queryset, and do nested iterations all the way down to Minute.


So I've got a few considerations:

1. The parent's events queryset should only be evaluated as much as is  
needed to yield one child at a time.
2. The parent's events queryset should not be duplicated as it is  
distributed among the children, ie it should make references and not  
copies (I don't know how to make sure this happens).
3. I don't want to empty the parent's 'events' list as it is  
distributed among the children, as other methods depend on the list  
being there.
4. The events attribute of the 'top level' instance is a django  
queryset, but it will be a list for all descendent instances (they can  
be nested arbitrarily deeply). This limits the number of functions  
available – ie you can't pop() a django queryset.


At first I thought the bisect module was the way to go, but it is too  
tightly tied to integer list indices, and works very awkwardly when  
bisecting on datetime attributes. List slices produce copies, unless  
I'm mistaken. Something tells me that a plain old while loop with a  
break might do the trick, but I can't quite see it clear. Ideally this  
would be something that starts iterating where the date attribute  
falls into the right range, and then stops iterating as soon as it  
passes out of that range. Probably I'll have to settle for just one or  
the other, but one can dream.


Thanks for reading all this. I'm hoping that all the restrictions and  
conditions will make the solution more obvious, rather than less  
obvious, to those who know more than I...


--Eric
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __iter__ loops, partitioning list among children

2008-08-23 Thread Kent Johnson
On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen
[EMAIL PROTECTED] wrote:
 At first I thought the bisect module was the way to go, but it is too
 tightly tied to integer list indices, and works very awkwardly when
 bisecting on datetime attributes.

I'm not sure what the problem is with bisect (to find the starting
point). Your list of model elements has integer indices. I think you
have to write a __cmp__ method for your model class that compares on
the datetime attribute, then it should work. You can also create a
list of (key, model) and sort/search that.
http://www.mail-archive.com/[EMAIL PROTECTED]/msg189443.html

 List slices produce copies, unless I'm
 mistaken.

List slices copy the references in the list, not the values. I.e. it
is not a deep copy. So you will have only one copy of each model
instance even if you slice up the list. So, unless your lists are very
large or you have many levels in your hierarchy, this might work.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] For Loops and nested loops

2008-08-16 Thread bob gailer

Umesh Singhal wrote:
Hi im still relatively new to python and i am designing a 
multiplication table that enables a user to input the size of the 
times table unfortunately ive stumbled on the nested loops this is 
what i have right now:


a=raw_input('please enter a number')
b=int(a)
n=b+1
for row in range(1, n):
 for col in range(1, n):
 print %3d  % (row * col),
 print

the input which comes out is:
  12345
  2468   10
  369   12   15
  48   12   16   20
  5   10   15   20   25

however i need something more on the lines of:
| 2 3 4 5
==
2 | 4 6 8 10
3 | 6 9 12 15
4 | 8 12 16 20
5 | 10 15 20 25

does anyone know what i need the third nested for loop to be ? to make 
it like the above example. Pleasee help me !!


I could write the program for you but I'd rather prod you into working 
it out yourself as I think you will learn more in the process.


What code would you write to generate the first line? It is a loop, but 
not nested.


At the beginning of each row you want to print the row number. What one 
statement would you add and where would you put it to do that.


BTW I would find your questions and comments easier to read if you 
divided sentences with capitalization and punctuation.


Be sure to reply-all.

--
Bob Gailer
Chapel Hill NC 
919-636-4239


When we take the time to be aware of our feelings and 
needs we have more satisfying interatctions with others.


Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] For Loops and nested loops

2008-08-16 Thread Steve Willoughby
On Sat, Aug 16, 2008 at 06:33:42AM +0100, Umesh Singhal wrote:
 Hi im still relatively new to python and i am designing a multiplication 
 table that enables a user to input the size of the times table unfortunately 
 ive stumbled on the nested loops this is what i have right now:

Is this a homework assignment?  Forgive me if it's not, but somehow
it feels like the sort of thing a teacher would assign.  At least,
I've been known to give my programming students things like it
before when they were just starting out.

 a=raw_input('please enter a number')
 b=int(a)
 n=b+1
 for row in range(1, n):

remember what n means in range(1, n).  You may have a fencepost
error (off-by-one), depending on what you intended to happen here.


-- 
Steve Willoughby|  Using billion-dollar satellites
[EMAIL PROTECTED]   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] For Loops and nested loops

2008-08-16 Thread Lie Ryan
On Sat, 2008-08-16 at 18:07 +0200, [EMAIL PROTECTED] wrote:
 Message: 1
 Date: Sat, 16 Aug 2008 06:33:42 +0100
 From: Umesh Singhal [EMAIL PROTECTED]
 Subject: [Tutor] For Loops and nested loops
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=windows-1252
 
 
 Hi im still relatively new to python and i am designing a
 multiplication table that enables a user to input the size of the
 times table unfortunately ive stumbled on the nested loops this is
 what i have right now:
 
 a=raw_input('please enter a number')
 b=int(a)
 n=b+1
 for row in range(1, n):
  for col in range(1, n):
  print %3d  % (row * col),
  print
 
 the input which comes out is:
   12345 
   2468   10 
   369   12   15 
   48   12   16   20 
   5   10   15   20   25
 
 however i need something more on the lines of:
 | 2 3 4 5
 ==
 2 | 4 6 8 10
 3 | 6 9 12 15
 4 | 8 12 16 20
 5 | 10 15 20 25
 
 does anyone know what i need the third nested for loop to be ? to make
 it like the above example. Pleasee help me !! 

You don't need to use third nested loop, your two nested loop is enough.

First, however, you need to think first, how you'd generate the output.
Following your thinking pattern, I'd do it like this:

#1
| 2 3 4 5

#2
| 2 3 4 5
==
2 |
 
#3
| 2 3 4 5
==
2 | 4

#4
| 2 3 4 5
==
2 | 4 6

#5
| 2 3 4 5
==
2 | 4 6 8

#6
| 2 3 4 5
==
2 | 4 6 8 10


#7
| 2 3 4 5
==
2 | 4 6 8 10
3 | 

#8 etc

Do you see how you could generate the table headings?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] For Loops and nested loops

2008-08-16 Thread bob gailer




PLEASE REPLY TO THE GROUP NOT JUST ME. Did you miss my request for that
(reply-all)?

Umesh Singhal wrote:

  Hi Bob,
unfortunately when i pasted in the code it seems to have gone wrong
this is how it is at the moment with the correct indentation for the
nested loop:
code:
  a=raw_input('please enter a number')
  b=int(a)
  n=b+1
  for row in range(1, n):
   for col in range(1, n):
   print "%3d " % (row *
col),
   print
I am also unaware of what code I would need to enter to enable the row
to have the value selected, if you could please tell me as I will
understand it more if i see the code infront of me
thank you 
Umesh Singhal
  

How did you get this much code written and not be able to figure that
out?

Put something like 

print "%3d |" % row, 

between the 2 for statements. 

-- 
Bob Gailer
Chapel Hill NC 
919-636-4239

When we take the time to be aware of our feelings and 
needs we have more satisfying interatctions with others.

Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loops and Modules

2007-12-06 Thread bhaaluu
Greetings,

On Dec 6, 2007 12:44 AM, earlylight publishing
[EMAIL PROTECTED] wrote:
 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.

That is a good start! Get it working first, then figure it out later. 8^D


 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.


A couple of things which may help you when you're testing/debugging
your programs:

type(object)
dir(object)

Play with those in the interactive interpreter to see what they do, for example:
 a = 7
 type(a)
type 'int'
 a = time
 type(a)
type 'str'
 import random
 dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill',
'_BuiltinMethodType', '_MethodType', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp',
'_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt',
'_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']

etc.

Another little trick I use to watch the values of variables and set breakpoints:

print variable_Name
raw_input(Pause)

I just insert those two lines after each variable I want to watch (perhaps
to see if it is actually doing what I think it is supposed to be doing?).


 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?


while True: or while 1: do the same thing, and they are a generic infinite loop.
You can use the keyword break somewhere inside the loop to break out of it.

When you figure out what condition  must be met to quit the while loop,
you can replace the True or 1 with your condition.

For example, working with the snippet you supplied:
import random
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)
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
t.start()
print 'Start with the number ', startNum, '. Then continuously add 7
to that number until the timer runs out.  You have 30 seconds.'
while 1:
answer = int(raw_input('Enter your answer: '))
if newNum == answer:
print 'That is correct!  Keep going.'
score = score + 5
print 'Your score is ', score
newNum += 7
else:
print 'That is incorrect.  Please try again.'

That isn't quite working as it should, but I only added a couple of lines
and did the requisite indentation for the while loop. It might be enough
to keep you going for a wee bit?

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] While Loops and Modules

2007-12-05 Thread earlylight publishing
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.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Infinite Loops (and threads)

2006-12-24 Thread Jonathan McManus
Hi all,

Just a quick question, really. Is there any good way to have an infinite
loop in a program, without said infinite loop eating up the CPU? I've
tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
loop, and this appears to have worked on a basic infinite loop, but this
doesn't appear to work for two separate infinite loops (in threads).

Thanks in advance.

-- 
Regards,
Jonathan McManus


signature.asc
Description: This is a digitally signed message part
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread Kent Johnson
Jonathan McManus wrote:
 Hi all,
 
 Just a quick question, really. Is there any good way to have an infinite
 loop in a program, without said infinite loop eating up the CPU? I've
 tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
 loop, and this appears to have worked on a basic infinite loop, but this
 doesn't appear to work for two separate infinite loops (in threads).

You would have to put a sleep in each thread.

Why are you using infinite loops? Are you implementing some kind of 
polling loop? Often there are better alternatives, either an event 
notification or some kind of lock. If you post some details of why you 
want to do this we may be able to help you find a better way.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread Luke Paireepinart
Kent Johnson wrote:
 Jonathan McManus wrote:
   
 Hi all,

 Just a quick question, really. Is there any good way to have an infinite
 loop in a program, without said infinite loop eating up the CPU? I've
 tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
 loop, and this appears to have worked on a basic infinite loop, but this
 doesn't appear to work for two separate infinite loops (in threads).
 

 You would have to put a sleep in each thread.

 Why are you using infinite loops? Are you implementing some kind of 
 polling loop? Often there are better alternatives, either an event 
 notification or some kind of lock. If you post some details of why you 
 want to do this we may be able to help you find a better way.

 Kent

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

   
Kent et. al.,

I'm writing something that has to do with sockets.
I need to recv any incoming packets from the socket.
I will have potentially hundreds of separate sockets open in a single 
application.
I was just going to create a thread for each, so I could receive from 
them separately.

Alternately, I figured I could read from each socket in sequence if I 
could get the recv method to not block until it gets input,
so I tried this,

#code 
self.conn.setblocking(False)
info = self.conn.recv(8000)#this should read everything.
# code

where conn is connected to another computer already,
and I get the following error:

(Verbatim except for line 3, changed to hide username/password)
Traceback (most recent call last):
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 199, in ?
toc.login('---username---','---password---')
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 116, in login
print self.getFlap()
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 93, in 
getFlap
info = self.conn.recv(8000)#this should read everything.
error: (10035, 'The socket operation could not complete without blocking')

Do I misunderstand what blocking is?
It seems to me that blocking would mainly apply to inputs.
(My understanding is that 'blocking' means when you call 'recv' it will 
return '' if it didn't receive anything.)

I'd appreciate any links that I could read up on, or any advice on how 
to make socket inputs with event notification, as Kent mentioned earlier.

Basically, as Kent said, I have a polling loop, and I am not sure what 
the alternative is to threads.

Thanks,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread Adam Bark

On 24/12/06, Luke Paireepinart [EMAIL PROTECTED] wrote:


Kent Johnson wrote:
 Jonathan McManus wrote:

 Hi all,

 Just a quick question, really. Is there any good way to have an
infinite
 loop in a program, without said infinite loop eating up the CPU? I've
 tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
 loop, and this appears to have worked on a basic infinite loop, but
this
 doesn't appear to work for two separate infinite loops (in threads).


 You would have to put a sleep in each thread.

 Why are you using infinite loops? Are you implementing some kind of
 polling loop? Often there are better alternatives, either an event
 notification or some kind of lock. If you post some details of why you
 want to do this we may be able to help you find a better way.

 Kent

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


Kent et. al.,

I'm writing something that has to do with sockets.
I need to recv any incoming packets from the socket.
I will have potentially hundreds of separate sockets open in a single
application.
I was just going to create a thread for each, so I could receive from
them separately.

Alternately, I figured I could read from each socket in sequence if I
could get the recv method to not block until it gets input,
so I tried this,

#code 
self.conn.setblocking(False)
info = self.conn.recv(8000)#this should read everything.
# code

where conn is connected to another computer already,
and I get the following error:

(Verbatim except for line 3, changed to hide username/password)
Traceback (most recent call last):
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 199, in ?
toc.login('---username---','---password---')
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 116, in
login
print self.getFlap()
  File C:\Python Scripts\AIM Connection Server\toc2.py, line 93, in
getFlap
info = self.conn.recv(8000)#this should read everything.
error: (10035, 'The socket operation could not complete without blocking')

Do I misunderstand what blocking is?
It seems to me that blocking would mainly apply to inputs.
(My understanding is that 'blocking' means when you call 'recv' it will
return '' if it didn't receive anything.)

I'd appreciate any links that I could read up on, or any advice on how
to make socket inputs with event notification, as Kent mentioned earlier.

Basically, as Kent said, I have a polling loop, and I am not sure what
the alternative is to threads.

Thanks,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Well I've been doing some networking stuff in stackless myself recently and
I would probably do something like this:

import select
import stackless
import socket

def get_data(sock):
   sock.setblocking(0)
   poller = select.poll()
   poller.register(sock, select.POLLIN)
   while True:
   if poller.poll(0):
   sock.recv(1024)
   stackless.schedule()

stackless.tasklet(get_data)(socket.socket(socket.AF_INET, socket.SOCK_DGRAM
))
stackless.run()

stackless thread things are really low on resources so you can run tens of
thousands without too much trouble.
HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread زياد بن عبدالعزيز الباتلي
Luke Paireepinart [EMAIL PROTECTED] On Sun, 24 Dec 2006 10:02:19
-0600 wrote:  Kent Johnson wrote:
 Kent et. al.,
 
 I'm writing something that has to do with sockets.
 I need to recv any incoming packets from the socket.
 I will have potentially hundreds of separate sockets open in a single 
 application.
 I was just going to create a thread for each, so I could receive from 
 them separately.
 
 Alternately, I figured I could read from each socket in sequence if I 
 could get the recv method to not block until it gets input,
 so I tried this,
 snip
 
 Thanks,
 -Luke
Use import select and read about it for more information (i.e.
help(select) within Python shell).

I advice you (and others interested in writing Python code dealing
with sockets) *very strongly* to read the following:
http://www.amk.ca/python/howto/sockets/

(Currently, I'm having trouble accessing that URL. I don't know if
it's my ISP or the the site is down.)
I hope that helps.
Ziyad.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread Kent Johnson
Luke Paireepinart wrote:

 Kent et. al.,
 
 I'm writing something that has to do with sockets.
 I need to recv any incoming packets from the socket.
 I will have potentially hundreds of separate sockets open in a single 
 application.
 I was just going to create a thread for each, so I could receive from 
 them separately.

Yes, that is one way to do it - make a thread for each socket and use 
blocking I/O. Then each thread will block until data is available. This 
avoids the kind of busy wait loop the OP described.
 
 Alternately, I figured I could read from each socket in sequence if I 
 could get the recv method to not block until it gets input,

That is another good approach. You might want to look at Twisted or 
Medusa, they are both server frameworks that use asynchronous, 
non-blocking I/O to manage multiple sockets in a single thread:
http://twistedmatrix.com/trac/
http://www.nightmare.com/medusa/

 Do I misunderstand what blocking is?
 It seems to me that blocking would mainly apply to inputs.

Usually, though output can block too.

 (My understanding is that 'blocking' means when you call 'recv' it will 
 return '' if it didn't receive anything.)

No; with a blocking socket, recv() will not return until data is 
available; with a non-blocking socket recv() will raise an exception if 
data is not available.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-12 Thread Alan Gauld
 Does python have foreach loops?  I don't see any
 mention of them in the docs.  Am I going to have to
 use Perl (gasp!) if I want my beloved foreach loop?

Its called a for loop in Python...

Or is there some extra magic in the Perl version that I'm missing?

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-12 Thread Alan Gauld
 I was thinking more along the lines of this:
 
 A C++ for loop:

This is exactly NOT a foreach loop, its a vanilla for loop.

 
 #include iostream
 
 using std::cout;
 
 int main() {
 
 for (int i = 0; i  10; i++) {
 cout  i  \n;
 }

for i in range(10): print i

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] foreach loops

2006-09-11 Thread Christopher Spears
Does python have foreach loops?  I don't see any
mention of them in the docs.  Am I going to have to
use Perl (gasp!) if I want my beloved foreach loop?

-Chris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-11 Thread Danny Yoo


 Does python have foreach loops?  I don't see any mention of them in the 
 docs.  Am I going to have to use Perl (gasp!) if I want my beloved 
 foreach loop?

Can you show an example of a Perl foreach loop?  Perhaps someone can help 
translate it into idiomatic Python.

Good luck!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-11 Thread Luke Paireepinart
Danny Yoo wrote:
   
 Does python have foreach loops?  I don't see any mention of them in the 
 docs.  Am I going to have to use Perl (gasp!) if I want my beloved 
 foreach loop?
 

 Can you show an example of a Perl foreach loop?  Perhaps someone can help 
 translate it into idiomatic Python.
   
It seems to me that foreach is the same as the python 'for' loop
#-- perl code
@myNames = ('Larry', 'Curly', 'Moe');
print Who's on the list:\n; foreach (@myNames) {
print $_ . \n;
}

#--- python code:
names = ['Larry','Curly','Moe']
print Who's on the list?\n
for x in mynames:
print x+'\n'
#

Am I missing the point here?
-Luke
 Good luck!
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-11 Thread Luke Paireepinart
Christopher Spears wrote:
 Hmmm...Perl is probably a bad example.  My apologies. 
 I was thinking more along the lines of this:

 A C++ for loop:

 #include iostream

 using std::cout;

 int main() {
   
   for (int i = 0; i  10; i++) {
   cout  i  \n;
   }
   
   return 0; 
 }

   
for i in range(10):
print i+'\n'


that does the same thing as
a = [0,1,2,3,4,5,6,7,8,9]
for i in a:
print i+'\n'

or
a = range(10)
for i in a:
print i+'\n'

Python's 'for' loop is not really meant as an iterator over a list of 
numbers
so this feature isn't built into the loop itself, you have to use the 
range function,
which just generates a list of numbers to iterate over.


Perhaps you should read an introductory Python tutorial.
Any one of them should cover the types of questions that people from 
other languages have about Python.
It sounds like you know how to program already, so the 'python for 
non-programmers' type of tutorial
may not be best-suited to you, but just look around.
If you have any more questions I'd be happy to answer them,
as would the rest of the list, I'm sure.

HTH,
-Luke

   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-11 Thread Jordan Greenberg
Christopher Spears wrote:
 Hmmm...Perl is probably a bad example.  My apologies. 
 I was thinking more along the lines of this:
 
 A C++ for loop:
 
 #include iostream
 
 using std::cout;
 
 int main() {
   
   for (int i = 0; i  10; i++) {
   cout  i  \n;
   }
   
   return 0; 
 }
 
The same functionality can be provided using python for and the range()
function, like:

for i in range(0, 10):
print i


Though because of the way python works you don't need to use this type
of loop anywhere near as often as in other languages. For example in
java (and c++, but my c++ is so rusty I'm not going embarrass myself
trying to write an example) you're constantly doing things like looping
over an array:

public void main(String[] args) {
int[] foo;

/* then later after foo has been initialized to whatever: */

for (int i=0; ifoo.length; i++) {
System.out.println(foo[i]);
}
}

The equivalent code in python is much cleaner, after foo has been
initialized to whatever:

for each in foo:
print each


Hope this helps,
Jordan Greenberg





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-12 Thread Alan Gauld
 def increment(time, seconds):
  time.seconds = time.seconds + seconds
 
  while time.seconds = 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1

Tale a look at what this loop is doing.
Think about its purpose. If you werre doing this 
with paper and pencil would you really use iteration?
Think division

 As an exercise, rewrite this function so that it
 doesn't contain any loops.
 
 I have been staring at this function and drawing a
 blank.  Something tells me that I need to use
 iteration, but I am not sure how I could implement it.

The loops are implementing a mathematical function 
which doesn't need a loop. Look at the division and 
modulo operators.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] no loops

2006-07-11 Thread Christopher Spears
I am working on another problem from How To Think
Like A Computer Scientist.  Here is a function:

def increment(time, seconds):
  time.seconds = time.seconds + seconds

  while time.seconds = 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1

  while time.minutes = 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1 

Here is the function in action:

 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
1:60:120
 increment(atime,1)
 printTime(atime)
2:2:1

Now the exercise is:
As an exercise, rewrite this function so that it
doesn't contain any loops.

I have been staring at this function and drawing a
blank.  Something tells me that I need to use
iteration, but I am not sure how I could implement it.

-Chris

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-11 Thread Gregor Lingl
Christopher Spears schrieb:

IF you know that it's 2 seconds after midnight,
how many hours, minutes, seconds after midnight ist this.

If you should compute this by hand, how would you proceed?

Best wishes,
Gregor

 I am working on another problem from How To Think
 Like A Computer Scientist.  Here is a function:

 def increment(time, seconds):
   time.seconds = time.seconds + seconds

   while time.seconds = 60:
 time.seconds = time.seconds - 60
 time.minutes = time.minutes + 1

   while time.minutes = 60:
 time.minutes = time.minutes - 60
 time.hours = time.hours + 1 

 Here is the function in action:

   
 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
 
 1:60:120
   
 increment(atime,1)
 printTime(atime)
 
 2:2:1

 Now the exercise is:
 As an exercise, rewrite this function so that it
 doesn't contain any loops.

 I have been staring at this function and drawing a
 blank.  Something tells me that I need to use
 iteration, but I am not sure how I could implement it.

 -Chris

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-11 Thread John Fouhy
On 12/07/06, Christopher Spears [EMAIL PROTECTED] wrote:
 Now the exercise is:
 As an exercise, rewrite this function so that it
 doesn't contain any loops.

 I have been staring at this function and drawing a
 blank.  Something tells me that I need to use
 iteration, but I am not sure how I could implement it.

Hi Chris,

You are using iteration.  That's what loops are :-)

Perhaps you meant to say recursion, which is where a function calls
itself.  You could solve this recursively, but I think Gregor's
comment is closer to what they want you to do.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-11 Thread Marc Poulin

--- John Fouhy [EMAIL PROTECTED] wrote:

 On 12/07/06, Christopher Spears
 [EMAIL PROTECTED] wrote:
  Now the exercise is:
  As an exercise, rewrite this function so that it
  doesn't contain any loops.
 
  I have been staring at this function and drawing a
  blank.  Something tells me that I need to use
  iteration, but I am not sure how I could implement
 it.
 
 Hi Chris,
 
 You are using iteration.  That's what loops are :-)
 
 Perhaps you meant to say recursion, which is where
 a function calls
 itself.  You could solve this recursively, but I
 think Gregor's
 comment is closer to what they want you to do.
 
 -- 
 John.

I agree with Gregor and John. What makes the problem
difficult is the fact that time is represented using 3
different units of measure: hours, minutes, and
seconds. The math becomes much simpler if you convert
the time value to a single unit (such as seconds).

But it doesn't have to be seconds. I recall seeing one
 database that stores time as fractional hours where a
minute is worth 1/60 of an hour and a second is worth
1/3600 of an hour. 

In other words, 1:15 is stored as 1.25 hours, 4:30 is
stored as 4.5 hours, and so forth. Converting from
(hours, minutes, seconds) to fractional hours is
pretty easy, but going the other way is not so simple.




__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-11 Thread Bob Gailer
Christopher Spears wrote:
 I am working on another problem from How To Think
 Like A Computer Scientist.  Here is a function:

 def increment(time, seconds):
   time.seconds = time.seconds + seconds

   while time.seconds = 60:
 time.seconds = time.seconds - 60
 time.minutes = time.minutes + 1

   while time.minutes = 60:
 time.minutes = time.minutes - 60
 time.hours = time.hours + 1 

 Here is the function in action:

   
 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
 
 1:60:120
   
 increment(atime,1)
 printTime(atime)
 
 2:2:1

 Now the exercise is:
 As an exercise, rewrite this function so that it
 doesn't contain any loops.

 I have been staring at this function and drawing a
 blank.  Something tells me that I need to use
 iteration, but I am not sure how I could implement it.
   
take a look at the divmod built-in function.
   


-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] for loops over multiple lists of the same length

2006-06-22 Thread Emily Fortuna
I feel like there should be a better way to do this process:
Can you please help?
(This is trivial example code I created off the top of my head, but the 
same concept that I am trying to do elsewhere.)

class Person(object):
def __init__(self, first_name, age, fav_color):
self.first_name = first_name
self.age = age
self.fav_color = fav_color

first_names = ['emily', 'john', 'jeremy', 'juanita']
ages = [6, 34, 1, 19]
colors = ['blue', 'orange', 'green', 'yellow']

ageIter = ages.iter()
colorIter = colors.iter()
people = [Person(name, ageIter.next(), colorIter.next()) for name in 
first_names]

print people

any suggestions, please?
Emily

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops over multiple lists of the same length

2006-06-22 Thread Kent Johnson
Emily Fortuna wrote:
 I feel like there should be a better way to do this process:
 Can you please help?
 (This is trivial example code I created off the top of my head, but the 
 same concept that I am trying to do elsewhere.)
 
 class Person(object):
   def __init__(self, first_name, age, fav_color):
   self.first_name = first_name
   self.age = age
   self.fav_color = fav_color
 
 first_names = ['emily', 'john', 'jeremy', 'juanita']
 ages = [6, 34, 1, 19]
 colors = ['blue', 'orange', 'green', 'yellow']
 
 ageIter = ages.iter()
 colorIter = colors.iter()
 people = [Person(name, ageIter.next(), colorIter.next()) for name in 
 first_names]
   
 print people
 
 any suggestions, please?

The builtin function zip() does this:
people = [Person(name, age, color) for name, age color in
zip(first_names, ages, colors)]

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops over multiple lists of the same length

2006-06-22 Thread Shantanoo Mahajan
+++ Emily Fortuna [22-06-06 13:22 -0400]:
| I feel like there should be a better way to do this process:
| Can you please help?
| (This is trivial example code I created off the top of my head, but the 
| same concept that I am trying to do elsewhere.)
| 
| class Person(object):
|   def __init__(self, first_name, age, fav_color):
|   self.first_name = first_name
|   self.age = age
|   self.fav_color = fav_color
| 
| first_names = ['emily', 'john', 'jeremy', 'juanita']
| ages = [6, 34, 1, 19]
| colors = ['blue', 'orange', 'green', 'yellow']
| 
| ageIter = ages.iter()
| colorIter = colors.iter()
| people = [Person(name, ageIter.next(), colorIter.next()) for name in 
| first_names]
|   
| print people
| 
| any suggestions, please?
| Emily

data = 
[['emily',6,'blue'],['jhon',34,'orange'],['jeremy',1,'green'],['junita',19,'yellow']]
people = [Person(name,age,color) for name,age,color in data]


Regards,
Shantanoo
-- 
Eliminate guilt. Don't fiddle expenses, taxes or benefits, and don't
cheat colleagues.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops

2006-04-11 Thread David Rock
* josip [EMAIL PROTECTED] [2006-04-11 09:13]:
   I have problem with this question.
   Can someone show me the code and than explain it?

   Write a Python program to print out the following  shape. You are 
 expected to use two for loops (these must be nested) to solve this problem.

   output:
   * * * * * 
   *  *
   *  *
   * * * * *

That looks a lot like homework.  If you have a specific question about a
_part_ of code _you_ have written, we'll be glad to help out explaining
those specifics.  

We generally try to stay away from doing the work for you :-)

-- 
David Rock
[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops

2006-04-11 Thread Alan Gauld
   Write a Python program to print out the following  shape.
   You are expected to use two for loops (these must be nested) to solve 
 this problem.

   output:
   * * * * *
   *  *
   *  *
   * * * * *

 That looks a lot like homework.

I agree and very poor homework too.
I certainly wouldn't expect to use two for loops, I'd only use one.
(And that assumes the more general problem of drawing an
arbitrary sized square, for the specific case I'd use a single print
statement and triple quoted string!)

Any homework which implies that only one design is acceptable
is a bad assignment in my book!

 We generally try to stay away from doing the work for you :-)

But the advice stays good. Tell us how far you got and what's
sticking you and we will try to help...

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loops and exceptions

2006-03-30 Thread Kent Johnson
Matthew White wrote:
 Hello,
 
From a general style and/or programmatic perspective, which is a better
 way to write this bit of code?

Hmm, neither?
 
 try:
 (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, 
 search_attrs):
 except Exception, e:
 warn_the_user(e)
 do_something_useful()
 
 for (name, data) in (dn, attrs):
 print '%s' % (name)
 for key, value in data.iteritems():
 print '%s = %s' % (key, value)

This will run the for loop even if you get an exception. I think the for 
loop is buggy, too, it is different from the one below.
 
 OR
 
 try:
 for dn, attrs in conn.search_s(search_base, search_scope, search_filter, 
 search_attrs):
 print dn
 for key, value in attrs.iteritems():
 print '\t%s = %s' % (key, value)
 print
 except Exception, e:
  warn_the_user(e)
  do_something_useful

This might be OK. It will catch exceptions in the for loop, which you 
may or may not want.

If this code is at a low level of your program, it's best to only catch 
expected exceptions, and let unexpected exceptions propagate to a higher 
level. At the higher level, you can have a generic except block that 
reports the error and moves on. This is often in a top-level loop or 
event handler. Your code has elements of both - code that does real work 
with a generic except block that reports errors.

Anyway here is a construction that is very useful for catching just the 
exceptions you expect to see from a bit of code, while running the rest 
of the code outside of the try block.

try:
 (dn, attrs) = conn.search_s(search_base, search_scope, 
search_filter, search_attrs):
except ConnectionError, e:
 warn_the_user(e)
 do_something_useful()
else:
 print dn
 for key, value in attrs.iteritems():
 print '\t%s = %s' % (key, value)
 print

The idea is to put as little code as possible in the scope of the try, 
and to catch as few exceptions as possible. If no exception is raised, 
the else: block will run. If there is an exception in that code, it will 
propagate to a higher level.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] for loops and exceptions

2006-03-29 Thread Matthew White
Hello,

From a general style and/or programmatic perspective, which is a better
way to write this bit of code?

try:
(dn, attrs) = conn.search_s(search_base, search_scope, search_filter, 
search_attrs):
except Exception, e:
warn_the_user(e)
do_something_useful()

for (name, data) in (dn, attrs):
print '%s' % (name)
for key, value in data.iteritems():
print '%s = %s' % (key, value)

OR

try:
for dn, attrs in conn.search_s(search_base, search_scope, search_filter, 
search_attrs):
print dn
for key, value in attrs.iteritems():
print '\t%s = %s' % (key, value)
print
except Exception, e:
 warn_the_user(e)
 do_something_useful


Personally I like the second method more.  To my eyes it is compact
and efficient.  Coming from a perl background I tend to like to get
very compact, which can be an impediment to code readability.  As I get
started with python I want to make sure that I don't repeat the same
mistakes and let too many perl-isms creep into my python code.

-mtw


-- 
Matthew White - District Systems Administrator
Tigard/Tualatin School District
503.431.4128

The greatest thing in this world is not so much where we are, but in
what direction we are moving.   -Oliver Wendell Holmes

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] nested loops

2005-08-22 Thread Jonas Melian
Is there any way more efficient for run a nested loop?

--
for a in list_a:
for b in list_b:
if a == b: break


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] nested loops

2005-08-22 Thread Danny Yoo


On Mon, 22 Aug 2005, Kent Johnson wrote:

  Is there any way more efficient for run a nested loop?
 
  --
  for a in list_a:
  for b in list_b:
  if a == b: break

Hi Jonas,

Depends on what we're trying to do.  Is it necessary to have a nested loop
here?  What kind of problem is this trying to solve?

If the question is: are any elements in list_a shared in list_b?, then
yes, we can avoid nested loops altogether.  If we're concerned about
efficiency, we can take advanatage of dictionaries, or use something like
the 'set' data structure.

http://www.python.org/doc/lib/module-sets.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2005-08-08 Thread Will Harris
Thanks for the help guys.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >