How are the letters deleted from this "Vowel eater"? - python

word = input("enter a word: ")
word = word.upper()
for letter in word:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter =="O":
continue
elif letter == "U":
continue
else:
print(letter)
If I used Joseph as an example, it would return JSPH but I have no idea how the vowels are "deleted"

The letter variable takes one character from the input and compares using the if-else statement. If the character matches the vowels the letter is not printed.
That means the program is only printing the non-vowel characters.

For continue, it essentially skips to the end of the loop and starts the next loop, so following through your loop:
Look at the current letter
If the current letter is a vowel, then continue. (This skips to the next letter in the loop, so the line print(letter) will not be run).
If the current letter is not a vowel, it reaches the else statement and prints the letter.
This means that in the end, the program only prints letters which are not vowels, as whenever a vowel is reached continue is run meaning it skips to the next letter (so the letter is not printed).
Side note: even if you didn't use continue in each elif statement, and used maybe pass instead (which is just a "blank" instruction), the code would still work as by entering one of the if or elif options in the if statement, it means that it won't run any of the other elif or elses afterwards, so the print(letter) wouldn't be called either way. A better way to show the use of continue would be to place the print(letter) outside and after the if statement.

Use regex
word = input("enter a word: ")
word = word.upper()
import re
re.sub("[AEIOU]","", word)

Related

Issue with analyzing strings in Python for Wordle-esque progam

I've created a function that takes a user-inputted guess, compared it to a hidden word taken randomly from a word doc, and returns a string that indicates if any letters match or are in the word at all. Here is the function:
def wordResults(guess, testGuess):
#guess = user inputted guess
#testGuess = secret word
results = ""
for i in range(5):
#Check if letters at given position match
#in each word, append capital letter if so
if guess[i] == testGuess[i]:
results += guess[i].upper()
#Check if letter at given position is in
#the secret word at all, append lowercase
#letter if so
elif testGuess.find(guess[i]) != -1:
results += guess[i]
#Append underscore if neither condition is met
else:
results += "_"
return results
My issue lies with the elif-statement. I would like it to print a lowercase only if that letter appears in the word, but not if the letter is already in the correct spot. Here is the program running to show what I'm referring to:
(Note: the hidden word is also user-inputted until I get the program working as intended)
For Guess #2, I would like it so that the first 'h' does not show up, since it is indicating the 5th letter in 'conch' that is already confirmed with a capital 'H'. Hope that makes sense.
It's a lot easier to work with a list and then make it a string at the end:
guess = guess.lower()
testGuess = testGuess.lower()
result = []
for i, letter in enumerate(guess):
if letter in testGuess:
if letter == testGuess[i]:
result.append(letter)
else:
result.append(letter.upper())
else:
result.append('_')
for i, letter in enumerate(result):
if letter.upper() in result and result[i] != letter:
result[i] = '_'
return ''.join(result)
For guess two, then the second loop checks if each letter is already in the loop and placed correctly and if it's not in the correct spot, makes it back into an _.

How to find words without certain letters in them and certain letters in the same place that are in specified length

I want to make a hangman game that randomises the word each time you guess a letter, but keeps the wrong letters wrong and the ones you guessed at the same place in the new word. (Like if your word was cat in the beginning and you guessed the 'a'; now the word can be hat.)
I feel like I want to implement too many statements in a while loop and it breaks somehow.
I have this function
def RevealLetters(inputLetter):
LetterPositons.clear()
global WrongGuessCounter
for pos,char in enumerate(Word):
if(char == inputLetter):
LetterPositons.append(pos)
for x in LetterPositons:
if MaskedWord[x] == "_":
MaskedWord[x] = inputLetter
if len(LetterPositons) == 0:
WrongGuessCounter += 1
WrongLetters.append(inputLetter)
Which adds the wrongly guessed letter to a list and those letters should not be used again.
Then in another function I have this while loop which should be able to go thru the list of words and select words that are a specified length (the length was set in another function)
def RandomiseWord():
global Word
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while (len(Word) != len(MaskedWord)) and (all(letter in Word for letter in WrongLetters)) :
Word = random.choice(WordBank)
but this somehow gives me words that either contain a letter from the list or a word with a different length.
I tried using if statements inside the while but it broke it further.
And lastly how may I check for words that have the same letters in the same place?
The issue was in my while. it has to be the "Or" statement.
in the end the randomise function looked like this:
def RandomiseWord(): #Randomises the word to add a challange to the game
global Word
global MaskedWord
global WrongLetters
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while len(Word) != (len(MaskedWord)+1) or all(letter in Word for letter in WrongLetters) or not all(CheckWord()) :
Word = random.choice(WordBank)
and for finding words with letters in the same place I used:
def CheckWord(): #checks if the word contains the letters in the same place as the hidden one
global MaskedWord
global Word
Match = []
LetterList = list(Word)
LetterList.pop()
for x in range(len(MaskedWord)):
if MaskedWord[x] == "_":
continue
elif MaskedWord[x] == LetterList[x]:
Match.append(True)
else:
Match.append(False)
return Match

