10 Replies - 796 Views - Last Post: 12 January 2013 - 10:39 PM Rate Topic: -----

#1 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Python school project help

Posted 29 November 2012 - 01:18 PM

Hello, I have written most of my program with succession but I have come across an issue where I try one method and I get a TypeError and another method in which I get an invalid syntax error. The program is a word scramble game and after two incorrect guesses, the program provides a hint in which comes from a dictionary of words. I haven't worked with the dictionary much and I'm not sure how to implement printing out the value of the key in the dictionary. My code is pretty simple and I have commented the program a good bit. I have also sent my program to my professor to see if he could help out but he doesn't always reply in time and my program is due at midnight tonight. Along with the help, if you have any suggestions for my program to make it better, I'd love to hear it. I am by no means requesting anybody to do the homework for me, only help in understanding how to implement the value and recommendations.

Thanks

#Program name - COP 1000 Project 5
#Author - Charles Goggins
#Date - 11/8/2012
#Description: This program takes a word from a list and displays it to the
#player scrambled up. The player will have three chances to guess the word,
#after two incorrect guesses the program will provide the player with a hit
#to help him/her out.

#Algorithm:
#   1. Print COP 1000 header with introduction
#   2. Generate random word for scramblin'
#   3. Display scrambled word to player
#   4. Prompt player for guess #1
#       a. If guess incorrect, print sorry, incorrect message
#       b. If guess correct print good job message and go to step 7
#   5. Prompt player for guess #2
#       a. If guess incorrect, print sorry, incorrect message and provide hint
#       b. If guess correct print good job message and go to step 7
#   6. Prompt player for guess #3
#       a. If guess incorrect, print sorry, this is incorrect and provide word
#       b. If guess correct print good job message and go to step 7
#   7. Ask player if he/she would like to play again and return to step 1


#Imports the random module from the Python library
import random  

#Creates a dictionary for the words
words = {'frisbee':'Something that spins after being thrown', 
         'xbox':'A popular game console',
         'school':'A place where you go to learn',
         'hamster':'A pet',
         'toyota':'A brand of cars and trucks'}


#Function that prints the COP 1000 line and briefly explains the game
def Intro():
    print('COP 1000 Project 5 - Charles Goggins')

    print('I\'m going to show you a scrambled word and give you three guesses.')
    print('After your second guess, I\'ll help by giving you a hint.')
    

#Selects a word from the dictionary at random and returns it it's caller
def getWord(word):
    wordKey = random.choice(list(word.keys()))
    return wordKey

#When the player types HELPME in the guess prompt, the program will provide a hint
def getHint():
    hint = len(wordKey.index)
    return hint

#Gets the first guess from the player, also ensures only characters are entered
def getGuess1():
    print('Enter your first guess: ', end = '')
    guess = input()
    while True:
        if guess.isalpha():
            return guess
        else:
            if guess.isdigit():
                print('Please enter a letter:', end = '')
                guess = input()

#Does the same as getGuess1() but gets the player's second guess only if he/she didn't guess correctly the first time              
def getGuess2():
    print('Enter your second guess: ', end = '')
    guess = input()
    while True:
        if guess.isalpha():
            return guess
        else:
            if guess.isdigit():
                print('Please enter a letter:', end = '')
                guess = input()

#==============================================================MAIN PROGRAM===============================================#

