473,583 Members | 3,346 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Hangman code

21 New Member
Making a hangman code (I'm a n00b, still in the tutorial stage)

Anyway, here's my (top-secret) code:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     if len(choice)>1:
  4.         print "Don't cheat!"
  5.         guess()
  6.     elif guess in y:
  7.         b[z.find(choice)]=choice
  8.         print "Good Choice!"
  9.         print ''.join(b)
  10.         guess()
  11.  
  12. def main():
  13.     x=raw_input("Type a name")
  14.     y=x.lower().split(' ')
  15.     z=''.join(y)
  16.     print z
  17.     b=['_ ']*len(z)
  18.     print ''.join(b)
  19.     guess()
  20.  
  21. if __name__=='__main__':
  22.     main()
  23.  
Anyways, I get down to line 6 and it tells me that global name z is not defined. I'm guessing I have to put the z thing in there, but I don't know how.

What should I do?
P.S. the code is still in development. That is why it is not finished.
Mar 17 '07 #1
24 15924
bartonc
6,596 Recognized Expert Expert
Making a hangman code (I'm a n00b, still in the tutorial stage)

Anyway, here's my (top-secret) code:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     if len(choice)>1:
  4.         print "Don't cheat!"
  5.         guess()
  6.     elif guess in y:
  7.         b[z.find(choice)]=choice
  8.         print "Good Choice!"
  9.         print ''.join(b)
  10.         guess()
  11.  
  12. def main():
  13.     x=raw_input("Type a name")
  14.     y=x.lower().split(' ')
  15.     z=''.join(y)
  16.     print z
  17.     b=['_ ']*len(z)
  18.     print ''.join(b)
  19.     guess()
  20.  
  21. if __name__=='__main__':
  22.     main()
  23.  
Anyways, I get down to line 6 and it tells me that global name z is not defined. I'm guessing I have to put the z thing in there, but I don't know how.

What should I do?
P.S. the code is still in development. That is why it is not finished.
Hi St33med. Most code we see here is "still in development"; we're here to help you get it working. So, welcome to the Python help forum on TSDN!

This is an issue of "scope". The scope rules say that variables assigned in a function are "local" to that function. I quick way to make this work is (but maybe not the best):
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     if len(choice)>1:
  4.         print "Don't cheat!"
  5.         guess()
  6.     elif guess in y:
  7.         b[z.find(choice)]=choice
  8.         print "Good Choice!"
  9.         print ''.join(b)
  10.         guess()
  11.  
  12. if __name__=='__main__':
  13.     x=raw_input("Type a name")
  14.     y=x.lower().split(' ')
  15.     z=''.join(y)
  16.     print z
  17.     b=['_ ']*len(z)
  18.     print ''.join(b)
  19.     guess()
  20.  
  21.  
I'm in a rush at this second, but I'll have some time in just a bit...
Thanks for joining.
Mar 17 '07 #2
bartonc
6,596 Recognized Expert Expert
Hi St33med. Most code we see here is "still in development"; we're here to help you get it working. So, welcome to the Python help forum on TSDN!

This is an issue of "scope". The scope rules say that variables assigned in a function are "local" to that function. I quick way to make this work is (but maybe not the best):
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     if len(choice)>1:
  4.         print "Don't cheat!"
  5.         guess()
  6.     elif guess in y:
  7.         b[z.find(choice)]=choice
  8.         print "Good Choice!"
  9.         print ''.join(b)
  10.         guess()
  11.  
  12. if __name__=='__main__':
  13.     x=raw_input("Type a name")
  14.     y=x.lower().split(' ')
  15.     z=''.join(y)
  16.     print z
  17.     b=['_ ']*len(z)
  18.     print ''.join(b)
  19.     guess()
  20.  
  21.  
I'm in a rush at this second, but I'll have some time in just a bit...
Thanks for joining.
What this does is put the varaibles x, y and z into the module scope. As such, they can be "seen" by functions that are also in that scope. This use of "global" scope variables is good for learning because it is fairly simple. There are lot's of other things to change before we get to the final working program, but let's take it one step at a time. And HAVE FUN.
Mar 17 '07 #3
St33med
21 New Member
Well, the code worked and I made some enhancements:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     a=type.find(str(choice))
  4.     if len(choice)>1:
  5.         print "Don't cheat!"
  6.         guess()
  7.     elif a!=-1:
  8.         b[a]=str(choice)
  9.         print "Good Choice!"
  10.         c=''.join(b)
  11.         print c
  12.         if type==c:
  13.             print "You Win!"
  14.         else:
  15.             guess()
  16.     else:
  17.         d+=1
  18.         e[d]=choice
  19.         if d==0:
  20.             print "O",e
  21.             guess()
  22.         elif d==1:
  23.             print e,"O<"
  24.             guess()
  25.         elif d==2:
  26.             print e,"0<-"
  27.             guess()
  28.         elif d==3:
  29.             print e,"O<-<\n Game Over"
  30.  
  31. if __name__=='__main__':
  32.     type=raw_input("Type a name:")
  33.     type=''.join(type.lower().split(' '))
  34.     #print type
  35.     b=['_ ']*len(type)
  36.     print ''.join(b)
  37.     d=-1
  38.     e=['']*5
  39.     guess()
The problem with this code is that it tells me that d was referenced before assignment. If I put d in def guess, then it will always return d to -1 and the guy taking guesses will have infinite amount of guesses. That might have been why you said that the solution was not the best. What should I do?
Mar 18 '07 #4
ghostdog74
511 Recognized Expert Contributor
Well, the code worked and I made some enhancements:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     choice=raw_input("Guess!(lowercase only please!)")
  3.     a=type.find(str(choice))
  4.     if len(choice)>1:
  5.         print "Don't cheat!"
  6.         guess()
  7.     elif a!=-1:
  8.         b[a]=str(choice)
  9.         print "Good Choice!"
  10.         c=''.join(b)
  11.         print c
  12.         if type==c:
  13.             print "You Win!"
  14.         else:
  15.             guess()
  16.     else:
  17.         d+=1
  18.         e[d]=choice
  19.         if d==0:
  20.             print "O",e
  21.             guess()
  22.         elif d==1:
  23.             print e,"O<"
  24.             guess()
  25.         elif d==2:
  26.             print e,"0<-"
  27.             guess()
  28.         elif d==3:
  29.             print e,"O<-<\n Game Over"
  30.  
  31. if __name__=='__main__':
  32.     type=raw_input("Type a name:")
  33.     type=''.join(type.lower().split(' '))
  34.     #print type
  35.     b=['_ ']*len(type)
  36.     print ''.join(b)
  37.     d=-1
  38.     e=['']*5
  39.     guess()
The problem with this code is that it tells me that d was referenced before assignment. If I put d in def guess, then it will always return d to -1 and the guy taking guesses will have infinite amount of guesses. That might have been why you said that the solution was not the best. What should I do?
in your guess() function, 'd' is never 'initialized' before you do d+=1.
Either you pass 'd' value into guess(), as in guess(d) , or use global.
Mar 18 '07 #5
bartonc
6,596 Recognized Expert Expert
What my friend ghostdog74 means is:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     global d
  3.     choice=raw_input("Guess!(lowercase only please!)")
  4.     a=type.find(str(choice))
  5.     if len(choice)>1:
  6.         print "Don't cheat!"
  7.         guess()
  8.     elif a!=-1:
  9.         b[a]=str(choice)
  10.         print "Good Choice!"
  11.         c=''.join(b)
  12.         print c
  13.         if type==c:
  14.             print "You Win!"
  15.         else:
  16.             guess()
  17.     else:
  18.         d+=1
  19.         e[d]=choice
  20.         if d==0:
  21.             print "O",e
  22.             guess()
  23.         elif d==1:
  24.             print e,"O<"
  25.             guess()
  26.         elif d==2:
  27.             print e,"0<-"
  28.             guess()
  29.         elif d==3:
  30.             print e,"O<-<\n Game Over"
  31.  
  32. if __name__=='__main__':
  33.     type=raw_input("Type a name:")
  34.     type=''.join(type.lower().split(' '))
  35.     #print type
  36.     b=['_ ']*len(type)
  37.     print ''.join(b)
  38.     d=-1
  39.     e=['']*5
  40.     guess()
  41.  
It's very cute! I ran it and it work using this global scope technique. You a really quit a good pythoneer. Keep it up! Next you may want to play with parameter passing (also as GD has suggested).
Mar 18 '07 #6
ghostdog74
511 Recognized Expert Contributor
Just an opinion of mine, its better to use while loop for tasks like this:
for example:
Expand|Select|Wrap|Line Numbers
  1. while 1:
  2.          ask for input
  3.          if input is quit or exit:
  4.                 break
  5.          else:
  6.                 call your functions.
  7.  
In the original code, guess() is defined as a function, but in it, there are also calls to guess() itself. In programming concepts, this is something like recursion. Before the first call to guess() has returned to caller, another guess() gets called and so on. The stack gets slowly "filled up" due to storing of return addresses and etc etc......at least that's how i feel.
Mar 18 '07 #7
bvdet
2,851 Recognized Expert Moderator Specialist
What my friend ghostdog74 means is:
Expand|Select|Wrap|Line Numbers
  1. def guess():
  2.     global d
  3.     choice=raw_input("Guess!(lowercase only please!)")
  4.     a=type.find(str(choice))
  5.     if len(choice)>1:
  6.         print "Don't cheat!"
  7.         guess()
  8.     elif a!=-1:
  9.         b[a]=str(choice)
  10.         print "Good Choice!"
  11.         c=''.join(b)
  12.         print c
  13.         if type==c:
  14.             print "You Win!"
  15.         else:
  16.             guess()
  17.     else:
  18.         d+=1
  19.         e[d]=choice
  20.         if d==0:
  21.             print "O",e
  22.             guess()
  23.         elif d==1:
  24.             print e,"O<"
  25.             guess()
  26.         elif d==2:
  27.             print e,"0<-"
  28.             guess()
  29.         elif d==3:
  30.             print e,"O<-<\n Game Over"
  31.  
  32. if __name__=='__main__':
  33.     type=raw_input("Type a name:")
  34.     type=''.join(type.lower().split(' '))
  35.     #print type
  36.     b=['_ ']*len(type)
  37.     print ''.join(b)
  38.     d=-1
  39.     e=['']*5
  40.     guess()
  41.  
It's very cute! I ran it and it work using this global scope technique. You a really quit a good pythoneer. Keep it up! Next you may want to play with parameter passing (also as GD has suggested).
It does work well. However, if you enter a word that has two of the same letter as in "sell", you can never solve it. You should not use a variable name that masks a Python built-in function (type). We had another thread on Hangman recently, and we used this function to determine the occurances of a letter in a word:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
I agree with ghostdog74 abot the use of a loop instead of recursion. I also encourage you to avoid using global variables where possible. As in the function listed above, the word (s) and letter (item) are passed to get_index() and in return we receive a list of indices or an empty list if there were no occurances of 'item' in 's':
Expand|Select|Wrap|Line Numbers
  1. >>> iLst = indexList('mississippi', 's')
  2. >>> iLst
  3. [2, 3, 5, 6]
  4. >>> hint_string = '_'*len('mississippi')
  5. >>> for i in iLst:
  6. ...     lst = [hint_string[:i], ]
  7. ...     if len(hint_string) >= i+1:
  8. ...         lst.append(hint_string[(i+1):])
  9. ...     hint_string = 's'.join(lst)
  10. ...     
  11. >>> hint_string
  12. '__ss_ss____'
  13. >>> 
Mar 18 '07 #8
St33med
21 New Member
Well here is my code, almost finished:
Expand|Select|Wrap|Line Numbers
  1. import sys
  2. def guess(d,x,e):
  3.             choice=raw_input("Guess!(lowercase only please!)")
  4.             a=type.find(str(choice))
  5.             if len(choice)>1:
  6.                 print "Don't cheat!"
  7.                 guess(d,x,e)
  8.             elif a!=-1:
  9.                 b[a]=str(choice)
  10.                 print "Good Choice!"
  11.                 c=''.join(b)
  12.                 print c, e
  13.                 if type==c:
  14.                     print "You Win!"
  15.                     sys.exit()
  16.                 else:
  17.                     guess(d,x,e)
  18.             else:
  19.                 d+=x
  20.                 if guess in e:
  21.                     print "You have already guessed this!"
  22.                     guess(d,x,e)
  23.                 e[d]=choice
  24.                 if d==0:
  25.                     print "O"
  26.                     x=1
  27.                 elif d==1:
  28.                     print "O<"
  29.                     x=2
  30.                 elif d==2:
  31.                     print "0<-"
  32.                     x=3
  33.                 elif d==3:
  34.                     print "O<-<\n Game Over"
  35.                     sys.exit()
  36.                 print "Letters Guessed: ", ' '.join(e)
  37.                 guess(d,x,e)
  38. if __name__=='__main__':
  39.     type=raw_input("Type a name:")
  40.     type=''.join(type.lower().split(' '))
  41.     #print type
  42.     b=['_ ']*len(type)
  43.     print ''.join(b)
  44.     d=0
  45.     x=0
  46.     e=['']*4
  47.     guess(d,x,e)
  48.  
  49.  
Where should I put this indexList?
Mar 18 '07 #9
bvdet
2,851 Recognized Expert Moderator Specialist
Well here is my code, almost finished:
Expand|Select|Wrap|Line Numbers
  1. import sys
  2. def guess(d,x,e):
  3.             choice=raw_input("Guess!(lowercase only please!)")
  4.             a=type.find(str(choice))
  5.             if len(choice)>1:
  6.                 print "Don't cheat!"
  7.                 guess(d,x,e)
  8.             elif a!=-1:
  9.                 b[a]=str(choice)
  10.                 print "Good Choice!"
  11.                 c=''.join(b)
  12.                 print c, e
  13.                 if type==c:
  14.                     print "You Win!"
  15.                     sys.exit()
  16.                 else:
  17.                     guess(d,x,e)
  18.             else:
  19.                 d+=x
  20.                 if guess in e:
  21.                     print "You have already guessed this!"
  22.                     guess(d,x,e)
  23.                 e[d]=choice
  24.                 if d==0:
  25.                     print "O"
  26.                     x=1
  27.                 elif d==1:
  28.                     print "O<"
  29.                     x=2
  30.                 elif d==2:
  31.                     print "0<-"
  32.                     x=3
  33.                 elif d==3:
  34.                     print "O<-<\n Game Over"
  35.                     sys.exit()
  36.                 print "Letters Guessed: ", ' '.join(e)
  37.                 guess(d,x,e)
  38. if __name__=='__main__':
  39.     type=raw_input("Type a name:")
  40.     type=''.join(type.lower().split(' '))
  41.     #print type
  42.     b=['_ ']*len(type)
  43.     print ''.join(b)
  44.     d=0
  45.     x=0
  46.     e=['']*4
  47.     guess(d,x,e)
  48.  
  49.  
Where should I put this indexList?
Anywhere above "if __name__ == '__main__':"
Mar 18 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
15794
by: tigrfire | last post by:
So I'm trying to write a hangman game and the output is coming out a little strange. Here's my code thus far: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int hangman()
18
9192
ilikepython
by: ilikepython | last post by:
Hi I'm new to Python(3 to 4 days) and I'm working on a hangman game and have been having some problems that really annoy me. Here is part of my script: c = input('Would you like to play hangman? Type y or n ') word = sample(('soccer', 'robbery', 'antibiotics'), 1) word = str(word) spaces =...
4
2590
by: princessfrost | last post by:
Hi! I was wondering if someone could please help me with a hangman program that I have to do. I have some ideas, but really don't know what to do or where to start. My program needs to be: interactive with the user, menu based(like Menu: 1. Play hangman 2. Exit program), have a dictionaryand use a random method(create arrays of Strings or...
47
11441
by: araujo2nd | last post by:
Originally Posted by araujo2nd my name is andre, im from south africa, i was wondering if any1 could help me with a hangman application, im now in grade 11 and have a huge portfolio piece to do by the 15th which i have just started now, i have always struggled with java and would rele appreciate all the help that i can get. Pls could some1 help...
3
2944
by: kaka_hunter | last post by:
#include <iostream> #include <fstream> using namespace std; const int max_tries=7; int earnings=0; int wordnum; void getword () { ifstream fin;
2
4029
by: tesa | last post by:
I am not able to figure out how to make this work. I am trying to create a hangman game. I am in a basic javascripting class. I am to only use very basic code as you can see. I am able to use any online resources to help me. I have added alot of comments for what should be happening however is not happening. I also have a teacher that...
0
1687
by: Madmartigan | last post by:
Hi I'm a newbie to C# and have been instructed to create a Hangman game in SharpDevelop. I don't want the answer to the full code, just some help along the way. I have included my code thus far and at this stage would like to know how I can get the RandomWordManager, which I found on another site, to display a newly generated word as the...
8
3738
by: tidiz | last post by:
Hi, I'm trying to make a hangman game that should look like this: Welcome to Hangman ______ Your guess: c Success! __cc__ Your guess: b
1
2573
by: AlexSc | last post by:
Hi to All, I am doing on a hangman project, Where this is a very simple one, where player would guess the word and if it is correct the letter would be from "-" to the correct letter once all letter is correct they system will appear out good job u clear the game. I had done up the game and it work however i find mine is rather impractical,...
0
8172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7928
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8188
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6574
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5369
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3839
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1422
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1151
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.