我有一个爱情计算器,它显示了有多少名1和名2恋爱(占100%),这取决于元音的数量是否匹配。到目前为止,这是我的代码:
name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
vowels1 = 0
vowels2 = 0
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in name1:
if letter.lower() in VOWELS:
vowels1 = 1+vowels1
print("You have",vowels1,"vowels.")
它没有显示name1中有多少个元音。您如何制作它,以便确实显示name1中有多少个元音?
答案 0 :(得分:1)
您应该创建一个直接返回解决方案的函数,而不是定义修改全局变量的函数。这样,它就不依赖于某些脆弱的全局状态。
def count_vowels(word):
vowels = {'a', 'e', 'i', 'o', 'u'} # I use a set here rather than a list because
# sets have very fast membership checks.
count = 0
for letter in word:
if letter in vowels:
count += 1
return count
然后您可以简单地做到:
num_vowels = count_vowels(name1)
可能值得注意的是,count_vowels
可以简化为单层:
def count_vowels(word):
return sum(lett in {'a', 'e', 'i', 'o', 'u'} for lett in word)
答案 1 :(得分:0)
def up_it(word):
vowel =['a','e','i','o','u']
count =0
for i in vowel:
count+=word.count(i)
return count
答案 2 :(得分:0)
您定义了一个函数up_it(word)
,但没有调用它。下面是该代码的简化版本:
name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
vowels1 = 0
vowels2 = 0
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in name1:
if letter.lower() in VOWELS:
vowels1 = 1+vowels1
up_it(name1) # call the function
print("You have", vowels1, "vowels.")
现在,该代码并未真正正确使用函数。更好的方法是使函数采用(并使用)参数,然后返回计数值。考虑到这一点,我们将有以下内容:
def count_vowels(word):
VOWELS = 'aeiou'
vowels_count = 0
for letter in word:
if letter.lower() in VOWELS:
vowels_count += 1
return vowels_count
name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
print("You have", count_vowels(name1), "vowels.")
print("You have", count_vowels(name2), "vowels.")
答案 3 :(得分:0)
list
答案 4 :(得分:0)
您的代码看起来应该可以工作-无论如何对于name1-您只是忘记了调用up_it()。 所以试试这个:
def up_it(word):
letters = []
for letter in name1:
if letter.lower() in VOWELS:
vowels1 = 1+vowels1
name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
vowels1 = 0
vowels2 = 0
VOWELS = 'aeiou'
up_it("literally anything because you don't use the value passed")
print("You have",vowels1,"vowels.")
问题是您定义的up_it函数从不实际使用传入的可变字。它始终使用name1。另外,您还有一个称为来声明和初始化的字母的列表,但从未在方法中使用它。
我认为您真正想要的是以下代码:
def up_it(word):
word = word.lower()
return sum([word.count(vowel) for vowel in 'aeiou'])
name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
vowels_name_1 = up_it(name1)
vowels_name_2 = up_it(name2)
print(name1,"has", vowels_name_1,"vowels.")
print(name2,"has", vowels_name_2,"vowels.")