#Initializes some varibles, ans = 'y' is for the play again loop
ans = 'y'
guesses = 0
while ans == 'y':

    #Calls the getWord() function
    w0rd = getWord(words)
    #Turns w0rd into a list to enable scrambling
    scramWord = list(w0rd)
    #Scrambles the word
    random.shuffle(scramWord)
    #Joins the scrambled word together to be able to display it
    sWord = ''.join(scramWord)

    print('The scrambled word is ' +sWord)

    #Calls the getGuess1() function and determines whether the player guessed correctly
    guessed = getGuess1()
    if guessed == w0rd:
        print('Congratulations!')

    if guessed != w0rd:
        print('Sorry, that is incorrect')

        #Counts the amount of guesses taken
        guesses = guesses + 1

        #Calls the getGuess2() function
        guessed2 = getGuess2()
        if guessed2 == w0rd:
            print('Congratulations!')
              
        else:
            if guessed2 != w0rd:
                print('Sorry, that is incorrect')
                guesses = guesses + 1

                #Code to provide the hint
                if guesses == 2:
                    for i in scramWord:
                        print(w0rd[i])

    #Code to ask the player if he/she wants to play again
    print('would you like to play again?', end = '')
    ans = input()



Is This A Good Question/Topic? 0
  • +

Replies To: Python school project help

#2 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Python school project help

Posted 29 November 2012 - 01:40 PM

That's a pretty good set of code, there. Save, of course, for a couple of alarming decisions.

A.) I really don't like what you did there, with the two guess functions.
B.) You should realize input("Enter your guess: ") is a much nicer way of asking the user to enter something. Printing stuff and then taking input puts the question and answer on separate lines, which, to me, is fugly.
C.) In getGuess2, you reference the guess variable which WOULD BE FINE if you only used one guess function and one variable name in it, but since you decided to repeat yourself (a strong violation of the DO NOT REPEAT YOURSELF philosophy of Python and other OOP languages, aka, the DRY principle.), you suffered one of the many consequences.
D.)Your input validation mechanism is pretty weak.

The easiest way to eliminate the second getGuess method while still maintaining an assumed requirement of printing out which guess number you're on is to do something like this:

def getGuess(extra=None):
    if not extra:
        return input("Enter your guess: ")
    return input("Enter your {0} guess: ".format(extra))


getGuess("1st")
getGuess("2nd")
getGuess("3rd")




On input validation: You wrote
def getGuess1():
    print('Enter your first guess: ', end = '')
    guess = input()
    while True:
        if guess.isalpha():
            return guess
        else:
            if guess.isdigit():
                print('Please enter a letter:', end = '')
                guess = input()



That means that if guess is not alpha or digit, your function will return nothing.

Example:
>>> def doNothing(): pass
... 
>>> doNothing() #Note nothing happened
>>> print(doNothing()) #print works on the return value, of which there is None.
None



Consider this example:
>>> " ".isdigit()
False
>>> " ".isalpha()
False
>>> "".isdigit()
False
>>> "".isalpha()
False



See how whitespace and nothing at all are registered as neither digits nor alphas? So, if the user entered nothing, the function would return nothing.

Unfortunately, the rest of your code will let that silently slip by, too. None != "toyota", for example.
>>> None == "toyota"
False





As it turns out, a loop like this works pretty well:
>>> guessed = ""
>>> while not guessed.isalpha():
...     guessed = input("Enter your guess: ")
... 
Enter your guess: 9
Enter your guess:  
Enter your guess: 
Enter your guess: 
Enter your guess: 
Enter your guess: 
Enter your guess:     
Enter your guess: \m
Enter your guess: 3
Enter your guess: HELLO!
Enter your guess: HELLO #success here, all are alpha


This post has been edited by Python_4_President: 29 November 2012 - 01:59 PM

Was This Post Helpful? 0
  • +
  • -

#3 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Re: Python school project help

Posted 29 November 2012 - 01:57 PM

View PostPython_4_President, on 29 November 2012 - 01:40 PM, said:

That's a pretty good set of code, there. Save, of course, for a couple of alarming decisions.

A.) I really don't like what you did there, with the two guess functions.
B.) You should realize input("Enter your guess: ") is a much nicer way of asking the user to enter something. Printing stuff and then taking input puts the question and answer on separate lines, which, to me, is fugly.
C.) In getGuess2, you reference the guess variable which WOULD BE FINE if you only used one guess function and one variable name in it, but since you decided to repeat yourself (a strong violation of the DO NOT REPEAT YOURSELF philosophy of Python and other OOP languages, aka, the DRY principle.), you suffered one of the many consequences.


