how to make this python code look cleaner? - python

I've recently wrote 'hangman' in python. Then added few things and now I am trying to clean this up a bit.
Any ideas how to get rid of these two while (...) true statements?
Also I think there's too many if (...) else statements.
Any tips and other suggestions would be appreciated :)
word = "stackoverflow"
user_word = []
used_letters = []
def find_indexes(word, letter):
indexes = []
for index, letter_in_word in enumerate(word):
if letter == letter_in_word:
indexes.append(index)
return indexes
for _ in word:
user_word.append("_")
while True:
try:
no_of_tries = int(input("Enter number of tries: "))
break
except ValueError:
print("Enter numeric value :)")
while True:
letter = input("Enter a letter: ").lower()
if letter.isalpha():
if len(letter) == 1:
used_letters.append(letter)
found_indexes = find_indexes(word, letter)
if len(found_indexes) == 0:
print("There's no such letter in your word :(")
no_of_tries -= 1
print("Tries left: ", no_of_tries,)
if no_of_tries == 0:
print("It was nice...to meet you")
# sys.exit()
else:
for index in found_indexes:
user_word[index] = letter
whole_word = "".join(user_word)
if whole_word == word:
print("WOW, VICTORY!!! :D")
print("".join(user_word))
print("Used letters: ", used_letters )
else:
print("Enter ONE letter")
else:
print("Enter letter")

Your loop is even continuing if the word is complete or the chances are over.
Use a variable in the while loop:-
playing = True
while playing:
And to over the thing use this:-
if no_of_tries == 0:
print("It was nice...to meet you")
playing = False
if whole_word == word:
print("WOW, VICTORY!!! :D")
playing = False

Too broad question, perhaps.
A good rule is to handle trivial cases first and do the main processing last:
while True:
letter = input("Enter a letter: ").lower()
if not letter.isalpha():
print("Enter letter")
continue
if len(letter) != 1:
print("Enter ONE letter")
continue
used_letters.append(letter)
... etc ...
Notice how the indentation level has decreased.

Related

How to specify the code to terminate if a specific word is entered as input?

the code is about a game like hangman. It has 3 input : guess_num, length, guess. It should terminate the whole program if in any of that input the word stop or exit is entered.my break statement only works for each part of the program. for example each input only terminates its part. how can i code this to terminate whole program if stop or exit is entered in any of that
while True: # For repeating the game if user wants to
print("Welcome to Guess-The-Letter game") # Start of the game
print("") # Just and indent line
# Asking for user to choose number of guess
while True:
num_guess = input("how many times do you want to guess [1-10]: ")
if num_guess.lower() == "stop" or num_guess.lower() == "exit":
print("Game Ends!")
break
try:
num_guess = int(num_guess)
except ValueError:
print("Not a number!")
continue # Checking for non number input
if num_guess < 1 or num_guess > 10:
print("Out of Range") # Checking for out of range input
else:
result1 = int(num_guess) # Storing the value
break # Anything else would be in range that we want and will store the value and break the loop
# Asking for user to choose length of word
while True:
length = input("please enter the length of the word [4-5]: ")
if length.lower() == "stop" or length.lower() == "exit":
print("Game Ends!")
break
try:
length = int(length)
except ValueError:
print("Not a number!")
continue # Checking for non number input
if length < 4 or length > 5:
print("Out of Range") # Checking for out of range input
else:
result2 = int(length) # Storing the value
break # Anything else would be in range that we want and will store the value and break the loop
# Choosing the words
if result2 == 4:
word = choice(word4)
elif result2 == 5:
word = choice(word5)
guess_list = [] # List of guess letters
sec_word = [] # the list for formatting the random word
for i in range(len(word)):
sec_word.append("*") # To format the random word into ****
guess = "" # Defining nothing in variable for the first time of iteration
print("Selecting the word...") # Just a Display
while result1 > 0: # Start of the guessing game on the condition that guess left is greater than 0
print("word is:", "".join(sec_word)) # Displaying the word
# Displaying the remaining guess number
print("Guess remaining:", result1)
# Showing the guess for the previous time
print("Previous guess:", guess)
guess = input("Please guess a letter: ") # Guessing the letter
if guess in guess_list:
# if user input a similar letter like previous letter
print(guess, "has been guessed before", end=" ")
guess_list.append(guess) # Add the guess letters to a list
if guess.lower() == "stop" or guess.lower() == "exit":
print("Game Ends!")
break # Letting user end the game at anytime
if guess in word: # For the input that is correct
if length == 4: # Displaying the word letter by checking for each index for 4 letters words
if guess == word[0]:
sec_word[0] = guess
if guess == word[1]:
sec_word[1] = guess
if guess == word[2]:
sec_word[2] = guess
if guess == word[3]:
sec_word[3] = guess
elif length == 5: # Displaying the word letter by checking for each index for 5 letters words
if guess == word[0]:
sec_word[0] = guess
if guess == word[1]:
sec_word[1] = guess
if guess == word[2]:
sec_word[2] = guess
if guess == word[3]:
sec_word[3] = guess
if guess == word[4]:
sec_word[4] = guess
print(guess, "is in the word!")
if guess not in word: # For the wrong inputs from user
print(guess, "is not in the word! Try agin")
print("") # Just a space after each question
if "".join(sec_word) == word:
print("You win!")
break # if user guess the right word before end of the guess number
result1 -= 1 # After each guess the remaining guess time drops 1 time
You can use sys.exit() to terminate the program.
import sys
if guess.lower() == "stop" or guess.lower() == "exit":
print("Game Ends!")
sys.exit()

