Any Python programers here?

Some of us love those electrons just a little too much
Post Reply
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Any Python programers here?

Post by Klast Brell »

Over the summer session I'm taking a programing class. this in an intro to programing class for people who are learning for the first time. It is not a class to teach a new language to people who already have experience programing in other languages. As such I'm dealing with learning not just the particulars of the language, but how to twist my brain in to that mode where you can see in your head how the code needs to be organized.

To my surprise I'm doing well so far. But I hit a wall with a program I am working on. The program picks a number from 1 to 100 and prompts you to guess the number. If you guess wrong it tells you to guess lower or higher until you get it right. The it congratulates you and ends. I got that part of the program working. Then I had to add a new feature. The program had to be set up so that you only had 5 guesses to get the number. Use up your guesses, and it gives you a you lose message and ends.

I got it to tell you grats you guessed the number in X tries. I got it to tell you you lost after 5 tries. But I have a problem in the code. If you guess the number right without using up your guesses it tells you you win and asks you to guess again. And again. until you use up your guesses. It's stuck making you guess 5 times whether you win or lose.

If any of you know programing, could you take a look at this code and see if you can tell me what needs to be tweaked to make it stop the guess loop after 5 tries? for the purpose of debugging sanity I changed it to guess a number between 1 and 2 in three tries.

Code: Select all

# 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 too high, too low
# or right on the money
#
#Michael Dawson - 1/8/03 - V 1.0
#
# Klast - V 2.0

import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'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.randrange(2) + 1
guess = int(raw_input("Take a guess: "))
tries = 1
# guessing loop
while tries <3:
    if (guess == the_number):
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"    
    elif (guess > the_number):
        print "Lower..."
    else:
        print "Higher..."

    guess = int(raw_input("Take a guess: "))
    tries += 1

# Results feedback
if tries >=3 :
    print "unfortunately you could not guess it in five tries"
    raw_input("\n\nPress the enter key to exit.")
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Barious
Sublime Master Elect0rzed
Posts: 389
Joined: Wed Jan 01, 2003 3:30 am

Re: Any Python programers here?

Post by Barious »

Shouldn't you just break out of your while loop if they guessed correctly?

-Barious
Baginns Hobbiton
Perfect Mastah
Posts: 94
Joined: Thu Nov 13, 2003 11:36 am

Re: Any Python programers here?

Post by Baginns Hobbiton »

Hey there,

You need to break out of the while loop if they guess correctly. I don't code in Python, so my syntax probably won't be exactly correct but I would create a Boolean variable and check it in the loop. Something like this:
Before you enter the loop declare the Boolean Variable and set its value to False

# guessing loop
while tries <3 and win = false:
if (guess == the_number):
print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"
win = true
elif (guess > the_number):
print "Lower..."
else:
print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1

# Results feedback
if tries >=3 :
print "unfortunately you could not guess it in five tries"
raw_input("\n\nPress the enter key to exit.")
Again, I'm not a python programmer so there might be an easier way to break out of the loop in that language.

PS. Text always ignores my tabs or leading spaces on the board, so I apoligize for the ugly code.
Baginns Hobbiton
Storm Warden of Karana

Finber
Level 62 Phantasmist
Companion of Areadne
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

I guess I don't know how to do that.

Should I be using a break statement in the if branches?

Hmm. what if I put an AND statement in to the while statement

while tries <3 and guess != the_number:

Then when it breaks out of the while loop follow it up with another if.

if the_number == guess:
print "you win"
else:
print "you lose"
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

Looks like that did it.!

Code: Select all

import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'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.randrange(2) + 1
guess = int(raw_input("Take a guess: "))
tries = 1
# guessing loop
while tries <3 and guess != the_number:
          
    if (guess > the_number):
        print "Lower..."
    else:
        print "Higher..."

    guess = int(raw_input("Take a guess: "))
    tries += 1

# Results feedback
if tries >=3 :
    print "unfortunately you could not guess it in five tries"
else:
    print "You guessed it! The number was", the_number
    print "And it only took you", tries, "tries!\n" 
    raw_input("\n\nPress the enter key to exit.")
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Baginns Hobbiton
Perfect Mastah
Posts: 94
Joined: Thu Nov 13, 2003 11:36 am

