The while loop in my Hangman game isn't working - python-3.x

answer = input("Type word here: ").lower()
word_amount = len(answer.split())
maximum_words = 1
while maximum_words != float(word_amount):
print("False input, 1 Word only!")
answer = input("Type word here: ").lower
word_amount = len(answer.split())
counter = 0
while counter != 20:
counter += 1
print("Can't see this!!!!!!")
guess_amount = 0
guess = input("Guess the word: ").lower()
while guess_amount != 9:
if answer == guess:
guess_amount = 9
print("You win!!!")
else:
print("Nope")
guess_amount += 1
guess = input("Guess again: ").lower()
if guess_amount == 9 and answer != guess:
print("You lose!!!")
This is the entire code to my hangman game, where person 1 types in word and then person 2 has 10 tries to guess the word, everything works fine except for this while loop:
answer = input("Type word here: ").lower()
word_amount = len(answer.split())
maximum_words = 1
while maximum_words != float(word_amount):
print("False input, 1 Word only!")
answer = input("Type word here: ").lower
word_amount = len(answer.split())
When I run the game and type in more then one word the game is supposed to go into a loop and is supposed to keep on asking to type in one word only. But when I run it, type in more than 1 word and then 1 word(which should stop the loop), it says that "split" is not a defined function and I don't know why that is. Would be glad if someone could help me. Thank you in advanced :)

You did a mistake in this line.
answer = input("Type word here: ").lower
You forgot to put brackets after lower.
Just use lower() instead of lower
You will get the desired output:
Type word here: hello how are you
False input, 1 Word only!
Type word here: hello fine
False input, 1 Word only!
Type word here: hello hi
False input, 1 Word only!
Type word here:

Related

Working of the interpreter in this program

This may sound like a stupid question but I had to ask. The following code checks whether a word entered by the user is a palindrome or not. When I use the below code, it says "This word is a Palindrome" for all the words.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
k-=1
b=True
else:
b=False
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
But when I do this small change in the next block of code, it correctly detects whether the word is palindrome or not. I got this in a trial and error basis.
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
b=True
else:
b=False
k-=1
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
Please help. Thanks in advance.
At the moment, some of the issue is that your "final" answer is based on the "last" test. What you really want to do is say "Not a Palindrome" as soon as you determine that and then stop.
Try:
is_a_palindrome = True
for index in range(len(word)):
if word[index] != word[- (index+1)]:
is_a_palindrome = False
break
Note as well, that this can be technically simplified to:
is_a_palindrome = word == "".join(reversed(word))

Python program won't append more than one value

Whenever I try to append(guesses) to the all_guesses variable it seemingly replaces the existing value from the previous loop. I want the program to record down all the player's number of guesses per game round but it only record the most recent value. I made sure the variable isn't in the while loop so that it doesn't overwrite it, so what's wrong? I'm really new to python programming so I can't seem to figure this out. Each time I run the loop the guessed and all_guesses values are reset to their original.
This is a snippet of my program:
def main():
guesses = 0
guessed = []
all_guesses = []
guess = input('\nPlease guess a letter: ').lower()
letter = 'abcdefghi'
answer = random.choice(letter)
while len(guess) != 1 or guess not in letter:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ')
while len(guess) < 2 and guess in letter:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
else:
if guess == answer:
guesses = guesses + 1
played = played + 1
print("\nCongratulations, that is correct!")
replay = input('Would you like to play again? Type y/n: ').lower()
all_guesses.append(guesses)
The short answer would be that all_guesses needs to be a global defined outside of main and the replay logic also needs to wrapped around main.
You seem to be missing logic, as you never modify guessed but expect to find things in there. And there are dead ends and other missing parts to the code. As best as I can guess, this is roughly what you're trying to do:
from random import choice
from string import ascii_lowercase as LETTERS
all_guesses = []
def main():
guessed = []
answer = choice(LETTERS)
guess = input('\nPlease guess a letter: ').lower()
while len(guess) != 1 or guess not in LETTERS:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ').lower()
while len(guess) == 1 and guess in LETTERS:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
continue
guessed.append(guess)
if guess == answer:
print("\nCongratulations, that is correct!")
break
guess = input("\nIt's not that letter. Try again: ").lower()
all_guesses.append(len(guessed))
while True:
main()
replay = input('Would you like to play again? Type y/n: ').lower()
if replay == 'n':
break
print(all_guesses)

limiting the number of character

i would like to know how to put limit on how many character can player put
thinking to limit it by one letter per answer.
it's a guessing game but the computer can only answer yes or no.
five chances to guess a letter.
then need to guess the right word after 5 tries.
import random
words = dict(
helium = "type of element",
korea="a country in asia",
peugeot="brand of a car",
bournemouth="a good place for holiday")
word=list(words)
choice=random.choice(word)
x=list(choice)
score=0
chance=5
print("\n\n\t\t\t WELCOME TO GUESSING GAME")
print("\t\t\tYOU HAVE 5 CHANCES TO GUESS THE WORD")
print("\nit has a", len(choice),"letters word")
print("and this is a clue", (words[choice]))
while word:
guess = input("is there a letter :")
if guess in choice:
print("yes")
else:
print("no")
score +=1
if score == chance:
print("time to guess the right word")
guess = input("and the word is :")
if guess == choice:
print("well done you guess the right word which is ", choice.upper())
break
else:
print("better luck next time the right word is ", choice.upper())
break
Hope this is what you want:
First you should make a new function:
def own_input(text=""):
user_input = ""
# While the length of the input string is not 1
while len(user_input) != 1:
# Ask user for input with message
user_input = input(text)
Now you can use it like this:
a = own_input("Character: ")

Returning to my if statement

This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the while statements. Any advice would be appreciated.
print('Welcome to Word Madness!!')
vowels = list('aeioyu')
consonants = list('bcdfghjklmnpqrstvwxz')
wordCount = 0
complete = False
while not complete:
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
print('You chose to enter: ',str(mode))
#When user chooses to quit program will system exit
if mode == 'quit':
print('Sorry to see you go! Come back to Word Madness soon!')
import sys
sys.exit(0)
#If vowels are selected then they will be counted
if mode == 'vowels':
word = input('Please enter your word!')
number_of_vowels = sum(word.count(i) for i in vowels)
print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice == 'n':
averageV = int(number_of_vowels // wordCount)
print('Your average number of Vowels was: ',averageV)
print('Thank you for using Word Madness!')
complete = True
else:
mode = 'vowels'
#If consonants are selected then they will be counted
elif mode == 'consonants':
word = input('Please enter your word!')
number_of_consonants = sum(word.count(i) for i in consonants)
print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
#If user has no more words to enter then they are given an average
else:
mode == 'consonants'
else:
print('ERROR! INVALID INPUT DETECTED!')
From your question and the comment, I assume that you want to ask
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
only once. If that is the case, you can move that statement just above the while loop.
Or also, you can give an option whether user really wants to specify the mode again.
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)
So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:
After every
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
Add
elif choice == 'n':
function()
Function() --> Calling the main function.

How can you compare frequency of letters between two words in python?

I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')

Resources