First condition of an if-block is getting skipped

I'm writing code with Python 2.7 that checks if a character is present in a input string but Python keeps skipping part of my if-statement.
Each time I run the code and enter a guess character value, the execution goes straight to the else statement and never executes the if(guess in PuzzleSetter) == True block at all.
What am I doing wrong?
PuzzleSetter = " "
List = []
def setPuzzle():
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
print("Guessing player try guessing: "+PuzzleSetter.upper())
time.sleep(5)
print(chr(27) + "[2J")
List = [' __ ']*len(PuzzleSetter)
print("\n")
print(List)
while(True):
guess = raw_input("\nGuessing player make your guess: ")
if len(guess) != 1:
print("You are meant to enter a single letter")
continue
else:
guess = guess.upper()
print(guess)
if(guess in PuzzleSetter) == True:
finder = PuzzleSetter.find(guess)
print(PuzzleSetter+" contains "+str(PuzzleSetter.count(guess))+" "+guess+"'s")
for count in range(PuzzleSetter.count(guess)):
List[finder] = guess.upper()
finder = PuzzleSetter.find(guess, finder+1)
print(List)
if List.count("__") == 0:
print("Guessing player wins!")
break
else:
HangerMan()
enter += 1
if enter == 7:
print("Guessing player lost!")
print("\nPlayer two becomes the puzzle setter")
setPuzzle()
As I thought, you're leaving PuzzleSetter as input and not converting it to upper case like you are guess. If it contains any lower case letters they will never be found. Try this:
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
PuzzleSetter = PuzzleSetter.upper()
print("Guessing player try guessing: "+PuzzleSetter)

Question about dictionary items addition in Python (Guess the word game)

