在编写通过函数传递单词时,不断得到错误的输出



我正在编写一段代码,通过函数请求用户输入。当单词的开头索引是大写时,我希望它输出"大写";真的";。当单词的开头索引是小写时,我希望它打印";错误";。每次我输入一个小写单词时,我仍然会得到输出";没错">

这是我写的代码:

def printWord():
user = input("Please enter a word here: " )

if user[0].upper():
print("True")

elif user[0].lower(): 
print("False")
printWord()

有什么建议吗?

您正在寻找isupper()/islower()方法。upper()会将该字符/字符串转换为大写。

def printWord():
user = input("Please enter a word here: " )

if user[0].isupper():
print("True")

elif user[0].islower(): 
print("False")
printWord()

使用isupper()

>>> "a".upper()
'A'
>>> "A".upper()
'A'
>>> "a".isupper()
False
>>> "A".isupper()
True

"myword".upper()->MYWORD

"myword".isupper()->False

"MYWORD".isupper()->True

.upper()将字符串转换为大写,.isupper()检查字符串是否为大写。

https://www.w3schools.com/python/ref_string_upper.asphttps://www.w3schools.com/python/ref_string_isupper.asp

当您用.usupper().islower()替换.upper().lower()时,您的代码就可以工作了。

最新更新