如果句子中的所有单词都是小写的,如何返回"Yes"?



我目前可以让我的代码返回"是";对于每个字符,但如果句子中的每个单词都是小写的,我不知道如何使代码在代码末尾只返回ONE Yes。这是我的

sentence = "hello thEre is this aLL lowercase"
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
print("Yes")
lower = True
if not ch.islower():
print("No")
lower = False

我知道我不能循环打印("是"(,因为它每次都会打印,但我不知道如何以其他方式打印。谢谢你的帮助。

以下是解决方案的一种方法。

我有意不提供任何解释,因为这将有助于你自己研究这些概念。调查:

  • 列出理解
  • all()函数
  • 布尔测试

示例代码:

s = ‘lower case statement’
result = all([i.islower() for i in s.split()])
print('Yes' if result else 'No')
>>> ‘Yes’

我建议将短代码的每一部分拆开,看看它是如何工作的。

简化:

就我个人而言,我不介意在教育环境中分享这一点,因为学习编写Python(以及一般代码(的一部分是学习高效地编写它。也就是说,这里有一个简化的解决方案:

print('Yes' if s.islower() else 'No')
>>> ‘Yes’

如果你只关心它是小写的,那么当你第一次找到大写字母时,你应该跳出循环。如果循环外lower为true,则仅打印yes。

我假设这是一个练习,所以我不会给出任何代码。

你需要有一个变量";发现任何非小写单词";在循环之前设置为false,如果发现单词不是小写,则设置为true。如果该变量在循环之后仍然为假;是";,否则不会。

也许如果你已经编写了实现这一点的代码,你会发现它是可以优化的。

您可以使用isLower(),只需记住删除空格

def checkLower(string):
string = string.replace(" ","")
print(string)
for i in string:
if i.islower() == False:
return "no"
return "yes"

您可以使用.islower()简单地执行此操作,因为如果字符串中的所有字符都是小写,islow((方法将返回True,否则,它将返回False。

sentence = "hello thEre is this aLL lowercase"
if(sentence.isLower()):
print('Yes')
else:
print('No')
sentence = "hello there this is all lowercase"
sent = sentence.split(" ")
lower = True
for wd in sent:
for ch in wd:
if not ch.islower():
lower = False
if lower:
print("Yes")
if not lower:
print("No")

我对python及其工作原理不太了解,但以下是我添加到所提供代码中的逻辑。

现在您正在打印"是";每次你找到一个小写单词。

def isAllLower(sentence):
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
lower = True
if not ch.islower():
lower = False
if lower == True:
print("Yes")
elif lower == False:
print("No")
isAllLower("hello thEre is this aLL lowercase")

到目前为止,最简单的方法是使用lower((函数将默认降低的句子与初始函数进行比较!

def SentenceisLower(sentence):
sentencelower = sentence.lower()
if (sentence == sentencelower):
print("Yes!")

在任何其他结果中都没有回复!

最新更新