The easiest way to eliminate the second getGuess method while still maintaining an assumed requirement of printing out which guess number you're on is to do something like this:

def getGuess(extra=None):
    if not extra:
        return input("Enter your guess: ")
    return input("Enter your {0} guess: ".format(extra))


getGuess("1st")
getGuess("2nd")
getGuess("3rd")



Thank you, I try to make things as easy to understand and read as possible. Especially for myself.

A. I didn't really like it either, but I didn't know how else to get multiple guesses going and it say enter your second guess instead of first guess again.

B. Yeah, I know. I usually always did but whenever I would add built in functions when using that method such as .isAlpha, .startswith(''), ect., it always gave me an error. So I've just been going with the print and then input method. But yeah though, I prefer the input('') method much more since it is less code and just looks better.

C. In your version, what does the extra = NONE mean and what does the .format(extra) function do? Unfortunately I'm not supposed to use functions or anything like that that we haven't gone over in class without asking the professor first, and like I said above He doesn't always reply right away.

Thanks again.
Was This Post Helpful? 0
  • +
  • -

#4 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Python school project help

Posted 29 November 2012 - 02:11 PM

Eek, throttled learning!

Quote

B. Yeah, I know. I usually always did but whenever I would add built in functions when using that method such as .isAlpha, .startswith(''), ect., it always gave me an error. So I've just been going with the print and then input method. But yeah though, I prefer the input('') method much more since it is less code and just looks better.


I detect an inattention to case sensitivity possibly attributable to prior Java coding experience!

In Python, most of that stuff is all lowercase. Type help(str) in a python interpreter and note how EVERY METHOD NAME IS LOWERCASE. It's different in Java, where they use camelCase for most everything.





Quote

C. In your version, what does the extra = NONE mean and what does the .format(extra) function do? Unfortunately I'm not supposed to use functions or anything like that that we haven't gone over in class without asking the professor first, and like I said above He doesn't always reply right away.


Default arguments and string building/formatting.
def myExample():
    print("Hi, I take no arguments no matter what!")

def myExample2(argument):
    #three ways of doing the same thing. I like the format method best because it's easier to modify the string at 3AM. 
    print("Hi! I take an argument. You gave me: %s" % str(argument))
    print("Hi! I take an argument. You gave me: {0}".format(argument))
    print("Hi! I take an argument. You gave me: " + str(argument))

def myExample3(defaultArgument = "Hello world!")
    print(defaultArgument)


myExample()
myExample("YOU FAIL!") # generates error, arguments given
myExample2() #generates an error, no arguments given
myExample2("HELLO!")
myExample3() #No error, default argument supplied
myExample3("HELLO EARTH!") #Also no error, default argument overriden


This post has been edited by Python_4_President: 29 November 2012 - 02:13 PM

Was This Post Helpful? 0
  • +
  • -

#5 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Re: Python school project help

Posted 29 November 2012 - 02:33 PM

View PostPython_4_President, on 29 November 2012 - 02:11 PM, said:

Eek, throttled learning!

Quote

B. Yeah, I know. I usually always did but whenever I would add built in functions when using that method such as .isAlpha, .startswith(''), ect., it always gave me an error. So I've just been going with the print and then input method. But yeah though, I prefer the input('') method much more since it is less code and just looks better.


I detect an inattention to case sensitivity possibly attributable to prior Java coding experience!

In Python, most of that stuff is all lowercase. Type help(str) in a python interpreter and note how EVERY METHOD NAME IS LOWERCASE. It's different in Java, where they use camelCase for most everything.





Quote

C. In your version, what does the extra = NONE mean and what does the .format(extra) function do? Unfortunately I'm not supposed to use functions or anything like that that we haven't gone over in class without asking the professor first, and like I said above He doesn't always reply right away.


