Python Function not returning result - python

So this code has worked correctly without the try clause, but I need it to work in this manner because I want to continue prompting the user for input and give an option to exit. Ive searched and cant find a similar questions asked. Can someone please take a look and see what Im missing, thanks.
vowels = 'aeiou'
def converter(word):
while True:
try:
first = word[0]
if first in vowels:
word = word + 'yay'
return word
else:
while word[0] not in vowels:
word = word[1:] + word[0]
word = word + 'ay'
return word
split = word.split()
translated = [converter(word) for word in split]
translated = " ".join(translated)
print(translated)
except ValueError:
if word.lower() == "exit":
word = word.lower()
print("Adios")
else:
print("Try again.\n")
converter(input('Words to translate into piglatin: '))

The problem with the code is that it enters an infinite while loop in the converter() function.
You should move the while loop outside the function:
while True:
converter(input('Words to translate into piglatin: '))
Then, you can process the input to check if the user wants to quit. If the user chooses not to quit, then you should pass the input string to the converter() function. You already have most of the components needed looking at your CodeHS link without the try/except block.

Related

python having a hard time at my letter guessing game

I'm trying to do a guessing game in python but I cant figure some stuff out. I have to enter a word and it will print a lot of spaces and the person is suppose to guess the word. It has to look like this after the word it's been typed. The user will enter a letter and is suppose to look like this (word is dog):
Enter a letter: a
So far you have:
***
if they guess the "o" for example, it will replace the * with an 'o' and so on until you get all the words right. And that's what I can't figure out, can somebody please help me? here is my program for far:
def main():
letters_guessed = set()
# Read word
word = input("\n Please Enter a word: ")
# print 100 spaces
print("\n" * 100)
# Storing the length of the word
word_length = len(word)
guess = '*' * word_length
while True:
print ("So far you have: ",
guess_letter = input ("Please guess a letter: ")
if len(guess_letter) != 1:
print ("Please guess one letter at a time")
if guess_letter in letters_guessed:
print ("\n You already guessed that letter, please try again")
letters_guessed.add(guess_letter)
if set(word) == set(letters_guessed):
break
print("You won, the word is " % word)
Somebody tried to help me but I just didn't understand how this works because I am new to the program, I want to be able to understand it also. Thank you. Here it was his output, just part of it.
while True:
print ("So far you have: ", "".join([c if c in letters_guessed else "*"
for c in word]))
guess_letter = input ("Please guess a letter: ")
I'll first explain the solution code you received. The following code:
[c if c in letters_guessed else "*" for c in word]
generates a list. If you see square brackets [ and ] , then we're list likely creating a list.
now what your friend is using is a generator. It's a short way of creating a for loop. In other words, this would do the same thing.
word = "dog"
letter_guessed = "go"
ourList = list() #new list
for letter in word: #we check every letter in the word
if letter in letter_guessed: #if our letter has been guessed
ourList.append(letter) # we can show that letter in our word
else:
ourList.append("*") # if the letter has not been guessed, we should
# not show that letter in our word, and thus we change it to a *
print(ourList)
This gives us the following list: ["*", "o", "g"]
What your friend then does, is take that list, and use join:
"".join[ourList]
This is a good way of turning a list of letters back into a string.
See: https://www.tutorialspoint.com/python/string_join.htm
Your own code has a few problems. Is it possible you didn't copy everything?
In python, using tabs effects the way your program runs. Because you put a tab before
print("You won, the word is " % word)
you'll run this line every single time, rather than only when the break statement is activated!
You have a similar problem with .add! Try to see if you can't spot it yourself.
I also recommend writing
print("You won, the word is " + word)
because this is much easier to use. (for more advanced formatting, look up .format() see https://pyformat.info/

How to use linear searches to search for letters in a user input word

I am finding it increasingly difficult to find the letters from a word that the user generated. The code I am using is on linear searches and can only display letters I have inputed.
Edit: To improve my question would like to know if I could search for a letter from the wordlist created in choice 1.
if choice == "1":
print ("Enter a Word")
minput= input()
wordList= list (minput)
print (wordList)
menu()
if choice== 2
letter=('a,b,c,d,e,f,g,h,f,h')
print ()
counter=0
searchLetter=input('Enter letter to find\t')
while counter<len(letter) and searchLetter!=letter[counter]:
counter+=1
if counter <len(letter):
print(searchLetter,'found')
else:
print(searchLetter, ' Not found')
As a commented, you can use the index() function to find the index of a letter in a string, like this:
letter = 'a,b,c,d,e,f,g,h,f,h'
searchLetter=input('Enter letter to find\t')
try:
index = letter.index(searchLetter)
except ValueError:
print("Letter not found")
else:
print('Letter found in index {0}'.format(index))
Here, I use a exception handler to check if the input exists in the string.
You can also use a condition, like this:
if searchLetter in letter:
...
You can use in parameter.
if letter in word:
print("word include that letter")

i need some assistance with my python pyglatin code

ok so the code is
pyg = 'ay'
print "To translate type A SINGLE word or name!"
original = raw_input("Type word Here:")
while len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word[1:] + first + pyg
print "Translating 1 moment..."
print "Translated view below!"
print new_word
print "Made by: Tobias Balentine"
raw_input ('pause')
if raw_input ("Do you want to start over?").lower().[0] != 'y': break
so my question is how do i restart to the start of the code without exiting the program when i put (if raw_input ("Do you want to start over?").lower().[0] != 'y': break) it just shows the translation again but i want it to go to the start of the code so you can type a different word to translate how would i go about doing this?
P.S. i am new to python
Copy this statement:
original = raw_input("Type word Here:")
inside your while statement. Your final code should be like this:
pyg = 'ay'
print "To translate type A SINGLE word or name!"
original = raw_input("Type word Here:")
while len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word[1:] + first + pyg
print "Translating 1 moment..."
print "Translated view below!"
print new_word
print "Made by: Tobias Balentine"
raw_input ('pause')
if raw_input ("Do you want to start over?").lower().[0] != 'y':
break
original = raw_input("Type word Here:")
As others have indicated, if you want to continually prompt the user for new words, you need to have that prompt be inside of the loop. You could do something like this, where you prompt the user in the loop, and then, if the input is valid, translate the word. If it's not, tell the user so. Then, in either case, you ask the user if she wants to start over, and break the loop if she doesn't say yes (or more accurately, if she types anything that doesn't start with a "Y" or "y").
pyg = 'ay'
print "To translate type A SINGLE word or name!"
while True:
original = raw_input("Type word Here:")
# Validate the input here. If it's valid,
# do the translation.
if original and original.isalpha():
word = original.lower()
first = word[0]
new_word = word[1:] + first + pyg
print "Translating 1 moment..."
print "Translated view below!"
print new_word
else:
# Tell the user if his input is invalid.
print "Your input was stupid. No translation 4 u."
# Ask the user if he wants to start over
if raw_input ("Do you want to start over?").lower()[0] != 'y':
break
# Give em something to remember you by
print "Made by: Tobias Balentine"

python improving word game

Im working on a word game. The purpose for the user is to guess a 5 letter word in 5 attempts. The user can know the first letter. And if he doesn't get the word correct, but if he has a letter in the correct place he gets to know this.
This is my code:
import random
list_of_words = ["apple","table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
attempts = 5
for attempt in range(attempts):
if attempt == 0:
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print ('Please enter a 5 letter word')
Else:
if answer != word:
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
print("correct, you have guessed the word in:", attempt, "attempts")
if answer != word:
print("Sorry maximum number of tries, the word is: %s" % word)
I have two questions about this code:
The first one is a small problem: If the user gives a 6 or 4 letter word it will still print the word. While I'd rather have it that the word is just ignored and the attempt isnt used..
If a letter is given correct (and also the first letter) it doesnt become a standard part of the feedback. Trying to get this with temp but of yet its not working great.
Any suggestions to clean up my code are also appreciated!
Thanks for your attention
I made some changes in your code, now it's working according to your specification. I also wrote a couple of explaining comments in it:
import random
list_of_words = ["apple", "table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
# changed the loop to a 'while', because i don't want to count the invalid length answers
# and wanted to exit the loop, when the user guessed correctly
attempts = 5
attempt = 0
correct = False
while attempt < attempts and not correct:
if attempt == 0:
# i stored a working copy of the initial hint (ex: "w....")
# i'll use this to store the previously correctrly guessed letters
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print("Please enter a 5 letter word")
else:
if answer != word:
# i simplified this loop to comparing the wordlist and answerlist and update templist accordingly
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
correct = True
print("Correct, you have guessed the word in %s attempts" % (attempt + 1))
attempt += 1
if answer != word:
# also i used string formatting on your prints, so is prints as a string, and not as a tuple.
print("Sorry maximum number of tries, the word is: %s" % word)
There are several problems with the code.
Just 1 for now. I notice in the sample output you are entering five letter words (beeds and bread) and it still prints out Please enter a 5 letter word.
These two lines:
if len(answer) != 4:
print ('Please enter a 5 letter word')
Surely this should be:
if len(answer) != 5:
print ('Please enter a 5 letter word')
continue
This would catch an invalid input and go round the loop again.
Answering your specific questions:
You will need to have a for loop around your input, keeping the user in that loop until they enter a word of appropriate length
If you move guessed letters to the correct places, it is trivial to win by guessing "abcde" then "fghij", etc. You need to think carefully about what your rules will be; you could have a separate list of "letters in the guess that are in the answer but in the wrong place" and show the user this.
To keep the display version with all previously-guessed characters, keep a list of the display characters: display = ["." for letter in answer], and update this as you go.
Other problems you have:
Too much hard-coding of word length (especially as len("plural") != 5); you should rewrite your code to use the length of the word (this makes it more flexible).
You only tell the user they've won if they guess the whole answer. What if they get to it with overlapping letters? You could test as if all(letter != "." for letter in display): to see if they have got to the answer that way.
Your list comprehension [i for i in answer if answer in word] is never assigned to anything.

Problem with my hangman game

I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?
import sys
import codecs
import random
if __name__ == '__main__':
try:
wordlist = codecs.open("words.txt", "r")
except Exception as ex:
print (ex)
print ("\n**Could not open file!**\n")
sys.exit(0)
rand = int(random.random()*5 + 1)
i = 0
for word in wordlist:
i+=1
if i == rand:
print (word, end = '')
break
wordlist.close()
guess = input("Guess a letter: ")
print (guess) #for testing purposes
for letters in word:
if guess == letters:
print ("Yessssh")
#guessing part and user interface here
In your "for word in wordlist" loop, each word will end in a newline. Try adding word = word.strip() as the next line.
By the way your last loop could be replaced with:
if guess in word:
print ("Yessssh")
Bonus tip: when adding "debug prints", it's often a good idea to use repr (especially when dealing with strings). For example, your line:
print (guess) #for testing purposes
Might be more useful if you wrote:
print (repr(guess)) #for testing purposes
That way if there are weird characters in guess, you'll see them more easily in your debug output.
This is what i did for my hangman game:
for x in range(0, len(secretword)):
if letter == secretword[x]:
for x in range(len(secretword)):
if secretword[x] in letter:
hiddenletter = hiddenletter[:x] + secretword[x] +hiddenletter[x+1:]
for letter in hiddenletter:
print(letter, end=' ')
secretword is the hidden word that the user is trying to guess.
hidden letter contains the amount of "_" in the word: i.e. hiddenletter = " _ " * len(secretword)
this replaces the blanks with the correctly guessed letters and then shows the underscores with the letters in the right places
i did my best...

Categories