【问题标题】:TypeError on Length of a String Characters字符串字符长度上的 TypeError
【发布时间】:2020-07-21 01:38:44
【问题描述】:

晚上好,提前感谢回复者的解释和解决方案。

我正在使用 Python 3.7 进行编码,正在参加 Python Intro 暑期课程。我的任务是创建一个请求 2 个用户输入的函数:(1) 字符键和 (2) 4 到 500 个字符之间的字符串、短语或句子。这两个函数都需要错误处理程序。第一个“角色”执行得很好。第二个“phrase_sentence”函数返回错误说明:

TypeError: '>=' not supported between instances of 'str' and 'int'

我正在按照我们教科书中的类似示例进行操作,但无法解决错误。我知道当涉及到数字(数字)时,我必须转换为浮点数或整数,但是示例和示例代码布局了我输入它的函数,因为它基于字符串字符的长度。我还尝试将整个 'if len' 语句括在括号中。

def main():
    # define keyCharacter function and request user input for a key
    
    character = input('Please enter a single alphabet character (a-z) for a key: ')
    if((character>='a' and character<= 'z') or (character>='A' and character<='Z')):
        print("Your key character is:", character)
    else:
        print("ERROR: Please enter a single alphabet character: ")
        character = (input('Please enter a single alphabet character (a-z) for a key: '))
        
    #theString()    
    phrase_sentence = input('Enter a phrase or sentence, between 4 & 500 characters long: ')
    if len((phrase_sentence) >= 4 and (phrase_sentence) <= 500):
        print("Your phrase or sentence is: ", phrase_sentence)
    else:
        print("ERROR: Sentence or phrase must be between\b 4 & 500 characters, try again!")
        phrase_sentence = input('Enter a phrase or sentence, between 4 & 500 characters long: ')
        
main()   

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    问题似乎在于您如何调用 len()。试试这个:

    character = input('Please enter a single alphabet character (a-z) for a key: ')
    if((character>='a' and character<= 'z') or (character>='A' and character<='Z')):
        print("Your key character is:", character)
    else:
        print("ERROR: Please enter a single alphabet character: ")
        character = (input('Please enter a single alphabet character (a-z) for a key: '))
        
    #theString()    
    phrase_sentence = input('Enter a phrase or sentence, between 4 & 500 characters long: ')
    if len(phrase_sentence) >= 4 and len(phrase_sentence) <= 500:
        print("Your phrase or sentence is: ", phrase_sentence)
    else:
        print("ERROR: Sentence or phrase must be between 4 & 500 characters, try again!")
        phrase_sentence = input('Enter a phrase or sentence, between 4 & 500 characters long: ')
    

    【讨论】:

    • 非常感谢,太好了。我无法相信我对解决方案的显而易见性是多么的无知。卡洛斯
    • 没问题,欢迎来到 SO :)。问题解决后,请将问题标记为已解决。
    猜你喜欢
    • 2016-01-10
    • 1970-01-01
    • 2021-05-26
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多