Add error if no vowel detected in input string [duplicate] - python

This question already has answers here:
How to check if a string contains a string from a list?
(5 answers)
Check presence of vowels in a string
(6 answers)
Closed 5 years ago.
I'm writing a program that is supposed to take an input and output what the most common vowel is as seen here:
while True:
string = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in string.upper() if c in vowel)
most = {k: x[k] for k in x if x[k] == max(x.values())}
for i in most:
vowel = i
y = most [i]
print("The most frequently occurring vowel in the string is: " ,vowel, "with ,y, "occurrences.")
break
But I can't figure out how to have an error message if there are no vowels in the input. I have tried:
if vowel != string:
print("Error, no vowels were detected in the user input.")
continue
But this doesn't work. If I put it before the section where it outputs the most common vowel, then no matter what is input the error message shows and the input starts again. If I put it after that, then the vowels are detected and most common is printed, but it continues to display the error message and restart the input instead of breaking the program.
How can I write the error so that it looks at the input to see if there are any vowels in there and displays the error if there aren't any?

Since you already have a counter of all vowels (x) it would be a waste to check (again) whether user input contains vowels. You could simply check that x is empty (i.e., that it has not counted any vowels):
if not x:
print("Error, no vowels were detected in the user input.")
continue
In addition, consider either dropping .upper() from c for c in string.upper() if c in vowel OR dropping lower case letters from vowel = "aeiouAEIOU". Keeping both is unnecessary.

Related

List is becoming None type in python [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 1 year ago.
The program is for hangman with hints (MIT OCW 6.0001 ps 2 ). It is supposed to check whether the word I have guessed up to now (here my_word "a_ple") can be the word chosen by the game (other_word). Hence in "a_ple" and "apple", since I have already guessed "p" but I still have the position with index[1] as a "_" it means that the word cannot be apple and the output printed should be false
my_word="a_ple"
other_word = "apple"
import string
def match_with_gaps(my_word, other_word):
matching = False
alphabet="string.ascii_lowercase"
alphabet=list(alphabet)
if len(my_word) == len(other_word):
for i in range(len(my_word)):
if my_word[i] != "_":
for a in range(len(other_word)):
if my_word[i] == other_word[a]:
if my_word[a] != "_":
print(type(alphabet)) #to check error in alphabet
if my_word[i] in alphabet:
matching = True
else:
break
else:
break
alphabet = alphabet.remove(my_word[i])
return matching
print(match_with_gaps(my_word, other_word))
Output :
I get one output as class list and then in the second iteration I get "can't perform remove on NoneType"
I am not understanding at which step is my alphabet list becoming None Type.
I tried using a clone of alphabet but it was yielding the same outcome
alphabet = alphabet.remove(my_word[i])
remove has no return (it's an inplace function as MisterMiyagi mentioned), see:
https://docs.python.org/3/tutorial/datastructures.html
so if you assign x = foo.remove("foo"), x will be None. Don't use the return of remove().

How do I take letters out of a list? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I am trying to make a program where it takes in user input and spits out the input without the letters. I'm really confused on why this isn't working.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = list(numText) # Turns ^ into list
for char in numList: # Every character in the list
if char.isalpha(): # Checks to see if the character is a letter
numList.remove(char) # Removes the letter from the list
print(numList) # Prints the new list without letters
input("") # Used so the program doesnt shut off
I know this is really dumb so im sorry for asking.
You should not iterate and remove at the same time, instead use a list comprehension.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = [char for char in numText if not char.isalpha()]
print(numList) # Prints the new list without letters
input("")

I need to define a function that determines the matching letters between words and returns back as a integer [duplicate]

This question already has answers here:
Comparing 2 variables characters (Python)
(3 answers)
Closed 4 years ago.
I need to define a function that compares words which determines matching letters before printing a message to tell the user how many letters of the guessed word are correct. It also needs to return back to the program as an integer. The function should return the number of matching letters and should not print anything
I am unsure how to do this?
def compareWords(word1, word2):
This will do the job, it loops over both the words and compares every letter pair.
def compareWords(word1, word2):
count = 0
for char1, char2 in zip(word1, word2):
if char1 == char2:
count += 1
return count
Naive method of solving this problem is to compare each character in word2 with word1
Sample Code :
def compareWords(word1,word2):
count = 0
for ch in word2:
if ch in word1:
count=count+1
return count
Hope this helps !

Translation from English to Pig Latin

I'm doing part of the 'PigLatin translation' program.
Here is the part I'm doing writing right now.
input_str = input("Input a word: ")
consonant_check = 0
while input_str[int(consonant_check)] != 'a' or 'e' or 'i' or 'u':
output_str = input_str[:int(consonant_check)] + input_str[0,int(consonant_check)] + 'ay'
consonant_check = int(consonant_check) + 1
else:
print(output_str)
This part is supposed to check if the word input begins with a consonant. If it does, the program could remove all consonants from the beginning of the word and append them to the end of the word. Then append "ay" to the end of the word.
By collecting information online I had some clues about how to make it happen but I think there are still something wrong with my code.
I would approach it similar to what you intended, resulting in the code below.
In short, check the first character of a string. If it's not a vowel (not in ['a','e','i','o','u']), move the character to the end of the string. Keep doing that until you hit a vowel (so 'string' becomes 'trings' then 'ringst' then 'ingstr' before breaking the loop). Once you finally hit a vowel, you leave the loop, and print the modified string + 'ay'. If the first character is a vowel, you leave the loop and print the string + 'ay'.
There's no need to set a consonant check - you're always checking the first character (0). And there's no need to have two variables - just keep modifying and replacing the original string.
word_string = input("Input a word: ")
while word_string[0] not in ['a','e','i','o','u']:
word_string = word_string[1:] + word_string[0:1]
else:
print(word_string + 'ay')
This isn't a direct answer to your question, but my solution to the pig-latin problem. When learning python, I found that looking at completed examples helped a great deal.
word = "snake"
import string
# Create a list of vowels an consonants
vowels = ['a','e','i','o','u','y']
vowels += [v.upper() for v in vowels]
consonants = [x for x in string.ascii_letters if x not in vowels]
if word[0] in consonants:
# Find the first vowel
idx = min([word.find(v) for v in vowels if word.find(v)>0])
# Split the word at this point and add 'ay'
word = word[idx:] + word[:idx] + 'ay'
print(word)
# Returns "akesnay"
I think your logic is overall a little messed up. I would suggest tackling the problem like this.
1.) Check to see if the first letter is a consonant, if not, do nothing, if so, go to step 2
2.) Find all of the consonants in the word and store them in a list
3.) If it is, remove the vowels from the word, and then append all of the consonant onto the end, followed by 'ay'.
There are infinite ways to actually implement this and I think it would be a good exercise for you to try to implement it yourself, but let me know if you need any more help.

Verifying that a letter is in a python string - Why I got this result? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
I am new to programming, and am learning on Python 3.4. I am working on an exercise to determine if a user defined letter is a vowel or consonant.
My original if statement looked as follows:
letter = input('Enter a letter')
if letter == 'a' or 'e' or 'i' or 'u':
print('your letter is a vowel')
else:
print ('your letter is a consonant')
this returned that my letter was a vowel every time.
I have since learned the answer was to have an if statement that looks as follows:
if letter == 'a' or letter == 'i' or .......
My question is why did my original if statement return that it was a vowel every time, and not give me an error?
My though process is that it is verifying that it is a string.
Any non-zeroish value evaluates to True in a condition. Also, comparison operators (== in this case) have higher priority than logical operators (or,and,not). (Details: https://docs.python.org/3/library/stdtypes.html)
So python interpreted your if statement as:
if (letter == 'a') or ('e') or ('i') or ('u'):
Since 'e' is not zero or zero-like, that part of the if was true, so your expression was true.
An easier approach than your working solution is:
if letter in 'aeiou':
Which checks if letter is a character in the string.

Categories