只有一个for循环在python中运行

时间:2018-07-20 21:58:08

标签: python

当我在代码中添加“ 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

2 个答案:

答案 0 :(得分:3)

执行循环for i in range(0,len(word)): a=i后,a的值将变为len(word)-1(在您的情况下为4),并且不再更改。这就是您要寻找的东西:

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

答案 1 :(得分:0)

看起来您想要做的是嵌套嵌套循环。以便您检查word中的每个字母是否符合条件。

但是在这种情况下,您还需要带有标志或表明已找到大写或小写字母的指示,以免重复计算。

您可以对预期的答案进行一些更改,但是我还要补充一点,您可以对该代码进行一些其他改进以简化/提高效率。

  • 研究使用列表的in功能:类似letter in capitals
  • 查看所有字符串中内置的.upper()功能
  • 列表理解

无论如何,这里都是针对您预期功能的修复程序。

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

capital_found = False
lower_found = False

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

    if not lower_found:

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

    if not capital_found:

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

print score