How can i add a letter multiple times in the different keys of a dictionary?
I made a guess the word game where the user enters the letter to complete the mysterious word.
Everything works fine with words where letters appears just one time (Ex. Dog) but I have problems when letters occur multiple times (Ex. Employee) because only the first one is filled.
I know this is probably not the most efficient way of doing this but I'm starting programming in python and was experimenting a bit with the concepts learned.
Here's the code, thanks for the help:
import os
word = input('choose the word to play with: ')
os.system('cls')
word_list = list(word)
word_dict = {}
for x in range(len(word_list)):
word_dict[str(x)] = word_list[x]
guess_dict = {}
for x in range(len(word_list)):
guess_dict[str(x)] = '_'
health = 10
victory = False
values = list(guess_dict.values())
print(values)
while victory == False:
letter = input('Choose the letter: ')
if letter in word_dict.values():
guess_dict[list(word_dict.keys())[list(word_dict.values()).index(letter)]] = letter
valori = list(guess_dict.values())
print(valori)
print()
if guess_dict == word_dict:
victory = True
print ('You won')
else:
health -= 1
print('ERROR!! ' + str(health) + ' lives remaining')
if health == 0:
print('You lose')
break
Your problem is exactly the dictionary. The dictionary has only one entry for each key. See here
In my opinion, you should use either a list, or a list of dictionaries.
import os
word = input('choose the word to play with: ')
os.system('cls')
word_list = list(word)
guess_list = [{'character': x, 'guessed': False} for x in word]
health = 10
victory = False
while True:
str = ''
for item in guess_list: #generate the string each iteration once
if False == item['guessed']:
str = str + "'_'"
else:
str = str + "'" + item['character'] + "'"
print(str)
if True == victory: #put the test here, so that the result is printed
print('You won!')
break
else:
letter = input('Choose the letter: ')
hit = False
missed_cnt = 0
for item in guess_list:
if item['character'] == letter: #if letter guessed, set flag
item['guessed'] = True
hit = True
if item['guessed'] == False: #count unguessed letters
missed_cnt +=1
if False == hit:
health -= 1
print('ERROR!! {0} lives remaining'.format(health))
if 0 == health:
print('You lose!')
break
if 0 == missed_cnt: #exit only after printing result
victory = True
Instead of a dictionary, you could use a set(). Since guessing a letter reveals all instances of that letter, removing it from the set corresponds to the same notion.
So you could do something like this:
word = input("hidden word:")
remainingLetters = set(word)
health = 10
while True:
print( "".join( "_" if letter in remainingLetters else letter for letter in word) )
letter = input("guess a letter:")
if letter in remainingLetters:
remainingLetters.remove(letter)
if remainingLetters: continue
print("you Win!")
break
health -= 1
if health == 0:
print("You lose")
break
print('ERROR!! {0} lives remaining'.format(health))
I would simply use a list of letters:
import os
from copy import deepcopy
word = list(input('choose the word to play with: '))
compare = deepcopy(word)
os.system('cls')
guess = []
for index, letter in enumerate(word):
guess.append('_')
health = 10
victory = False
while not victory:
letter = input('Choose the letter: ')
if letter in compare:
guess[compare.index(letter)] = letter
compare[compare.index(letter)] = ' '
print(guess)
print()
if guess == word:
victory = True
print ('You won')
else:
health -= 1
print('ERROR!! ' + str(health) + ' lives remaining')
if health == 0:
print('You lose')
break
The deepcopy in the beginning is because in Python if you do compare = word, compare would become a pointer to word. The variable compare by the way is to remove the already guessed characters from.
You could also check the input letter to make the code more robust:
while not victory:
letter = input('Choose the letter: ')
try:
value = float(letter)
print('Please enter a letter of type (str).')
continue
except ValueError:
pass
if len(letter) != 1:
print('Please enter only one letter!')
continue

Instead of using global what to use for my situation in my hangman game (python)

