我有一个家庭作业问题,要求通过原始输入读取字符串并计算字符串中有多少个元音.这是我到目前为止,但我遇到了一个问题:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
Run Code Online (Sandbox Code Playgroud)
它将元音计算得很好,但是由于if string[i] == vowels[i]:它只会计算一个元音,因为它i在范围内不断增加.如何在不遇到此问题的情况下更改此代码以检查输入的元音字符串?
这是一个家庭作业问题,它会问"选择一个字.请用户输入一个字母.检查字母中出现的字母数,然后在屏幕上输出数字." 到目前为止,我已按原样编写,似乎工作正常:
word = str("python")
letters = len(word)
attempt = str(raw_input ("Enter a letter: "))
while attempt in word:
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
attempt = str(raw_input ("Enter another letter: "))
while attempt not in word:
attempt = str(raw_input ("This letter is not present, enter another letter: "))
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
Run Code Online (Sandbox Code Playgroud)
但偶尔如果我输入信件,程序将停止,不再需要更多输入.我究竟做错了什么?如果代码非常草率并且编写得很糟糕,我很抱歉,因为我是编程新手.谢谢.