python - 在 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
解决方案
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
推荐阅读
- xml - Maven获取父pom标签值
- javascript - 试图在最后一个窗口上输出首字母.. EX:名字 = Joe,姓氏 = Apple,大学 = Mercer OUTPUT = FLmercer
- regex - 具有特定字符且没有其他字符的正则表达式
- python - 如何将默认值覆盖为非默认值
- drupal-8 - hook_form_FORM_ID_alter:在 drupal 8 视图中从暴露的过滤器中预先选择一个复选框
- spring-boot - Spring JPA @Query 抛出可选参数异常
- amazon-web-services - 向特定 DNS 公开 VPC/API 网关
- python - 在 Python 中可视化非常大的特征空间
- javascript - React Router - 使用按钮链接时呈现的空页面
- reactjs - 我们可以从 react-native 项目中获取网站或 Web 应用程序吗?