首页 > 解决方案 > 在 python 中只运行一个 for 循环

问题描述

当我在这段代码中输入“HelLO”时,它应该输出 10,但只输出 5,为什么?

如果单词包含小写字母,该程序将在分数上加 5,如果单词包含大写字母,则另加 5。但是,它只需要至少有一个分数才能被添加。HellO 有大写和小写字母,所以加起来应该是 10。

capitals="A","B","C","D","E","F","G","H","I","J",
         "K","L","M","N","O","P","Q","R","S","T","U",
         "V","W","X","Y","Z"  
characters="a","b","c","d","e","f","g","h","i","j",
           "k","l","m","n","o","p","q","r","s","t","u",
           "v","w","x","y","z"
word=raw_input("word please")
score=0

for i in range(0,len(word)):
    a=i

for i in range(0,26):
    if word[a]==characters[i]:
        score=score+5
        break

for i in range(0,26):
    if word[a]==capitals[i]:
        score=score+5
        break

print score

标签: python

解决方案


After the execution of the loop for i in range(0,len(word)): a=i the value of a becomes len(word)-1 (in your case, 4) and never changes again. Here's what you are looking for:

import string
score = 0
# Does the string have at least one uppercase char?
if set(string.ascii_uppercase) & set(word):
    score += 5
# Does the string have at least one lowercase char?
if set(string.ascii_lowercase) & set(word):
    score += 5

推荐阅读