Re: Any Python programers here?

Post by Baginns Hobbiton »

Hey there,

Yep, that should work fine. You would basically be doing the same thing but without the need for the Boolean.
Baginns Hobbiton
Storm Warden of Karana

Finber
Level 62 Phantasmist
Companion of Areadne
User avatar
Garrdor
Damnit Jim!
Posts: 2951
Joined: Wed Dec 25, 2002 9:02 pm
Location: Oregon

Re: Any Python programers here?

Post by Garrdor »

Image
Image
Didn't your mama ever tell you not to tango with a carrot?
Ddrak
Save a Koala, deport an Australian
Posts: 17516
Joined: Thu Jan 02, 2003 3:00 pm
Location: Straya mate!
Contact:

Re: Any Python programers here?

Post by Ddrak »

On a matter of style, I'd probably move the "win" code outside the loop and figure a way to only have the "input guess" code once.

Code: Select all

    import random

    print "\tWelcome to 'Guess My Number'!"
    print "\nI'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.randrange(2) + 1
    win = False

    # guessing loop
    for tries in range(1,3):
             
        guess = int(raw_input("Take a guess: "))

        if (guess > the_number):
            print "Lower..."
        else if (guess < the_number):
            print "Higher..."
        else:
            win = True
            break

    # Results feedback
    if win:
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"
    else:
        print "unfortunately you could not guess it in five tries"

    raw_input("\n\nPress the enter key to exit.")
(note - code not tested, but that's kinda how I'd do it). If you've not learned the "for" loop yet then just substitute "while tries < 3" and put "tries += 1" somewhere there.

Dd
Image
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

haven't gotten to the for loop yet.

But I really appreciate the help. I'm sure I'll have a lot more questions for you all before the summer session is done.
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

OK I have another one for you. I got this code working, but I have a redundant line of code in it.

Code: Select all

like=raw_input("Do you like programing ? ")
like=like.lower()

while like!= "yes" and like!="no":
    like=raw_input("\nPlease type yes or no: ")
    like=like.lower()
if like == "yes":
    print "\nI’m glad you like it!"
if like == "no":
    print "\nIt will grow on you."
Like=like.lower() is the second line of code, then it is repeated as the 3rd line of the while loop.

I tried incorporating the conversion to lower case in to the input, but it errors out on me.
I tried :
like=lower(raw_input("Do you like programing ? "))
like.lower=(raw_input("Do you like programing ? "))


None of these work for me. Any thoughts on how to incorporate the conversion to lower case in to that single line of code?
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Ddrak
Save a Koala, deport an Australian
Posts: 17516
Joined: Thu Jan 02, 2003 3:00 pm
Location: Straya mate!
Contact:

Re: Any Python programers here?

Post by Ddrak »

Think of it this way - just replace what you put in for "like" into the second line:

like=raw_input("Do you like programing ? ")
like=like.lower()

which merges to:

Code: Select all

like = raw_input("Do you like programing ? ").lower()
Essentially, raw_input returns a string object, which you then call the .lower method on.

Dd
Image
Kulaf
Soverign Grand Postmaster General
Posts: 7183
Joined: Mon Nov 08, 2004 3:06 am

Re: Any Python programers here?

Post by Kulaf »

Is this a structured language in which you can call modules? If so your main program should only be a few lines and everything else should be modularized.

For instance (psuedo language):

;Variable declarations go here

;main program
Call Test
Exit

:Test
While actual_input <> desired_input
Call Input
Return

:Input
Get actual_input
Return
Ddrak
Save a Koala, deport an Australian
Posts: 17516
Joined: Thu Jan 02, 2003 3:00 pm
Location: Straya mate!
Contact:

Re: Any Python programers here?

Post by Ddrak »

Python is kinda weird like that. It's an imperative language at its core, but has an 'import' statement which draws in other files. Given you can define functions imperatively, you end up creating a program with a small "main" bit at the very end that actually does the work.

At the level Klast's working though, it tends to just be a list of commands without classes/functions defined.

