我想从列表中输入多个元素,并让程序打印出准确的“pointCount”数量。如果我从任何一个列表中输入一个元素,它都可以工作(例如,“a”= 1点,“f”= 3点)。问题是,如果我,例如,输入“cafe”之类的东西,程序只会打印出“0点”而不是“7点”。
onePointLetters = ["a", "b", "c"]
twoPointLetters = ["d", "e"]
threePointLetter = ["f"]
enterLetter = input("Enter a letter: ").lower()
while enterLetter != "stop":
pointCount = 0
if enterLetter in onePointLetters:
pointCount += 1
if enterLetter in twoPointLetters:
pointCount += 2
if enterLetter in threePointLetter:
pointCount += 3
print("You have a total of " + str(pointCount) + " points!")
enterLetter = input("Enter another letter: ").lower()
我尝试了另一种编码方案。
onePointLetters = ["a", "b", "c"]
twoPointLetters = ["d", "e"]
threePointLetter = ["f"]
enterLetter = input("Enter a letter: ").lower()
while enterLetter != "stop":
pointCount = 0
for onePointLetters in enterLetter:
pointCount += 1
for twoPointLetters in enterLetter:
pointCount += 2
for threePointLetter in enterLetter:
pointCount += 3
print("You have a total of " + str(pointCount) + " points!")
enterLetter = input("Enter another letter: ").lower()
如果我保留其中一个for循环,后者似乎可以正常工作,但如果保留所有三个for循环,程序只会将所有值相加,每输入一个字母就得到6分(d = 6分,afe = 18分)。
有没有更好的解决办法?
2条答案
按热度按时间rpppsulh1#
您的第一个代码可以工作,但是您应该在while循环之外初始化pointCount
我建议用字典来解释这个问题:
z2acfund2#
您的第一次编码尝试检查输入是否在pointlist中。“a”在列表中,因此是1个点。“f”也在列表中,因此是3个点。但是,“Cafe”不在任何列表中。
您需要找到一种方法来遍历input-word的每个字母,并检查它们应该向pointsCounter添加多少点数。