简体   繁体   English

Python:我的代码出错,我不知道如何修复它

[英]Python: Error in my code and i don't know how to fix it

The example below is failing upper_lower('abcXYZ') , it returns true下面的示例失败upper_lower('abcXYZ') ,它返回 true

def upper_lower(s: str) -> bool:
    """Return True if and only if there is at least one alphabetic character
    in s and the alphabetic characters in s are either all uppercase or all
    lowercase.
    >>> upper_lower('abc')
    True
    >>> upper_lower('abcXYZ')
    False
    >>> upper_lower('XYZ')
    True
    """
    for char in s:
        if char.isalpha():
            if char.isupper() or char.islower():
                return True
            if char.swapcase():
                return False
            else:
                return False

Try that:试试看:

def upper_lower(s):
    return s.isupper() or s.islower()

print(upper_lower("abc"))  # True
print(upper_lower("12abc45"))  # True
print(upper_lower("ABC"))  # True
print(upper_lower("ABC45"))  # True
print(upper_lower("aBC"))  # False
print(upper_lower("123"))  # False

Your code currently returns True if the first alpha character is eiher lowcase or upcase:如果第一个字母字符是小写或大写,您的代码当前返回 True:

if char.isupper() or char.islower():
    return True   # return cause the function to end, other cars are not tested

I would suggest using list comprehension for this:我建议为此使用列表理解:

def upper_lower(word):
    if not word:
        return False
    else: 
        return all([s.isupper() for s in word]) or all([s.islower() for s in word])
def upper_lower(s):
    s = ''.join(c for c in s if c.isalpha())
    return bool(s) and (s.isupper() or s.islower())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的代码正在使用递归产生逻辑错误,但我不知道如何解决 - My code is producing a logic error with recursion and I don't know how to fix it 我写了这段代码,但我的 output 不是应有的二维,我不知道如何修复它 - I wrote this code but my output is not in 2D as it should have been, and I don't know how to fix it 这是我的计算机项目,我遇到错误,我不知道如何修复 - This is my Computer project and i am getting error and i don't know how to fix 我有一个 python TypeError,我不知道如何修复它 - I have a python TypeError and I don't know how to fix it 我不知道如何修复一元 +: 'str' 错误 - I don't know how to fix an unary +: 'str' error 我收到EOF错误,不知道如何解决 - I am getting an EOF error and don't know how to fix it 由于某种原因,在我的代码中出现“索引超出范围”的错误,我实际上刚刚开始使用 Python,因此不知道如何解决这个问题 - In My Code There Is A Error Saying "Index Out Of Range" For Some Reason, I Actually Just Started Python And Hence Don't Know How To Solve This Python 代码无法运行,我不知道如何修复它 - Python code doesn't run, I don't know what to do to fix it 我不知道如何用我的 Python 语句只显示一次错误消息 - I don't know how to only show error message once with my Python statement 我在我的 pythonanywhere 中收到 ImportError,我不知道它是什么或如何修复它 - I am getting an ImportError in my pythonanywhere and I don't know what it is or how to fix it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM