Hangman program: incorrect use of global variable in loop - python-3.x

I'm writing a program to play the game hangman, and I don't think I'm using my global variable correctly.
Once the first iteration of the program concludes after a correct guess, any successive iteration with a correct guess prints the word and all of its past values.
How can I only print the most current value of word? This chunk of code is within a while loop where each iteration gets user input. Thanks!
Code:
word=''
#lettersGuessed is a list of string values of letters guessed
def getGuessedWord(secretWord, lettersGuessed):
global word
for letter in secretWord:
if letter not in lettersGuessed:
word=word+' _'
elif letter in lettersGuessed:
word=word+' '+letter
return print(word)
The Output:
#first iteration if 'a' was guessed:
a _ _ _ _
#second iteration if 'l' was guessed:
a _ _ _ _ a _ _ l _
#third iteration if 'e' was guessed:
a _ _ _ _ a _ _ l _ a _ _ l e
#Assuming the above, for the third iteration I want:
a _ _ l e
Note: This is only a short section of my code, but I don't feel like the other chunks are relevant.

The main problem you are facing is that you are appending your global variable every time you call your function. However, I think you don't need to use a global variable, in general this is a very bad practice, you can simply use the following code considering what you are explaining in your question:
def getGuessedWord(secretWord, lettersGuessed):
return ' '.join(letter if letter in lettersGuessed else '_'
for letter in secretWord)
I also think that it is better if you use a python comprehension to make your code faster.

every time you are calling the function getGuessedWord you are adding to `word, You can not use a global:
secretWord = "myword"
def getGuessedWord(secretWord, lettersGuessed):
word = ""
for letter in secretWord:
if letter not in lettersGuessed:
word=word+' _'
elif letter in lettersGuessed:
word=word+' '+letter
return print(word)
getGuessedWord(secretWord,"")
getGuessedWord(secretWord,"m")
getGuessedWord(secretWord,"mwd")
Or you can solve this by setting word at a constant length, (not as nice and harder to follow) e.g: word='_ '*len(secretWord), then instead of adding to it, replace the letter word=word[:2*i]+letter +word[2*i+1:]
Example here:
secretWord = "myword"
word='_ '*len(secretWord)
def getGuessedWord(secretWord, lettersGuessed):
global word
for i, letter in enumerate(secretWord):
if letter in lettersGuessed:
word=word[:2*i]+letter +word[2*i+1:]
return print(word)
getGuessedWord(secretWord,"")
getGuessedWord(secretWord,"m")
getGuessedWord(secretWord,"w")
getGuessedWord(secretWord,"d")

Related

Code generator help-- Wont stop at sequence I want

I made a python random sequence generator, I can tell it the max the length of the sequence can be but I want it to stop at a specific sequence... I have spent a couple days searching for a way to do this.
I made the generator do what I want, make a random letter (uppercase and lowercase) and number sequence(I am able to manually change the max it can be) and I made it so It will run forever using a while loop. searched for a couple days to get it the way I want but wont work.
import string, random
while True :
def id_generator(size=2, chars=string.ascii_uppercase +
string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
if id_generator() == "2g":
break
print("found your code")
else :
print(id_generator())
The "size" makes the max the sequence can be. I wanted the the if statement to say if it creates "2g" to stop and say "found your code" else just keep generating... I think it has something to do with the if statement
First of all, don't define the function in the while loop. Define it elsewhere and then call it inside the while.
Next, after calling the function assign its value to a variable and let that be used by the conditionals.
I finally got it...
import string, random
num = input("Pick your num: ")
while True :
def id_generator(size=2, chars=string.ascii_uppercase + string.ascii_lowercase +
string.digits):
return ''.join(random.choice(chars) for _ in range(size))
if id_generator() == num:
print("found your code")
print(num)
break
else :
print(id_generator())

Blank line left in before input

I am trying to get my output to look like this:
You have 6 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: ​ a
Good guess: _ a_ _
But mine looks like this:
You have 1 guesses left
Available Letters: bcdfghjklmnopqruvwxyz
Please guess a letter: m
That letter in not in my word: _ i_ _ s
What Python 3.X is doing is putting a blank line above when I use an input statement like this:
user_guess = input('Please guess a letter: ')
Anyway to get rid of that blank line?

Replacing a character in a list

Im making a hangman game and the first function to make is an function that recieves a word, pattern (_ _ _ _ _) and a letter, and then add the letter to the pattern according to the index of the letter in the word.
for some reason - this code is not working. I'v tried to run it and the loop works well for 3 times till letter = index_1 and then it collapse
can you sopt the problem?
word = 'hallo'
i = 0
index_1 = word[i]
letter = 'l'
ling = len(word)
pattern = ['_']*ling
if letter in word:
for i in range(ling):
index_1 = word[i]
if letter == index_1:
pattern[index_1] = letter

Print on one line in python Window

I'm not sure how to get multiple outputs from a for loop to print on the same line in a window. I'm using the built in Window function from uagame with python3.x. Here's what the code looks like:
for char in a_word:
if char in user_guess:
window.draw_string(char+" ",x, y)
else:
window.draw_string('_ ',x, y)
y = y + font_height
This keeps displaying as:
_
_
_
_
And I want it to print as
_ _ _ _
Any idea how to get each character or _ to display on one line? This is for a WordPuzzle/Hangman type game.
Use this as a example, and hopefully you will implement the same to your code.
for i in range(1,10):
print(i,end=",")
print()
The output looks like
1,2,3,4,5,6,7,8,9,
Define a empty list and append your characters then print all at once
a=[]
for char in a_word:
if char in user_guess:
a.append(char)
else:
a.append(char)
print(a,end=",")
y = y + font_height

Python 2.7 - remove special characters from a string and camelCasing it

Input:
to-camel-case
to_camel_case
Desired output:
toCamelCase
My code:
def to_camel_case(text):
lst =['_', '-']
if text is None:
return ''
else:
for char in text:
if text in lst:
text = text.replace(char, '').title()
return text
Issues:
1) The input could be an empty string - the above code does not return '' but None;
2) I am not sure that the title()method could help me obtaining the desired output(only the first letter of each word before the '-' or the '_' in caps except for the first.
I prefer not to use regex if possible.
A better way to do this would be using a list comprehension. The problem with a for loop is that when you remove characters from text, the loop changes (since you're supposed to iterate over every item originally in the loop). It's also hard to capitalize the next letter after replacing a _ or - because you don't have any context about what came before or after.
def to_camel_case(text):
# Split also removes the characters
# Start by converting - to _, then splitting on _
l = text.replace('-','_').split('_')
# No text left after splitting
if not len(l):
return ""
# Break the list into two parts
first = l[0]
rest = l[1:]
return first + ''.join(word.capitalize() for word in rest)
And our result:
print to_camel_case("hello-world")
Gives helloWorld
This method is quite flexible, and can even handle cases like "hello_world-how_are--you--", which could be difficult using regex if you're new to it.

Resources