[Tutor] Loop

2011-06-04 Thread Vincent Balmori
Hello. Right now I am learning the python language through Python Programming 
for the Absolute Beginner 3rd Edition. I am having trouble with one question in 
Ch. 3 #2, which says "Write a program that flips a coin 100 times and then 
tells 
you the number of heads and tails." Right now I am having trouble connecting 
the 
random.randint function into the loop.


# Coin

import random

# Set up Values

coin = random.randint(1,2)
tails = 0
heads = 0
if (coin == 1):
tails += 1
else:
heads += 1

toss = 0
while toss < 100:
toss += 1
coin = input(random.randint(1,2)


print("Toss Count:", count)
print("Tails:", tails)
print("Heads:", heads)

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


[Tutor] Python Beginners

2011-06-08 Thread Vincent Balmori
Hello. Right now I am learning the python language through Python Programming 
for the Absolute Beginner 3rd Edition. I am having trouble with one question in 
Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a 
hint. The player should be able to see the hint if he or she is stuck. Add a 
scoring system that rewards players who solve a jumble without asking for the 
hint'". 

Right now I am having trouble with giving the 'hint' variable a value despite 
the conditions. Everything else is working fine.

# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word

import random

# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word

# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]

# hints for each word

hint = None
if word == "python":
hint = ("It's a snake!!")
elif word == "jumble":
hint = ("Shake Those Words!")
elif word == "easy":
hint = ("Not Hard!")
elif word == "difficult":
hint = ("Not Easy!")
elif word == "answer":
hint = ("I ask a question you have an...")
elif word == "xylophone":
hint = ("Metal bars with two drum sticks")

# start the game
print(
"""
   Welcome to Word Jumble!

   Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
print("\nFor a hint, type in 'yes'. If not, type in 'no'.")
helpcount = 0
help = input("Do you need a hint?: ")
if help == "yes":
print(hint)
helpcount += 1
guess = input("\nYour guess: ")

elif help == "no":
guess = input("\nYour guess: ")

while guess != correct and guess != "":
print("Sorry, that's not it.")
guess = input("Your guess: ")
 
if guess == correct:
print("That's it!  You guessed it!")

if helpcount == 0:
print("And you didn't even need a hint! You're awesome!\n")

print("Thanks for playing.")

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


[Tutor] Q

2011-06-08 Thread Vincent Balmori
For the Absolute Beginner 3rd Edition book, I am having trouble with another 
question, which says "create a game where the computer picks a random word and 
the player must guess that word. The computer tells the player how many letters 
are in the word. Then the player gets 5 chances to ask if a letter is in the 
word. The computer can only respond with 'yes' or 'no'. The player must then 
guess the word." 

In the "Loop of Game" section of my code for some reason it gives me five more 
chances than I wanted it to. When I put two as the chance limit, it allowed 
seven. Also, the program will always say "yes" to any letter I enter, even if 
it's wrong.

#Word Guess

import random
Aquino
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word

# Getting the letter count and selection

lcount = len(correct)

LETTERS = None
if correct == "python":
LETTERS = "python"
elif correct == "jumble":
LETTERS = "jumble"
elif correct == "easy":
LETTERS = "easy"
elif correct == "difficult":
LETTERS = "difficult"
elif correct == "answer":
LETTERS = "answer"
elif correct == "xylophone":
LETTERS = "xylophone"

#Start Game
print("\n\n This word has", lcount,"letters in it.")


#Loop of Game
chances = 0
while chances < 5:
guess = input("Does the word have a: ")
for letter in correct:
if letter.lower() in LETTERS:
print("\nYes")
chances += 1
guess = input("\nDoes the word have a: ")
else:
print("\nNo")
chances += 1
guess = input("\nDoes the word have a: ")

print("\nYour chances are up!")
theguess = input("What is your guess?: ")

if theguess == correct:
print("\n\nYou did it!")
input("\n\nPress the Enter key to exit.")

else:
print("\n\nSorry the word is:", correct)
print(("Try again!"))
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


[Tutor] Lists

2011-06-10 Thread Vincent Balmori
I'm stuck on two problems from the Absolute Beginners book. The first is 
simple. 
I am trying to print all the words in the list in random order without repeats, 
but it always shows None for some reason.

#Program prints list of words in random order with no repeats

import random

#List of words

list = ["first", "second", "third", "fourth","fifth"]

#Randomize word order

order = random.shuffle(list)

#Print words in random order
print(order)

input("\n\nPress the Enter to exit")


The other question is: "Improve the program by adding a choice that lets the 
user enter a name and get back a grandfather. You should still only use one 
list 
of son-father pairs. Make sure to include several generations in list so a 
match 
can be found." The only thing I have done is adding choice 5 with its basic 
elif 
block and adding another name in each of the three sequences in the list, but I 
am completely stuck otherwise.

#User can enter name of male and name of his father will show
#Allow user to add, replace, and delete son-father pairs.
#Also have the user enter a name to get back a grandfather

#Setting values
sondad = {"Vincent": "Ramon": "Lolo","Jesus": "God": "Unknown", "Simba": 
"Mufasa": "Lion"}

choice = None
while choice != "0":

print(
"""
Who's Your Daddy?!

0 - Quit
1 - Look Up Pair
2 - Add a Pair
3 - Replace a Pair
4 - Delete a Pair
5 - Look up a Grandfather

"""
)

choice = input("Choice: ")
print()

# exit
if choice == "0":
print("Good-bye.")

# look up pair
elif choice == "1":
choice = input("Which pair do you want to look up?: ")
if choice in sondad:
dad = sondad[choice]
print("\n", choice,"is son to:", dad)
else:
print("\nSorry, I don't know", choice)

# add a father
elif choice == "2":
choice = input("Who is the son you want to add?: ")
if choice not in sondad:
dad = input("\nWho's the father?: ")
sondad[choice] = dad
print("\n", dad, "has been added.")
else:
print("\nThat pair already exists!  Try replacing them.")

# replace a father
elif choice == "3":
choice = input("Which son do you want to replace a father?: ")
if choice in sondad:
dad = input("Who's the father?: ")
sondad[choice] = dad
print("\n", choice, "has been replaced.")
else:
print("\nThey don't exist! Try adding them.")
   
# delete a pair
elif choice == "4":
choice = input("Which pair do you want to delete?: ")
if choice in sondad:
del sondad[choice]
print("\nOkay, I deleted", choice)
else:
print("\nI can't do that!", choice, "don't exist.")

# look up grandfather:
elif choice == "5":
choice = input("Who's grandfather are you looking up?: ")
if choice in sondad:
dad = sondad[choice]
print("\n", choice,"is grandson to:", dad)
else:
print("\nSorry, I don't know", choice)
   
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
  
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


[Tutor] step value

2011-06-13 Thread Vincent Balmori
I am stuck on a question for Absolute Beginner's. I googled this and there have 
been others who have not understood the question and I am also not clear on the 
question he is asking. This function is a part of a tic tac toe 
program."Improve 
the function ask_number() so that the function can be called with a step value. 
Make the default value of step 1."



def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(input(question))
return response___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Step Value

2011-06-15 Thread Vincent Balmori
I am still working on that one question in the absolute beginners with the the 
ask_number function and step value. Honestly, I still have no idea what to do. 
This is one of my many attempts, but I know that it's wrong.

def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
if response in range(low, high, 1):
  return response
while response not in range(low, high):
response = int(input(question))
return response

I tried to find clues by looking at the later section that calls on the 
ask_number function:

def human_move(board, human):
"""Get human move."""  
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
if move not in legal:
print("\nThat square is already occupied, foolish human.  Choose 
another.\n")
print("Fine...")
return move___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] step value

2011-06-15 Thread Vincent Balmori
The question to that code I am trying to solve is

"Improve the function ask_number() so that the function can be called with a 
step value. Make the default value of step 1."   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Step Value

2011-06-16 Thread Vincent Balmori
"From Steven D'Aprono:
* change the ask_number function
to accept a fourth argument;
* make it optional rather than
required;
* give it a sensible default
value;
* within the function, that value
must then be passed to range
"

Okay, I think I understand it better for the quesiton:
"Improve the function ask_number() so that the function can be called with a 
step value. Make the default value of step 1." Here is the improved function 
and the human_move function that calls it later on. The thing I am unaware of 
doing is making the step value 'optional rather than required' though.

def ask_number(question, low, high, step):
    """Ask for a number within a range."""
    step = 1
    response = None
    while response not in range(low, high, step):
        response = int(input(question))
    return response

def human_move(board, human):
    """Get human move."""  
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES, 1)
        if move not in legal:
            print("\nThat square is already occupied, foolish human.  Choose 
another.\n")
    print("Fine...")
    return move    ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Step Value

2011-06-16 Thread Vincent Balmori
"def spam(n=3):
    """Return n slices of yummy spam."""
    return "spam "*n

And here it is in use:

>>> spam(4)
'spam spam spam spam '
>>> spam()  # just use the default
'spam spam spam '

Can you see what I did to set the default value for n? Read the function 
definition line "def spam... " carefully.

-- Steven"

This is my new code for a default step value based on your feedback Steve:

def ask_number(question, low, high, step):
    """Ask for a number within a range."""
    response = None
    if step == None:
        step = 1
    while response not in range(low, high, step):
        response = int(input(question))
    return response
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Step Value

2011-06-17 Thread Vincent Balmori

Here is my updated code. As simple as this may be, I am a little lost again.
I appreciate the help and explanations to try to push me to get this on my
own, but at this point (especially after one week) this is when me being
given the answer with an explanation will help me much more, so I can
understand how it works better.

def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response = None
while response not in range(low, high, step):
response = int(input(question))
return response

-Vincent


Alan Gauld wrote:
> 
> 
> "Vincent Balmori"  wrote
> 
> "def spam(n=3):
> """Return n slices of yummy spam."""
> return "spam "*n
> 
> 
>> This is my new code for a default step value based on your feedback 
>> Steve:
>>
>> def ask_number(question, low, high, step):
>>  """Ask for a number within a range."""
>>   response = None
>>   if step == None:
>>   step = 1
> 
> Nope, you are still missing the point.
> Look again at how Steven defined his function.
> What is different about his definition of n and your definition of 
> step?
> 
> 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
> 
> 

-- 
View this message in context: 
http://old.nabble.com/-Tutor--Step-Value-tp31865967p31871108.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Main Function

2011-06-17 Thread Vincent Balmori

I answered another question that says "Modify the guess_number program so
that the program's code is in a function called main(). Don't forget to call
main() so you can play the game." It seems to be working fine, but I would
like to have a second opinion if there was a better way to put it together.

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

import random  

def display_instruct():
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 10.")
print("Try to guess it in as few attempts as possible.\n")

# set ask_number function 
def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response =  None
while response not in range(low, high, step):
response = int(input(question))
return response

# guessing loop
def num():
# set the initial values
the_number = random.randint(1, 10)
tries = 0
guess = None
while guess != the_number and tries < 4:
guess = ask_number("Take a guess:", 1, 10)
if guess > the_number:
print("Lower...")
else:
print("Higher...")
tries += 1

if tries == 4:
print("\nYou fail!")
input("\n\nPress the enter key to exit.")
break

while guess == the_number:
print("\nYou guessed it!  The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
break

def main():
display_instruct()
num()
  
# start the program
main()
input("\n\nPress the enter key to quit.")
-- 
View this message in context: 
http://old.nabble.com/Main-Function-tp31873480p31873480.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Trivia

2011-06-23 Thread Vincent Balmori

I have to improve the trivia_challenge program so each question has a
different point value. I added a point into the text file after each
category line, so the next_block() can call it. Whenever the program
calculates the 'score = point' in main() it comes up with "TypeError:
unsupported operand type(s) for +=: 'int' and 'str' " The problem is I am
having trouble changing "point = next_line(the_file)" in the next_block() to
be an int type. 

http://old.nabble.com/file/p31917610/trivia_challenge2.py
trivia_challenge2.py 

http://old.nabble.com/file/p31917610/trivia.txt trivia.txt 



-- 
View this message in context: 
http://old.nabble.com/Trivia-tp31917610p31917610.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Trivia

2011-06-23 Thread Vincent Balmori

***ignore the "point = point" line in the next_block() function.
-- 
View this message in context: 
http://old.nabble.com/Trivia-tp31917610p31917637.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Trivia

2011-06-23 Thread Vincent Balmori

<<>>


It's working fine now with the scoring, but now at the end of the program
for some reason I get this error message:

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
line 83, in 
main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
line 76, in main
category, point, question, answers, correct, explanation =
next_block(trivia_file)
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
line 27, in next_block
point = int(next_line(the_file))
ValueError: invalid literal for int() with base 10: ''
-- 
View this message in context: 
http://old.nabble.com/Trivia-tp31917610p31917701.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Trivia

2011-06-24 Thread Vincent Balmori

"Your whole approach is very fragile in this respect, it only 
takes one small mistake in the data to wreck your program,. 
Somethjing like a config file format would be much more 
robust (and readable) the config reader module would make 
sure you got what you expected back. "

Can you please explain more on what you mean by this?


Alan Gauld wrote:
> 
> 
> "Vincent Balmori"  wrote
> 
>> It's working fine now with the scoring, but now at the end of the 
>> program
>> for some reason I get this error message:
>>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
>> line 27, in next_block
>>point = int(next_line(the_file))
>> ValueError: invalid literal for int() with base 10: ''
> 
> Thats because after the last question you try to read another
> block and don't check anywhere whether you actually read
> anything. Your next_block code just assumes there will
> always be valid data there, but at the end of the file there
> won't be. You get away with category being blank
> because replace() doesn't complain. But int() does.
> 
> Your whole approach is very fragile in this respect, it only
> takes one small mistake in the data to wreck your program,.
> Somethjing like a config file format would be much more
> robust (and readable) the config reader module would make
> sure you got what you expected back.
> 
> 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
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Trivia-tp31917610p31917979.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Television

2011-06-25 Thread Vincent Balmori

The question for this is to make a program that simulates a TV by creating it
as an object. The user should be able to to enter a channel and or raise a
volume. Make sure that the Channel Number and Volume stay within valid
ranges. Before I can even start correcting my code this error shows up. I
thought I had already created the "tv" instance.
http://old.nabble.com/file/p31925053/Television Television 

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television",
line 83, in 
main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television",
line 46, in main
print(Television(tv.display))
NameError: global name 'tv' is not defined


-- 
View this message in context: 
http://old.nabble.com/Television-tp31925053p31925053.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Television

2011-06-25 Thread Vincent Balmori

It's working better now. The problem I have left is that I have to set the
channel and volume values in a range (for both I intend for 0-10). I thought
the range() would be the choice, but probably I'm not using it right.
Another one is for the tv.channel to hold a new value instead of just
adding/subtracting the value and the only way I can think how is to use a
list and then have the function replace the value each time. I'm sure there
is a better way though.
http://old.nabble.com/file/p31928968/TV TV 


Alan Gauld wrote:
> 
> 
> "Vincent Balmori"  wrote
> 
>> Before I can even start correcting my code this error shows up.
> 
> You will find it much easier to write programns if you do
> not write out the whole program and then try to debug it!
> Just write a single method at a time and get that working
> before trying to debug a whole complex aopplication.
> 
> This code is fuill of errors whicvh will continually prevent
> you from running the code. I'll highlight a few. But as I
> said in your previous thread, you really need to read
> some more about the basics because your errors reveal
> a deep gap in your understanding of  variables, data types
> and their operations. Only once you undertsand that thoroughly
> will you be successful with classes and objects, because
> in OOP you are defining new data types and operations.
> If you can't use the standard types you have little hope
> of using newly defined ones!
> 
> Some examples:
> 
> class Television(object):
> def __init__(tv, channel = range(0,10), volume = range(0,10)):
> tv.channel = channel
> tv.volume = volume
> def cha(tv, level = 1):
> while 0 >= tv.channel <=10:
> 
> Here you store two range objects as your channel and
> volume attributes in init (In Python v 2 these would be
> lists but in Python 3 they are range objects).
> Then in cha() you try to compare them to a number,
> that won't work, they are incompatible types.
> Later you try to increment channel which agaion won't
> work. (And why you only increment channel and never
> decrement is a puzzle - and you ignore the level value
> read from the user?)
> 
> Similar applies in volu() except you have two methods,
> one up one down. But you are still trying to apply
> integer operations to range objects.
> 
> 
> In various places you do this:
> 
>   if level > 10:
> int(input("\n That's too much! Choose another number?: "))
> 
> The user input is read, converted to an int then thrown away.
> You need to store it in a variable.
> 
> Finally we come to the error message, it is in main():
> 
> def main():
> print(Television(tv.display))
> choice = None  Notice you do not create a tv instance. You try to 
> print an instance but in creating it you try to passs tv.display to 
> the constructor, but tv does not exist aty that point. And even if you 
> did succeed the instance would be immediately destroyed again because 
> you are not storing it in a variable. You need to go back to basic 
> data types and understand that concept. There is clearly something 
> missing at the moment since you jkeep making the same mistakes over 
> and over again.> thought I had already created the "tv" instance.> 
> http://old.nabble.com/file/p31925053/Television Television You defined 
> a class. You tried to create an instance of the class inside the print 
> statement, but it nevergot that far.Try reading my tutorial topic on 
> data - The Raw Materials - and then the OOP topic. Then go back to 
> whatever tutorial you are currently following and see if it helps.--  
> Alan GauldAuthor of the Learn to Program web 
> sitehttp://www.alan-g.me.uk/ 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Television-tp31925053p31928968.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Television

2011-06-26 Thread Vincent Balmori

I made in elif statement for the channel changer that works for it, but the
volume systems system boundary does not the way I want it to. If the volume
is 2 and I lower it by a value of 5, it will accept the volume at a negative
number thus going past the boundary. The vice-versa for the high boundary as
well.

http://old.nabble.com/file/p31932639/TV.py TV.py 


Noah Hall-3 wrote:
> 
> On Sun, Jun 26, 2011 at 2:02 AM, Vincent Balmori
>  wrote:
>>
>> It's working better now. The problem I have left is that I have to set
>> the
>> channel and volume values in a range (for both I intend for 0-10). I
>> thought
>> the range() would be the choice, but probably I'm not using it right.
> 
> I think the best way to do this is probably to set two properties -
> tv.channel_boundary and tv.volume_boundary, this is presuming that you
> don't want to allow the lower boundary to be changed. If you do,
> create an upper and lower boundary variable for each.
> 
>>def channel_remote(tv, level = 1):
>>if tv.channel in range(0,10):
> 
> Here, it'd be better if you used
> if tv.channel < 10:
> 
> That way you're not wasting a whole list and a list search just to
> test if something is less than ten.
> Using the boundaries, that would be
> if tv.channel < tv.channel_boundary:
> 
> There's also no need for this, not here, anyway. You should be testing
> in __init__, where the channel can be set incorrectly.
> 
>>level = int(input("\n Which channel do you want to go up to:
>> "))
> 
> Why have this when you allow level as an argument? It's a waste.
> 
>>if 0 > level > 10:
>>int(input("\n That's not valid! Choose another channel:
>> "))
>>else:
>>tv.channel += level
> 
> This is your second problem you've found, I guess?
> Well, how about this
> tv.channel = level
> Easy, right? :)
> 
>>print("\n The channel is now:", tv.channel)
> 
> 
>> Another one is for the tv.channel to hold a new value instead of just
>> adding/subtracting the value and the only way I can think how is to use a
>> list and then have the function replace the value each time. I'm sure
>> there
>> is a better way though.
>> http://old.nabble.com/file/p31928968/TV TV
> 
> 
> HTH
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Television-tp31925053p31932639.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Critter

2011-06-26 Thread Vincent Balmori

I'm on the Critter Caretake problem that involves handling more than one
critter. I have looked At David Merrick's threads for some answers, but the
difference is that he created a whole new class to handle it, while I only
made more critter objects. The only problem I have left is to have my
actions (play and eat) apply to all my creatures ALL AT ONCE, instead of one
at a time like it is in my code right now. 
http://old.nabble.com/file/p31933791/critter_caretaker3.py
critter_caretaker3.py 




-- 
View this message in context: 
http://old.nabble.com/Critter-tp31933791p31933791.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Critter

2011-06-27 Thread Vincent Balmori

Last thing I need to do solve is the __str__ problem. I can print the name
fine, but everytime I try to put in the self.hunger and self.boredom values
I get:

TypeError: Can't convert 'int' object to str implicitly

http://old.nabble.com/file/p31940427/critter_caretaker3.py
critter_caretaker3.py 
Alan Gauld wrote:
> 
> 
> "Vincent Balmori"  wrote
> 
>> I'm on the Critter Caretake problem that involves handling more than 
>> one
>> critter. I have looked At David Merrick's threads for some answers,
> 
> Given that David hasn't solved the problem yet that may not
> be the best source! :-)
> 
>> difference is that he created a whole new class to handle it,
> 
> He has now reverted to a simple list.
> 
>> made more critter objects. The only problem I have left is to have 
>> my
>> actions (play and eat) apply to all my creatures ALL AT ONCE, 
>> instead of one
>> at a time like it is in my code right now.
> 
> You can't. You can only apply the methods to one critter at a time.
> You can write code to wrap it all up into a convenient single call,
> but that code will still need to call each item separately. There is
> no such thing as a "call all" mechanism in Python.
> 
> BTW, You have the same issue as David with __str__.
> __str__() should return a string, it should not print anything itself.
> If you sdo that you can then, in your main code write
> 
> print(crit1)
> 
> instead of
> 
> crit1.__str__()
> 
> This makes using objects much more like using other data types.
> 
> Also in your init method:
> 
> def __init__(self, name, hunger = 0, boredom = 0):
> hunger = random.randint(0,15)
> boredom = random.randint(0,15)
> 
> These two lines mean you throw away the values being
> passed in to the constructor, so you might as well not
> have them. And...
> 
> self.name = name
> self.hunger = hunger
> self.boredom = boredom
> 
> Since you just assign them to the attributes you might as well
> just do the call to randint() here and delete the first two lines
> completely.
> 
> Finally in play()
> 
> def play(self, fun = 4):
> while self.boredom >= 3:
> fun = int(input("\n How long do you want to play?: "))
> if fun > 5:
> int(input("\n How long do you want to play?: "))
> 
> You ignore the value of fun passed into the method.
> (And in your code never pass a value) So again you could
> just lose the fun parameter.
> 
> Then if fun > 5 you ask the user for a value, convert it to an
> int then throw it away so it does no good. You probably should
> assign the new value to fun.
> 
> 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
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Critter-tp31933791p31940427.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] War: The Card Game

2011-06-30 Thread Vincent Balmori

I am working on the card game of war challenge where each player is given a
single card and the highest value wins. I keep getting a Type Error since
for the moment since the values of the cards cannot be compared due to their
types. I am thinking of creating a Card_Value class that will give each rank
and suit a certain value. If there is also a more elegant way of handling
some of the code in the main section that will be welcome.

http://old.nabble.com/file/p31961149/war.py war.py 
-- 
View this message in context: 
http://old.nabble.com/War%3A-The-Card-Game-tp31961149p31961149.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Blackjack Betting

2011-06-30 Thread Vincent Balmori

I have been working on another challenge that involves improving the
Blackjack program so the players can wager an amount. If a player loses they
will be removed from the game.  I keep getting the error: “NameError: global
name 'bet' is not defined.” I know I came across this error before in a
previous thread, but I am confused on how to solve this, since I am also
trying to juggle it with inherited methods at the same time. Here is the old
and new file for the blackjack program for comparison:

http://old.nabble.com/file/p31966195/blackjack.py blackjack.py 
http://old.nabble.com/file/p31966195/blackjackbetting.py blackjackbetting.py 
-- 
View this message in context: 
http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Blackjack Betting

2011-07-01 Thread Vincent Balmori

Sorry. Here is the entire Error stack if this can help.

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 240, in 
main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 236, in main
game.play()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 204, in play
player.win()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 129, in win
bet.stash += bet.wager



Prasad, Ramit wrote:
> 
>>I keep getting the error: “NameError: global
>>name 'bet' is not defined.” I know I came across this error before in a
>>previous thread, but I am confused on how to solve this, since I am also
>>trying to juggle it with inherited methods at the same time.
> 
> Telling us this without the stack trace is pretty unhelpful. The Python
> exceptions include a very good stack trace (with line numbers +- 1 line)
> and a decent description. This error means that wherever this error was
> raised was a reference to the name "bet" and it had no reference to any
> "bet" at that point. The reasons could be that you forgot to assign a
> value to the name first, maybe it was a typo, in a preceding function,
> forgot the reference to self, etc, etc.
> 
> I took a *quick* look at the code and found this (I did not check for
> other problems or if this error happens in more than one place):
> 
> 
> class BJ_Player(BJ_Hand, Bet):
> """ A Blackjack Player. """
> def is_hitting(self):
> response = games.ask_yes_no("\n" + self.name + ", do you want a
> hit? (Y/N): ")
> return response == "y"
> 
> def bust(self):
> print(self.name, "busts.")
> self.lose()
> 
> def lose(self):
> print(self.name, "loses.")
> betting = Bet()
> bet.stash -= bet.wager
> 
> def win(self):
> print(self.name, "wins.")
> bet = Bet()
> bet.stash += bet.wager
> 
> def push(self):
> print(self.name, "pushes.")
> 
> 
> There are a couple things wrong with this class. First, you never define
> an __init__ which might be technically okay but is unlikely to be what you
> want for any user defined class (especially one with multiple
> inheritance). Since there is no __init__ defined, it will call the first
> parent class BJ_Hand.__init__ but not the second parent class Bet.__init__
> (if it has one). 
> 
> Next for BJ_Player.lose(), bet is never defined and thus neither is
> bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you
> ran lint/pylint on this module it would have told you the error without
> even having to run it.
> 
> 
> Ramit
> 
> 
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
> 
> 
> 
> -Original Message-
> From: tutor-bounces+ramit.prasad=jpmchase@python.org
> [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of
> Vincent Balmori
> Sent: Thursday, June 30, 2011 1:49 PM
> To: tutor@python.org
> Subject: [Tutor] Blackjack Betting
> 
> 
> I have been working on another challenge that involves improving the
> Blackjack program so the players can wager an amount. If a player loses
> they
> will be removed from the game.  I keep getting the error: “NameError:
> global
> name 'bet' is not defined.” I know I came across this error before in a
> previous thread, but I am confused on how to solve this, since I am also
> trying to juggle it with inherited methods at the same time. Here is the
> old
> and new file for the blackjack program for comparison:
> 
> http://old.nabble.com/file/p31966195/blackjack.py blackjack.py 
> http://old.nabble.com/file/p31966195/blackjackbetting.py
> blackjackbetting.py 
> -- 
> View this message in context:
> http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information

Re: [Tutor] Blackjack Betting

2011-07-01 Thread Vincent Balmori

Here is the other one that occurs when I lose

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 240, in 
main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 236, in main
game.play()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 211, in play
player.lose()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 124, in lose
bet.stash -= bet.wager
NameError: global name 'bet' is not defined


Prasad, Ramit wrote:
> 
>>I keep getting the error: “NameError: global
>>name 'bet' is not defined.” I know I came across this error before in a
>>previous thread, but I am confused on how to solve this, since I am also
>>trying to juggle it with inherited methods at the same time.
> 
> Telling us this without the stack trace is pretty unhelpful. The Python
> exceptions include a very good stack trace (with line numbers +- 1 line)
> and a decent description. This error means that wherever this error was
> raised was a reference to the name "bet" and it had no reference to any
> "bet" at that point. The reasons could be that you forgot to assign a
> value to the name first, maybe it was a typo, in a preceding function,
> forgot the reference to self, etc, etc.
> 
> I took a *quick* look at the code and found this (I did not check for
> other problems or if this error happens in more than one place):
> 
> 
> class BJ_Player(BJ_Hand, Bet):
> """ A Blackjack Player. """
> def is_hitting(self):
> response = games.ask_yes_no("\n" + self.name + ", do you want a
> hit? (Y/N): ")
> return response == "y"
> 
> def bust(self):
> print(self.name, "busts.")
> self.lose()
> 
> def lose(self):
> print(self.name, "loses.")
> betting = Bet()
> bet.stash -= bet.wager
> 
> def win(self):
> print(self.name, "wins.")
> bet = Bet()
> bet.stash += bet.wager
> 
> def push(self):
> print(self.name, "pushes.")
> 
> 
> There are a couple things wrong with this class. First, you never define
> an __init__ which might be technically okay but is unlikely to be what you
> want for any user defined class (especially one with multiple
> inheritance). Since there is no __init__ defined, it will call the first
> parent class BJ_Hand.__init__ but not the second parent class Bet.__init__
> (if it has one). 
> 
> Next for BJ_Player.lose(), bet is never defined and thus neither is
> bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you
> ran lint/pylint on this module it would have told you the error without
> even having to run it.
> 
> 
> Ramit
> 
> 
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
> 
> 
> 
> -Original Message-
> From: tutor-bounces+ramit.prasad=jpmchase@python.org
> [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of
> Vincent Balmori
> Sent: Thursday, June 30, 2011 1:49 PM
> To: tutor@python.org
> Subject: [Tutor] Blackjack Betting
> 
> 
> I have been working on another challenge that involves improving the
> Blackjack program so the players can wager an amount. If a player loses
> they
> will be removed from the game.  I keep getting the error: “NameError:
> global
> name 'bet' is not defined.” I know I came across this error before in a
> previous thread, but I am confused on how to solve this, since I am also
> trying to juggle it with inherited methods at the same time. Here is the
> old
> and new file for the blackjack program for comparison:
> 
> http://old.nabble.com/file/p31966195/blackjack.py blackjack.py 
> http://old.nabble.com/file/p31966195/blackjackbetting.py
> blackjackbetting.py 
> -- 
> View this message in context:
> http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transactio

Re: [Tutor] Blackjack Betting

2011-07-01 Thread Vincent Balmori

I was able to get the program started without errors now. What is left now is
to: 

Having the stash change after winning and losing. No matter what, the value
in stash stays the same. The conditional statement I made which prevents
players with no money from playing is dependent on this.

After each game when I choose to play again, the betting options do not come
up again before the cards are drawn.

Apply the betting option to more than one player the same way each player
can choose to hit. I think the key involves modifying the init function in
class BJ_Game, where it adds the number of players and names.

http://old.nabble.com/file/p31977263/blackjackbetting.py blackjackbetting.py 




Emile van Sebille wrote:
> 
> On 7/1/2011 12:51 AM Andre Engels said...
> 
>> In this case, the error message says:
>>
>> NameError: global name 'bet' is not defined
> 
> Note use of the term global?
> 
>>
>> That means, at some time at the program, it is told to do something with
>> 'bet', but there is no variable bet. And when does that happen? That too
>> is told: at line 124, which says:
>>
>> bet.stash -= bet.wager
>>
>> Go to that line and read your code yourself - what is this 'bet' of
>> which the stash is to be lessened by its wager? Have you told your
>> program that this is the value of the variable 'bet'? Where and how?
> 
> Further, because global is used, it tells you that 'bet' is not in the 
> local scope, nor in the global scope.  Python's general scoping 
> resolution rule is local-global-builtin.  So bet, wherever you think it 
> may be defined, lives in a different namespace.
> 
> See http://docs.python.org/tutorial/classes.html
> 
> Emile
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Blackjack-Betting-tp31966195p31977263.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Blackjack Betting

2011-07-01 Thread Vincent Balmori

Also I must be doing something wrong if I have to enter a "bet = Bet()" into
each function where it is used. I tried putting Bet into the other classes'
arguments but it did not have any effect.


Emile van Sebille wrote:
> 
> On 7/1/2011 12:51 AM Andre Engels said...
> 
>> In this case, the error message says:
>>
>> NameError: global name 'bet' is not defined
> 
> Note use of the term global?
> 
>>
>> That means, at some time at the program, it is told to do something with
>> 'bet', but there is no variable bet. And when does that happen? That too
>> is told: at line 124, which says:
>>
>> bet.stash -= bet.wager
>>
>> Go to that line and read your code yourself - what is this 'bet' of
>> which the stash is to be lessened by its wager? Have you told your
>> program that this is the value of the variable 'bet'? Where and how?
> 
> Further, because global is used, it tells you that 'bet' is not in the 
> local scope, nor in the global scope.  Python's general scoping 
> resolution rule is local-global-builtin.  So bet, wherever you think it 
> may be defined, lives in a different namespace.
> 
> See http://docs.python.org/tutorial/classes.html
> 
> Emile
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Blackjack-Betting-tp31966195p31977301.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


[Tutor] Use __str__ method for int values

2013-03-10 Thread Vincent Balmori
I am trying to use a __str__ method to display the values of attribute mood = 
self.hunger + self. boredom.
When I try to execute I get this error:

Traceback (most recent call last):
  File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for 
the Absolute Beginner - Project 
Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in 
    main()
  File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for 
the Absolute Beginner - Project 
Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main
    print(crit)
TypeError: __str__ returned non-string (type int)


This is the code:


# Critter Caretaker
# A virtual pet to care for

import random

class Critter(object):

    """A virtual pet"""
    def __init__(self, name, hunger = 0, boredom = 0):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger += 1
        self.boredom += 1

    def __str__(self):
        mood = self.boredom + self.hunger
        return mood

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness < 5:
            m = "happy"
        elif 5 <= unhappiness <= 10:
            m = "okay"
        elif 11 <= unhappiness <= 15:
            m = "frustrated"
        else:
            m = "mad"
        return m
    
    def talk(self):
        print("I'm", self.name, "and I feel", self.mood, "now.\n")
        self.__pass_time()
    
    def eat(self, food = 4):
        food = int(input("How much do you want to feed?: "))
        while food > 5:
            food = int(input("That's too much! How much do you want to feed?: 
"))
        print("Brruppp.  Thank you.")
        self.hunger -= food
        self.boredom += int(food * random.randint(0,3))
        if self.hunger < 0:
            self.hunger = 0
        self.__pass_time()

    def play(self, fun = 4):
        fun = int(input("How long do you want to play?: "))
        while fun > 5:
            fun = int(input("That's too long! How long do you want to play?: "))
        print("Wheee!")
        self.boredom -= fun
        self.hunger += int(fun * random.randint(0,3))
        if self.boredom < 0:
            self.boredom = 0
        self.__pass_time()


def main():
    crit_name = input("What do you want to name your critter?: ")
    crit = Critter(crit_name)

    choice = None  
    while choice != "0":
        print \
        ("""
        Critter Caretaker
    
        0 - Quit
        1 - Listen to your critter
        2 - Feed your critter
        3 - Play with your critter
        """)
    
        choice = input("Choice: ")
        print()

        # exit
        if choice == "0":
            print("Good-bye.")

        # listen to your critter
        elif choice == "1":
            crit.talk()
        
        # feed your critter
        elif choice == "2":
            crit.eat()
         
        # play with your critter
        elif choice == "3":
            crit.play()
              
        # play with your critter
        elif choice == "4":
            print(crit)

        # some unknown choice
        else:
            print("\nSorry, but", choice, "isn't a valid choice.")

main()
("\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


[Tutor] Loop Exception Handles

2013-03-15 Thread Vincent Balmori
I am trying to loop a simple exception. I tried to put a while loop, but I keep 
getting syntax issues. I also tried to alternatively use something on the lines 
of "while number != int" also with no avail.   

def main():
    print("\t\tWelcome to Blackjack!\n")
    
    names = []
    try:
        number = games.ask_number("How many players? (1 - 7): ", low = 1, high 
= 8)
    except (ValueError, TypeError):
        print("That is not a number!")
        number = games.ask_number("How many players? (1 - 7): ", low = 1, high 
= 8)
        continue
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)
    print()___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor