This is a module in my program:
def runVowels():
# explains what this program does
print "This program will count how many vowels and consonants are"
print "in a string."
# get the string to be analyzed from user
stringToCount = input("Please enter a string: ")
# convert string to all lowercase letters
stringToCount.lower()
# sets the index count to it's first number
index = 0
# a set of lowercase vowels each element will be tested against
vowelSet = set(['a','e','i','o','u'])
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
# sets the loop to run as many times as there are characters
# in the string
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
# prints results
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
# runs the main menu again
getSelection()
However, when I test this program, I get this error:
line 28, in runVowels
stringToCount = input("Please enter a string: ")
File "<string>", line 1
PupEman dABest
^
SyntaxError: unexpected EOF while parsing
I tried adding a + 1 to the "while index < len(stringToCount)" but that didn't help either. I'm pretty new to python and I don't really understand what's wrong with my code. Any help would be appreciated.
I researched this error, all I found out was that EOF stands for end of file. This didn't help at all with resolving my problem. Also, I understand that sometimes the error isn't necessarily where python says the error is, so I double-checked my code and nothing seemed wrong in my eyes. Am I doing this the round-about way by creating a set to test the string elements against? Is there a simpler way to test if string elements are in a set?
Question resolved. Thank you to all!
Looks like you're using Python 2. Use raw_input(...) instead of input(...). The input() function will evaluate what you have typed as a Python expression, which is the reason you've got a SyntaxError.
As suggested use raw_input. Also you don't need to do this:
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
Strings in Python are iterable, so you can just do something like this:
for character in stringToCount:
if character in vowelSet : # Careful with variable names, one is a list and one an integer, same for consonants.
vowels += 1
elif character in consonantsSet: # Need this, if something is not in vowels it could be a number.
consonants += 1
else:
print "Your entry should only include letters."
This should do just fine. Using a while is not necessary here, and very non-Pythonic imho. Use the advantage of using a nice language like Python when you can to make your life easier ;)
You can count the vowels like so:
>>> st='Testing string against a set of vowels - Python'
>>> sum(1 for c in st if c.lower() in 'aeiou')
12
You can do something similar for consonants:
>>> sum(1 for c in st if c.lower() in 'bcdfghjklmnpqrstvwxyz')
26
Also,
if stringToCount[index] in vowels:
should read
if stringToCount[index] in vowelSet:
Here's another way you could solve the same thing:
def count_vowels_consonants(s):
return (sum(1 for c in s if c.lower() in "aeiou"),
sum(1 for c in s if c.lower() in "bcdfghjklmnpqrstvwxyz"))
To wit:
>>> count_vowels_consonants("aeiou aeiou yyy")
(10, 3)
>>> count_vowels_consonants("hello there")
(4, 6)
Python truly is grand.
The errors in your file run as follows (plus some suggestions):
stringToCount = input("Please enter a string: ")
This should be raw_input if you want what the user typed in as a string.
stringToCount.lower()
The .lower() method returns a new string with its letters lowered. It doesn't modify the original:
>>> a = "HELLO"
>>> a.lower()
"hello"
>>> a
"HELLO"
vowelSet = set(['a','e','i','o','u'])
Here you could just as easily do:
vowelSet = set("aeiou")
Note you also don't strictly need a set but it is indeed more efficient in general.
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
Please, you don't need comments for such simple statements.
index = 0
while index < len(stringToCount):
You usually don't need to use a while loop like this in python. Note that all you use index for is to get the corresponding character in stringToCount. Should instead be:
for c in stringToCount:
Now instead of:
if stringToCount[index] in vowels:
vowels += 1
index += 1
You just do:
if c in vowels:
vowels += 1
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
Not quite right. You're checking that a character doesn't equal a set. Maybe you meant:
elif c not in vowels:
consonants += 1
But then there'd be no else case... Got to fix your logic here.
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
The above is more pythonically written as:
print "In your string, there are: %s vowels %s consonants" % (
vowels, consonants)
# runs the main menu again
getSelection()
Not sure why you're calling that there - why not call getSelection() from whatever calls runVowel()?
Hope that helped! Enjoy learning this great language.
Bah, all that code is so slow ;). Clearly the fastest solution is:
slen = len(StringToCount)
vowels = slen - len(StringToCount.translate(None, 'aeiou'))
consonants = slen - vowels
...note that I don't claim it's the clearest... just the fastest :)
Related
My name is Shaun. I am 13 years old and trying to learn python.
I am trying to make a program that finds vowels in an input and then prints how many vowels there are in the input the user gives.
Here is the code:
s = (input('Enter a string: ')) # Let the user give an input (has to be a string)
Vwl = [] # Create an array where we will append the values when the program finds a vowel or several vowels
for i in s: # Create a loop to check for each letter in s
count_a = 0 # Create a variable to count how many vowels in a
count_e = 0 # Create a variable to count how many vowels in e
count_i = 0 # Create a variable to count how many vowels in i
count_o = 0 # Create a variable to count how many vowels in o
count_u = 0 # Create a variable to count how many vowels in u
The function below is pretty long to explain, so summary of the function below is to find a vowel in s (the input) and make one of the counters, if not some or all, increase by 1. For the sake of learning, we append the vowels in the array Vwl. Then, it prints out Vwl and how many letters there are in the list by using len.
if s.find("a" or "A") != -1:
count_a = count_a + 1
Vwl.append('a')
elif s.find("e" or "E") != -1:
count_e = count_e + 1
Vwl.append("e")
elif s.find("i" or "I") != -1:
count_i = count_i + 1
Vwl.append("i")
elif s.find("o" or "O") != -1:
count_o = count_o + 1
Vwl.append("o")
elif s.find("u" or "U") != -1:
count_u = count_u + 1
Vwl.append("u")
print(Vwl)
print(f"How many vowels in the sentence: {len(Vwl)}")
For some odd reason however, my program first finds the first vowel it sees, and converts the whole string into the first vowel it finds. Then it prints down the wrong amount of vowels based on the array of vowels in the array Vwls
Could someone please help me?
The reason your code only prints out the first vowel is because the if statements you coded are not inside a loop, that part of the code runs once and then it finishes, so it only manages to find one vowel.
Here are couple ways you can do what you are trying to do:
Way 1: Here is if you just want to count the vowels:
s = input()
vowel_counter = 0
for letter in s:
if letter in "aeiou":
vowel_counter+=1
print(f"How many vowels in the sentence: {vowel_counter}")
Way 2: Use a python dictionary to keep track of how many of each vowel you have
s = input()
vowel_dict = {}
for letter in s:
if letter in "aeiou":
if letter not in vowel_dict:
vowel_dict[letter]=0
vowel_dict[letter]+=1
print(f"How many vowels in the sentence: {sum(vowel_dict.values())}")
print(vowel_dict)
I am trying to capitalize every other letter of a string which is given by and input. For some reason it give me the error 'string index out of range' and i have no idea why! the range is set from 0 to the length of the string so that cant be possible i thought!
s = input('Please enter a string: ')
p=s.lower()
o=s.upper()
q=p
k=len(s)
l=1
for x in range(0,k):
if l%2==0:
q=q[x].swapcase()
l+=1
else:
l+=1
print(q)
When you do this:
q=q[x].swapcase()
q becomes a single letter.
The next time around you try:
q[1]
but there is no q[1] because you made it a single letter.
This is one of several reasons why python encourages you to avoid creating index variables and instead looping over the items themselves. If you do that and give your variables more descriptive names, these kind of error are easier to catch. For example:
s = input('Please enter a string: ')
lower_case = s.lower()
new_string = ""
for index, letter in enumerate(lower_case):
if index % 2 == 0:
new_string += letter.swapcase()
else:
new_string += letter
print(new_string)
Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
I have to create a program where I need to ask a user for a string and then my program must print the length of the string, the number of letters, the number of digits and the number of characters that are not letters.
counter = 0
num = 0
extra = 0
wrd = raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter + 1
print "You have " + str(counter) +" letters in your sentence."
for n in wrd:
if n.isnumeric():
num = num + 1
print "You have " + str(num) + " number(s) in your sentence"
for l in wrd:
extra = extra + 1
print "You have " + str(extra) + " characters that are not letters or numbers."
I got the first two parts figured out albeit I'm stuck on the last...I know its easier to just create one while loop but since I already started, I want to stick with three four loops.
You don't need another function. Since you've already counted the other characters, subtract them from the total:
print "You have", len(wrd) - counter - num, "characters that are not letters or numbers."
Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
No, but its pretty easy to create your own:
import string
def has_special_chars(s):
return any(c in s for c in string.punctuation)
Test:
>>> has_special_chars("ab#tjhjf$dujhf&")
True
>>> has_special_chars("abtjhjfdujhf")
False
>>>
In your case, you would use it like:
for l in wrd:
if has_special_chars(l)
extra=extra+1
But as #TigerHawkT3 has already beat me to saying, you should simply use len(wrd) - counter - num instead. Its the most canonical and obvious way.
Just to log a generic answer that will apply beyond this context -
import string
def num_special_char(word):
count=0
for i in word:
if i in string.punctuation:
count+=1
return count
print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers."
Output
You have 2 characters that are not letters or numbers.
Use one for loop with if, elif and else:
sentence = raw_input("Please enter a short sentence.")
alpha = num = extra = 0
for character in sentence:
if character.isspace():
pass
elif character.isalpha():
alpha += 1
elif character.isnumeric():
num += 1
else:
extra += 1
print "You have {} letters in your sentence.".format(alpha)
print "You have {} number(s) in your sentence".format(num)
print "You have {} characters that are not letters or numbers.".format(extra)
So I was doing our exercise when I came across capitalizing characters in odd indices. I tried this:
for i in word:
if i % 2 != 0:
word[i] = word[i].capitalize()
else:
word[i] = word[i]
However, it ends up showing an error saying that not all strings can be converted. Can you help me debug this code snippet?
The problem is strings in python are immutable and you cannot change individual characters. Apart fro that when you iterate through a string you iterate over the characters and not the indices. So you need to use a different approach
A work around is
(using enumerate)
for i,v in enumerate(word):
if i % 2 != 0:
word2+= v.upper()
# Can be word2+=v.capitalize() in your case
# only as your text is only one character long.
else:
word2+= v
Using lists
wordlist = list(word)
for i,v in enumerate(wordlist):
if i % 2 != 0:
wordlist[i]= v.upper()
# Can be wordlist[i]=v.capitalize() in your case
# only as your text is only one character long.
word2 = "".join(wordlist)
A short note on capitalize and upper.
From the docs capitalize
Return a copy of the string with its first character capitalized and the rest lowercased.
So you need to use upper instead.
Return a copy of the string with all the cased characters converted to uppercase.
But in your case both work accurately. Or as Padraic puts it across "there is pretty much no difference in this example efficiency or output wise"
You need enumerate and capitalise any character at any odd i where i is the index of each char in the word:
word = "foobar"
print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR
ch.upper() if i % 2 else ch is a conditional expression where we change the char if the condition is True or else leave as is.
You cannot i % 2 when i is the actual character from the string, you would need to use range in your code or use enumerate and concatenate the changed characters to an output string or make words a list.
Using a list you can use assignment:
word = "foobar"
word = list(word)
for i, ele in enumerate(word):
if i % 2:
word[i] = ele.upper()
print("".join(word))
Using an output string:
word = "foobar"
out = ""
for i, ele in enumerate(word):
if i % 2:
out += ele.upper()
else:
out += ele
if i % 2: is the same as writing if i % 2 != 0.
This is how I would change word letters in a word or a sentence to uppercase
word = "tester"
letter_count = 1
new_word = []
for ch in word:
if not letter_count % 2 == 0:
new_word.append(ch.upper())
else:
new_word.append(ch)
letter_count += 1
print "".join(new_word)
if I wanted to change odd words in a sentence to uppercase I would do this
sentence = "this is a how we change odd words to uppercase"
sentence_count = 1
new_sentence = []
for word in sentence.split():
if not sentence_count % 2 == 0:
new_sentence.append(word.title() + " ")
else:
new_sentence.append(word + " ")
sentence_count += 1
print "".join(new_sentence)
I think it will help...
s = input("enter a string : ")
for i in range(0,len(s)):
if(i%2!=0):
s = s.replace(s[i],s[i].upper())
print(s)
not sure why this isn't working.
error I'm getting: ord() expected a character, but string of length 0 found
code:
phrase = 'test'
number = 0
text = 0
random1 = ''
while (number <= len(phrase)):
letter = phrase[number:number+1]
text = ord(letter) - ord('a')
....
number = number + 1
if a print letter, i get the t for the first iteration
thanks,
You are failing on your last iteration. Because you let number take the value len(phrase), you are trying to slice your string beyond the end.
For example:
>>> "abc"[3:4]
''
String indices range from 0 to len(s)-1.
BTW: Python gives you much nicer ways to iterate over strings:
phrase = 'test'
for letter in phrase:
text = ord(letter) - ord('a')
....
You are iterating past the end of phrase, try this:
phrase = 'test'
number = 0
text = 0
random1 = ''
while (number < len(phrase)):
letter = phrase[number:number+1]
text = ord(letter) - ord('a')
Note the:
while (number < len(phrase)):
You do indeed have to show more code. What is i? Are you incrementing it each loop?
Typically, if you ARE incrementing i to act just like a for loop, you want to loop such that number < len(phrase), not <=.
Also, you can replace
letter = phrase[number:number+1]
with
letter = phrase[number]
Use for..in instead to process each letter in your string:
Code:
phrase = 'test'
for letter in phrase:
print letter
Output:
t
e
s
t
This would be the more "pythonic" way of doing character iteration. This way you're guaranteed to hit every letter without having to consider hitting the end, as what's happening in your code.
You want a char and not a string, right? Try to replace your
letter = phrase[number:number+1]
with
letter = phrase[number]