How do I check for error in Python to stop it from looping?

I am a beginner Python learner. This keeps looping and I couldn't seem to find the error in this to get it corrected. Any help would be appreciated. Thanks.
sentence = "that car was really fast"
i = 1
while i > 0:
for char in sentence:
if char == "t":
print("found a 't' in sentence")
else:
print("maybe the next character?")
If you only want to determine whether the letter "t" is in the sentence, this can be done very simply with Python's in operator:
if 't' in sentence:
print("found a 't' in sentence")
If you want to iterate over every letter in the sentence and print a line of output for each one depending on what it is, you only need a single for loop:
for char in sentence:
if char == "t":
print("found a 't' in sentence")
else:
print("maybe the next character?")
If you want to stop this loop as soon as you find a "t", the way to do that is break:
for char in sentence:
if char == "t":
print("found a 't' in sentence")
break
print("maybe the next character?")
You have set i = 1 but in the while loop there is nothing that changes the value of i to eventually become 0 and break out of the loop. Also, you don't even need the while loop because you are just iterating over the characters in the string sentence, so just do this:
sentence = "that car was really fast"
for char in sentence:
if char == "t":
print("found a 't' in sentence")
else:
print("maybe the next character?")
I think what you want is to print 'found t in sentence' if the char is a 't' and else print 'maybe the next character?'.
You should not use the while loop in this program only for loop will suffice what you are trying to do.

Negating string comparison in `if` confusing

The output of this confuses me! when the output of == are N and M, Shouldn't the output of != be A and I?. Word entered is "Nima".
word = input("Enter a word:")
UpperWord= word.upper()
for letter in word:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
else:
print(letter)
word = input("Enter a word:")
UpperWord= word.upper()
for letter in word:
if letter != "A":
continue
elif letter != "E":
continue
elif letter != "I":
continue
elif letter != "O":
continue
elif letter != "U":
continue
else:
print(letter)
The condition if letter != "A" is true for all letters but 'A', and for all of them, you execute continue and skip to the next iteration of the loop. The elif letter != "E" statement is executed only when the letter is 'A'. Since the letter is already known to be 'A', the condition is always true and the second continue statement is always executed. The second code fragment never produces any output.
Here's what you want:
for letter in UpperWord:
if letter not in "AEUIO":
continue
print(letter)
As DYZ says, the second code fragment would never produce output, because it actually continues the loop for all letters.
Remember, thee code executes from top to bottom, so to avoid this issue, check all of the vowels at once.
You also initialize UpperWord, but never use it, so unless the character is uppercase, it will always fall through. Here is the combination of both fixes:
vowelString = "AEIOU"
word = input("Enter a word:")
upperWord= word.upper()
for letter in upperWord:
if letter not in vowelString:
print(letter)
If you're up for it, I would also recommend researching Regular Expressions, or RegEx. This is a pattern-matching system that would make it much easier to match things going forward.
The solution with regex would look like:
import re
vowelRegex = re.compile(r"[aeiouAEIOU]")
word = input("Enter a word:")
for letter in word:
if vowelRegex.match(letter)==None:
print(letter)
This would easily allow you to expand your searched characters, as well as expanding to searching for more complex patterns.
Python Regex Documentation
Regex Playground

Python loops program

The point of the below program so far is to obtain the nearest 1 vowel by iterating from the location of the consonant on the alphabet list until the end of the alphabet list. Ones the loop finds the nearest (to the right) vowel, the loop should stop iterating and assign the index and letter of that vowel to the afterVowel and afterVowelIndex variables. The same should be done with every consonant (that is, if the current iteration of the input (word) is a consonant, we put it on the alphabet list and then iterate though the alphabet list to find the nearest-to-the-right vowel, then stop).
The problem is, it iterates though the alphabet list and outputs all the vowels to the right of the consonant on the alphabet instead of only one.
I tried using break, while loops with conditionals, and other techniques and nothing works, unfortunately.
How can this be fixed?
PS. The print statement below is used to check if one or more vowels are outputted; it is not an actual part of the program.
def rovarspraket(word = raw_input("Please enter a word: ")):
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a','e','i','o','u']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
for character in range(len(word.lower())):
for c in range(len(consonants)):
if word[character] == consonants[c]:
currentConsonant = word[character]
#2. Determine After and Before vowels
#After vowel
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV]:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
I'm hoping I understand your question correctly. If I am, couldn't you solve this with just one boolean flag?
def rovarspraket(word = raw_input("Please enter a word: ")):
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a','e','i','o','u']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
for character in range(len(word.lower())):
for c in range(len(consonants)):
if word[character] == consonants[c]:
currentConsonant = word[character]
#2. Determine After and Before vowels
#After vowel
flag = False
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV] and not flag:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
flag = True
break will exit out of one loop. You need a flag to break out of the second:
done = False
for a in range(alphabet.index(word[character]), len(alphabet)):
for aV in range(len(vowels)):
if alphabet[a] == vowels[aV]:
afterVowel = alphabet[a]
afterVowelIndex = a
print afterVowel, afterVowelIndex
done = True
break
if done:
break

Categories

Resources