Default arguments and string building/formatting.
def myExample():
    print("Hi, I take no arguments no matter what!")

def myExample2(argument):
    #three ways of doing the same thing. I like the format method best because it's easier to modify the string at 3AM. 
    print("Hi! I take an argument. You gave me: %s" % str(argument))
    print("Hi! I take an argument. You gave me: {0}".format(argument))
    print("Hi! I take an argument. You gave me: " + str(argument))

def myExample3(defaultArgument = "Hello world!")
    print(defaultArgument)


myExample()
myExample("YOU FAIL!") # generates error, arguments given
myExample2() #generates an error, no arguments given
myExample2("HELLO!")
myExample3() #No error, default argument supplied
myExample3("HELLO EARTH!") #Also no error, default argument overriden


"Eek, throttled learning!"
Is that a good thing?

I've never coded in Java

Confused......

Either way, I fixed the input validation issue with even less code than provided and it works. Do you have any ideas for how to display the value of the key of w0rd? This is the main issue that I am contending with. As far as the two guess functions go, I'll worry about that later. Right now I want to get this program done and get an A on it.
Was This Post Helpful? 0
  • +
  • -

#6 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Re: Python school project help

Posted 29 November 2012 - 02:44 PM

Ok, my professor wrote back with a small line of code and oh my gosh it worked. After all that work of trying to find out how to get it, one short line of code.

Thanks for your help Python_4_President.
Was This Post Helpful? 0
  • +
  • -

#7 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Python school project help

Posted 29 November 2012 - 02:45 PM

Throttled learning: I didn't get along with professors that wouldn't let me do things he/she didn't understand/hadn't covered, regardless of the motives for doing so. I didn't like it, but your mileage may vary.


On camelCase: I noticed in your paragraph B you mentioned isAlpha and startswith, and getting errors when using things like that.

startswith is a valid method name for a Python string. isAlpha is not. isalpha is. isAlpha != isalpha != ISALPHA.

None != NONE != none. None is a meaningful name in Python, the others are not.

Case sensitivity is something you've got to consider in almost every programming language.

on getting values from dictionaries: words is the dictionary. w0rd is the key. words[w0rd] is the value.


Quote

Thanks for your help Python_4_President.


Don't thank me! Thank yourself for figuring it out! Also, stick with it, get awesome at it, and help build the better robot army.

Also, post your code so others who happen on this thread can see what you did.

This post has been edited by Python_4_President: 29 November 2012 - 02:50 PM

Was This Post Helpful? 0
  • +
  • -

#8 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Re: Python school project help

Posted 29 November 2012 - 03:02 PM

Throttled learning: Ah, ok. I was wrong on the camelCase, it wasn't the .isalpha or .startswith() functions, it was when I tried to use the end = '' at the end of the input() function that produced the errors.

hint = word[w0rd] was exactly what he told me to put. It looks so simple its amazing. As soon as I finish this program up I will definitely post it on here. Now I'm trying to get it do provide the hint on each play again cycle. It's not going for some reason. Should I post my code and you take a look at it?
Was This Post Helpful? 0
  • +
  • -

#9 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Python school project help

Posted 29 November 2012 - 03:08 PM

I do love code!
Was This Post Helpful? 0
  • +
  • -

#10 Goggz56  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 25-March 11

Re: Python school project help

Posted 29 November 2012 - 03:15 PM

lol ok.

#Program name - COP 1000 Project 5
#Author - Charles Goggins
#Date - 11/8/2012
#Description: This program takes a word from a list and displays it to the
#player scrambled up. The player will have three chances to guess the word,
#after two incorrect guesses the program will provide the player with a hit
#to help him/her out.

