Is This A Correct Use Of The `in` Keyword In Python?
I am trying to make a really basic hangman game by using an if/in check, however, the code wasn't responding to changes in the player input. Since this is my first time using the i
Solution 1:
Please check if this code works for you. I modified it a little and added some more conditions.
#put word into here, as a string :)
print("Welcome to Hangman")
word = ["a", "v", "a", "c", "a", "d", "o"]
wordLength = len(word) + 1
lives = wordLength * 2print("lives:", lives)
print("Letters in word", wordLength)
guess = input("Enter the letter : ")
while lives != 0:
if guess in word:
print("YES!")
print(guess)
index = word.index(guess)
#print("Index = ",index)
del word[index]
else:
print("Wrong!")
lives -=1print("lives:", lives)
if len(word)==0 and lives > 0:
print("Success!!")
break
guess = input("Enter the letter : ")
if lives == 0:
print("falied! try again")
Solution 2:
Is this a correct use of the
in
keyword in python?
yes, it's correct to use the in
keyword to check if a value is present in a sequence (list
, range
, string
etc.), but your sample code contains several other errors, which are out-of-scope of the main question, just like the game below...
In the meanwhile, I got interested by the question and coded a quick StackOverflow Popular Tags Hangman game with Tag definitions, i.e:
import requests
from random import choice
# src https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
# english word_list (big)# word_list = requests.get("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt").text.split("\n")# you can use any word_list, as long as you provide a clean (lowered and sripped) list of words.# To create a hangman game with the most popular tags on stackoverflow, you can use:try:
word_list = requests.get("https://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow").json()['items']
word_list = [x['name'].lower() for x in word_list if x['name'].isalpha()] # filter tags with numbers and symbolsexcept:
print("Failed to retrieve json from StackExchange.") # exit here# function that returns a random word with/out length range , uses word_listdefrand_word(_min=1, _max=15):
# filter word_list to words between _min and _max characters
r_word = [x.strip() for x in word_list if _min <= len(x) <= _max] #return choice(r_word)
# tag definition from stackoverflow wikideftag_info(w):
try:
td = requests.get(f"https://api.stackexchange.com/2.2/tags/{w}/wikis?site=stackoverflow").json()['items'][0]['excerpt']
return(td)
except:
passprint(f"Failed to retrieve {w} definition")
# game logic (win/loose)defplay(word):
word_l = list(word) # list with all letters of word
wordLength = len(word_l)
lives = 7print("Lives:", lives)
print("Letters in word", wordLength)
place_holder = ["*"for x in word_l]
used = [] # will hold the user input letters, so no life is taken if letter was already used.while1:
print("".join(place_holder))
guess = input().lower().strip() # get user guess, lower it and remove any whitespaces it may haveifnot guess orlen(guess) > 1: # if empty guess or multiple letters, print alert and continueprint("Empty letter, please type a single letter from 'a' to 'z' ")
continueif guess in word_l:
used.append(guess) # appends guess to used lettersprint(guess, "Correct!", guess)
for l in word_l: # loop all letters in word and make them visibleif l == guess:
index = word_l.index(guess) # find the index of the correct letter in list word
word_l[index] = "."# use index to substitute the correct letter by a dot (.), this way, and if there are repeated letters, they don't overlap on the next iteration. Small hack but it works.
place_holder[index] = guess # make the correct letter visible on place_holder. Replaces * by guesselif guess in used:
print("Letter already used.")
continueelse:
used.append(guess) # appends guess to used lettersprint(HANGMANPICS[-lives])
lives -= 1# removes 1 lifeprint(f"Wrong! Lives: {lives}" )
if lives == 0:
print(f"You Lost! :-|\nThe correct word was:\n{word}\n{tag_info(word)}")
#print(HANGMANPICS[-1])break# When there are no more hidden letters (*) in place_holder the use won.ifnot"*"in place_holder:
print(f"You Won!!!\n{word}\n{tag_info(word)}")
breakprint("Welcome to StackTag Hangman")
while1:
play(rand_word(1, 15)) # creates a new game with a random word between x and x letters. play() can be simply be used as play("stackoverflow").
pa = input("Try again? (y/n)\n").lower().strip() # Ask user if wants to play again, lower and cleanup the input for comparision below.if pa != "y": # New game only if user input is 'y', otherwise break (exit)print("Tchau!")
break
Notes:
- You can play with it
- Asciinema Video
- v2 with approx. 7k computer jargon's.
Post a Comment for "Is This A Correct Use Of The `in` Keyword In Python?"