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.)
 

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] 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


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


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


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