#Algorithm:
#   1. Print COP 1000 header with introduction
#   2. Generate random word for scramblin'
#   3. Display scrambled word to player
#   4. Prompt player for guess #1
#       a. If guess incorrect, print sorry, incorrect message
#       b. If guess correct print good job message and go to step 7
#   5. Prompt player for guess #2
#       a. If guess incorrect, print sorry, incorrect message and provide hint
#       b. If guess correct print good job message and go to step 7
#   6. Prompt player for guess #3
#       a. If guess incorrect, print sorry, this is incorrect and provide word
#       b. If guess correct print good job message and go to step 7
#   7. Ask player if he/she would like to play again and return to step 1


#Imports the random module from the Python library
import random  

#Creates a dictionary for the words
words = {'frisbee':'Something that spins after being thrown', 
         'xbox':'A popular game console',
         'school':'A place where you go to learn',
         'hamster':'A pet',
         'toyota':'A brand of cars and trucks'}


#Function that prints the COP 1000 line and briefly explains the game
def Intro():
    print('COP 1000 Project 5 - Charles Goggins')

    print('I\'m going to show you a scrambled word and give you three guesses.')
    print('After your second guess, I\'ll help by giving you a hint.')
    

#Selects a word from the dictionary at random and returns it it's caller
def getWord(word):
    wordKey = random.choice(list(word.keys()))
    return wordKey

#When the player types HELPME in the guess prompt, the program will provide a hint
def getHint():
    hint = len(wordKey.index)
    return hint

#Gets the first guess from the player, also ensures only characters are entered
def getGuess1():
    print('Enter your first guess: ', end = '')
    guess = input()
    while True:
        if guess.isalpha():
            return guess
        else:
            guess = input('Please enter a letter: ')


#Does the same as getGuess1() but gets the player's second guess only if he/she didn't guess correctly the first time              
def getGuess2():
    guess = input('Enter your second guess: ')
    while True:
        if guess.isalpha():
            return guess
        else:
            guess = input('Please enter a letter: ')

def getGuess3():
    guess = input('Enter your final guess: ')
    while True:
        if guess.isalpha():
            return guess
        else:
            guess = input('Please enter a letter: ')

#==============================================================MAIN PROGRAM===============================================#

#Initializes some varibles, ans = 'y' is for the play again loop
ans = 'y'
guesses = 0
while ans == 'y':

    #Calls the getWord() function
    w0rd = getWord(words)
    #Turns w0rd into a list to enable scrambling
    scramWord = list(w0rd)
    #Scrambles the word
    random.shuffle(scramWord)
    #Joins the scrambled word together to be able to display it
    sWord = ''.join(scramWord)

    print('The scrambled word is ' +sWord)

    #Calls the getGuess1() function and determines whether the player guessed correctly
    guessed = getGuess1()
    if guessed == w0rd:
        print('Congratulations!')

    if guessed != w0rd:
        print('Nope, sorry')

        #Counts the amount of guesses taken
        guesses = guesses + 1

        #Calls the getGuess2() function
        guessed2 = getGuess2()
        if guessed2 == w0rd:
            print('Congratulations!')
              
        else:
            if guessed2 != w0rd:
                print('Nope, sorry')
                guesses = guesses + 1

                #Code to provide the hint
                while guesses == 2:
                    hint = words[w0rd]
                    print(hint)
                    guesses = guesses + 1
                    
        guessed3 = getGuess3()
        if guessed3 == w0rd:
            print('Congratulations!')
              
        else:
            if guessed3 != w0rd:
                print('Nope, sorry')
                guesses = guesses + 1
                            
    #Code to ask the player if he/she wants to play again
    print('would you like to play again?', end = '')
    ans = input()


Was This Post Helpful? 0
  • +
  • -

#11 witeboy724  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 42
  • Joined: 21-June 12

Re: Python school project help

Posted 12 January 2013 - 10:39 PM

I'm sure that you've already gotten this figured out, but I was looking for questions that I was actually able to help out on. I'm pretty new at Python.

You need to reset guesses back to 0 when the next game is started. You can throw in the line guesses=0 near the end. It can actually go right after the last line.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1