Pretty cool language in some of the ideas it has (leading whitespace is significant, no strict typing, functions are first class objects, etc.) but also quite messy in implementation.

Dd
Image
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

It works. Thanks!
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

got another one for ya.this code is supposed to count the number of vowels in a string. The code mostly works. But it returns a count of vowels+1. If the message has 3 vowels it prints 4. if the message has no vowels it prints 1.
I could fix it by subtracting 1 from the initial or final value of the counter. While that would work, I still would not understand why this is happening and I would end up making the same mistake again in another program.

Can you explain to me why my counter is off by one?

Code: Select all

message = raw_input("enter a message: ").lower()

counter=0
tracker=0
total=len(message)
VOWELS = "aeiou"

while tracker <= total:
    tracker = tracker + 1
    if message[tracker-1:tracker] in VOWELS:
        counter = counter + 1

print "your message has", str(counter), "vowels"
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Kulaf
Soverign Grand Postmaster General
Posts: 7183
Joined: Mon Nov 08, 2004 3:06 am

Re: Any Python programers here?

Post by Kulaf »

Set Tracker equal to 1 in your declarations. Increment Tracker at the end of the test condition.
Ddrak
Save a Koala, deport an Australian
Posts: 17516
Joined: Thu Jan 02, 2003 3:00 pm
Location: Straya mate!
Contact:

Re: Any Python programers here?

Post by Ddrak »

The problem is the last iteration returns an empty result from the slicing operation. Kulaf's solution will work. Personally I prefer to start indexes at zero, so I'd use the following:

Code: Select all

message = raw_input("enter a message: ").lower()

counter=0
tracker=0
total=len(message)
VOWELS = "aeiou"

while tracker < total:
    if message[tracker] in VOWELS:
        counter = counter + 1
    tracker = tracker + 1

print "your message has", counter, "vowels"
Pity you don't know about the 'for' loop yet:

Code: Select all

message = raw_input("enter a message: ").lower()

counter=0
VOWELS = "aeiou"

for ch in message:
    if ch in VOWELS:
        counter = counter + 1

print "your message has", counter, "vowels"
Dd
Image
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

I do know about the for loop. The assignment was to do the program twice. Once with a while loop and once with a for loop. I did the for loop first because it was easier. My code was identical to yours Dd, except for the name of a variable.
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Klast Brell
Sublime Prince of teh Royal Sekrut Strat
Posts: 4315
Joined: Fri Dec 20, 2002 11:17 am
Location: Minneapolis MN

Re: Any Python programers here?

Post by Klast Brell »

OK I have another one. My program needs to output all 52 cards in the deck in this specific format
Ac Ad Ah As
2c 2d 2h 2s
3c 3d 3h 3s
4c 4d 4h 4s
5c 5d 5h 5s
6c 6d 6h 6s
7c 7d 7h 7s
8c 8d 8h 8s
9c 9d 9h 9s
10c 10d 10h 10s
Jc Jd Jh Js
Qc Qd Qh Qs
Kc Kd Kh Ks
This is the code I used to do it.

Code: Select all

card = ('A',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '10',
        'J',
        'Q',
        'K')
suit = ('c',
        'd',
        'h',
        's')

for x in card:
    print x+suit[0],x+suit[1],x+suit[2], x+suit[3]
Is there a way to tidy up the last line so I don't type out 4 versions of the same thing?
"A few months ago, I told the American people I did not trade arms for hostages. My heart and best intentions still tell me that's true, but the facts and evidence tell me it is not." - Ronald Reagan 1987
Bahd Zoolander
Grand Inspector Inquisitor Commander
Posts: 2636
Joined: Fri Dec 20, 2002 9:42 pm

Re: Any Python programers here?

Post by Bahd Zoolander »

Add another for loop that iterates through the suits.

Code: Select all

for x in card:
    for s in suit:
       print x+suit[s]
I'm not a python person, so I don't know if print always outputs a newline or not. If it does then what you have seems to work, or you could just add them all to a string and print it once for each line.

Code: Select all

for x in card:
    line = ""
    for s in suit:
       line += x+suit[s]
    print line
Bahd Zoolander - Transcendent - On Vacation
Post Reply