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.
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)
Working on a homework question where all the vowels in a string need to be removed and if the letter "g" is beside a vowel, it would also be considered a vowel. For example given the string "fragrance" I want the string returned to say "frrnc"
This is what I have so far:
def disemvowel(text):
text = list(text)
new_letters = []
for i in text:
if i.lower() == "a" or i.lower() == "e" or i.lower() == "i" or i.lower() == "o" or i.lower() == "u":
pass
else:
new_letters.append(i)
print (''.join(new_letters))
disemvowel('fragrance')
# frgrnc
You can try using regex:
import re
def disemvowel(text):
return re.sub(r"G?[AEIOU]+G?", "", text, flags=re.IGNORECASE)
tests = {"fragrance": "frrnc", "gargden": "rgdn", "gargdenag": "rgdn", "gag": ""}
for test, value in tests.items():
assert disemvowel(test) == value
print("PASSED")
Output:
PASSED
Interesting, does this stack?
So if you had the word baggga, would the outer g's turn into vowels, which then would turn the inner g also into a vowel? So is the output bg or is it b?
You can either remove all g's next to vowels and then in a second step remove all vowels.
Or you could replace all g's next to vowels by, let's say 'a', and then remove all vowels. If the 'g is a vowel'-rule stacks, you may have to repeat the first step until the string does not change anymore.
You can add a variable to track if the previous letter was a vowel.
def disemvowel(text):
text = list(text)
new_letters = []
last_vowel_state=False
for i in text:
if i.lower() == "a" or i.lower() == "e" or i.lower() == "i" or i.lower() == "o" or i.lower() == "u":
last_vowel_state=True
pass
else:
if last_vowel_state==True and i.lower()=='g':
pass
else:
new_letters.append(i)
last_vowel_state=False
print (''.join(new_letters))
Input
disemvowel('fragrance')
Output
frrnc
Input
disemvowel('gargden')
Output
grgdn
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.upper())
I am writing code for a final project, which is an app that allows users to design their own license plate.
I want to write code that would basically allow the user to input an English word (which would be fewer than or equal to 10 characters long), then the app asks him if he wants to remove specific vowels from the word, then the app outputs the final word.
Because I am a beginner, I only know how to write code that would omit ALL vowels in whatever the user inputs. Ya feel?
The code I have tried so far:
keepOrDeleteVowel1 = input("Would you like to delete the vowels? Type 'yes' to delete vowels, or 'no' to type a new word.")
if keepOrDeleteVowel1 == "no" or "No" or "NO":
print("This is your word: " + original + "." + " Enjoy your new license plate! Thank you for using this app.")
break
elif keepOrDeleteVowel1 == "yes" or "Yes" or "YES":
firstLetter = original[0]
lastLetter = original[len(original)]
if firstLetter != "A" or firstLetter != "E" or firstLetter != "I" or firstLetter != "O" or firstLetter != "U" \
or lastLetter != "A" or lastLetter != "E" or lastLetter != "I" or lastLetter != "O" or lastLetter != "U":
original =original.remove("A")
original =original.remove("E")
original =original.remove("I")
original =original.remove("O")
original =original.remove("U")
print (original)
Sorry about the formatting. The code presented above should work to delete all vowels but only if the word does not start or end with a vowel. But I want to change this so to allow the user to delete vowels himself rather than having the program delete all vowels.
Please respond in detail, much appreciated.
You can ask the user for a vowel the same way you asked them for the original word, through input(). When you have saved that into a variable you can check to make sure that they have entered a vowel, if so you can go ahead and remove it like I've shown below. In order to avoid typing each vowel in lower and upper case while comparing I convert their input to lowercase with lower(), you can do the same for'no' as well.
vowel = input("Please, type the vowel.")
if vowel.lower() in "aeiou":
newOrig = original.replace(vowel, "")
print(newOrig)
else:
print("You have not entered a vowel.")
initial_word = input("Type the word: ")
vowel = input("Do you want to remove any vowel? If yes, type the vowel you want to remove: ")
if type(vowel) is str:
if len(vowel) == 1:
initial_word = initial_word.replace(vowel.lower(), '')
initial_word = initial_word.replace(vowel.upper(), '')
else:
print('Wrong input.')
print('The word is: ' + initial_word)
Output:
Type the word: AaxeyEizIoucU
Do you want to remove any vowel? If yes, type the vowel you want to remove: e
The word is: AaxyizIoucU