i am wondering whether there is other way to solve my situation(replace user input(guessword) into dashes string(words) in my Hangman Game than to use global. My previous posts for the game: How to replace the repeat word in python (Hangman Game)! and How do i detect the repeat input in my hangman game (Python)! and here is my code:
code from beginning:
def writeCustomwords():
f = open('custom.txt', 'w')
words = input("Enter a list of comma separated words:")
print("Custom words save into custom.txt")
f.write(words)
f.close()
def readFileWords():
if choose == "1":
txt = open('easy.txt', 'r')
txt.read()
txt.close()
elif choose == "2":
txt = open('intermediate.txt', 'r')
txt.read()
txt.close()
elif choose == "3":
txt = open('hard.txt', 'r')
txt.read()
txt.close()
elif choose == "4":
txt = open('custom.txt', 'r')
txt.read()
txt.close()
import random
def getRandomWord():
if choose == "1":
with open('easy.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print(random_word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "2":
with open('intermediate.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "3":
with open('hard.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "4":
with open('custom.txt') as txt:
word = txt.read().split(",")
random_word = random.choice(word)
print(random_word)
print("\nThere are", len(random_word)-random_word.count(" "),"letters in this word")
return random_word
def gethiddenWord():
import re
guess = getRandomWord().lower()
guessed = re.sub(r"\S", "-", guess)
print("\n\t\t\t-----------------------------------------------")
print("\t\t\tRULES")
print("\t\t\t-----------------------------------------------")
print("\n\t\t\tPlease Guess one letter(a-z) at a time!")
print("\n\t\t\tIf you want to guess the word, please enter '0'")
print("\n\nThe word is : ",guessed)
return guess,guessed
def checkValidGuess():
if len(guessword)==1 and guessword not in guesslist and guessword not in num:
return True
elif guessword in guesslist:
print("You have already guessed that letter")
elif guessword in num:
print("You can only input letter a-z")
print("Try again")
elif len(guessword) >1:
print("You can only guess one letter at a time!")
print("Try again")
def checkPlayerWord():
if guessall == word:
return True
else:
return False
return checkp
def checkLetterInWords():
if guessword.lower() in word:
return True
elif guessword.lower() not in word and guessword.lower() not in num:
return False
def gethiddenWord():
import re
guess = getRandomWord().lower()
guessed = re.sub(r"\S", "-", guess)
print("\n\t\t\t-----------------------------------------------")
print("\t\t\tRULES")
print("\t\t\t-----------------------------------------------")
print("\n\t\t\tPlease Guess one letter(a-z) at a time!")
print("\n\t\t\tIf you want to guess the word, please enter '0'")
print("\n\nThe word is : ",guessed)
return guess,guessed
my problem is here:
def getGuessedWord():
global words
for pos,l in enumerate(word):
if l==guessword.lower():
words= words[:pos] + guessword.lower() +words[pos+1:]
print(words)
return words
And outside the function
word,words = gethiddenWord()
my further code to access function:
choose = input("Enter your choice:")
readFileWords()
time =10
word,words = gethiddenWord()
count = len(word)-word.count(" ")
guesslist=[]
while time !=0 and word:
print("You have", time, "guesses left.")
guessword = input("Guess a letter or enter '0''to guess the word: ")
num = ["1","2","3","4","5","6","7","8","9"]
valid = checkValidGuess()
guesslist.append(guessword.lower())
if guessword =="0":
guessall = input("What is the word: ")
checkp = checkPlayerWord()
del guesslist[0]
if checkp == True:
print("Well done! You got the word correct!")
break
elif checkp == False:
print("Uh oh! That is not the word!")
time -=1
elif valid== True:
checkl= checkLetterInWords()
if checkl == True:
time -=1
print("Well done!",guessword,"is in my word")
count -= word.count(guessword)
getGuessedWord()
countfinish = checkFinish()
if countfinish == True:
break
else:
continue
elif checkl == False:
time -=1
print("Uh oh! That letter is not in my word!")
If without global, i cannot solve it. Please help! Thanks

How to check if a single letter (which has been input as a string variable) is equal to any character in another string?

I am trying to make a hangman game at the minute and this is the code so far:
word = raw_input("Please enter a word")
correctguesses = []
wrongguesses = []
guesscorrect = False
while guesscorrect == False:
guess = raw_input("Guess a letter")
if len(guess) != 1:
print "Your guess was more than one letter"
for i in word:
if guess == i in word:
print "correct"
correctguesses.append(guess)
print "here are your correct guesses so far" ,(''.join(correctguesses))
for i in word:
if guess != i in word:
print "incorrect"
wrongguesses.append(guess)
print "here are your wrong guesses so far:", (''.join(wrongguesses))
my output:
correct/
here are your correct guesses so far:/ e/
incorrect/
incorrect/
incorrect/
incorrect/
here are your wrong guesses so far:/ eeee/
It is doing that because it isn't the correct letter for the 4 other letters in hello (which was the word).
word = raw_input("Please enter a word")
correctguesses = []
wrongguesses = []
guesscorrect = False
while guesscorrect == False:
guess = raw_input("Guess a letter")
if len(guess) != 1:
print "Your guess was more than one letter"
continue #to prompt for input again
for i in word:
if guess == i: #i will be a letter in the word
print "correct"
correctguesses.append(guess)
print "here are your correct guesses so far" ,(''.join(correctguesses))
for i in word:
if guess != i: #put this case in the else block of the if in the previous loop and remove this loop
print "incorrect"
wrongguesses.append(guess)
print "here are your wrong guesses so far:", (''.join(wrongguesses))
I have commented some of the details.
This course might help with basics of python and programming.

Categories