在python3.4.3中不执行while循环

2024-06-26 14:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它接受一个字符串,并确定它是否为整数。你知道吗

在很大程度上,它运作良好。唯一的问题是当我在数字前面使用+或-时。我以为我在while循环中考虑到了这一点,但它似乎没有执行。这是我的密码:

def isInteger(sentence):
    """(str) -> bool
    takes veriable sentence, which is a string, and returns true if it is
    an integer
    >>> isInteger('75931')
    True
    >>> isInteger('345L55')
    False
    """
    value = True #Assume the string is a digit
    if len(sentence) > 0:
        sentence = sentence.strip()
    else:
        value = False
    if sentence[0] == '+' or sentence[0] == '-' or sentence[0].isdigit() == True:
        count = 1
        while count < len(sentence) and sentence[count].isdigit() == True:
            if sentence.isdigit() == True:
                count += 1
            else:
                value = False
                break
    else:
        value = False
        print(value) #test
    return value

Tags: orandfalsetruestringlenifis
2条回答

如果字符串以+-开头,则if条件通过:

if sentence[0] == '+' or sentence[0] == '-' or sentence[0].isdigit() == True:

但是,while的条件仍然失败,因为您正在使用sentence[0].isdigit()进行测试。你知道吗

一个简单的解决方法是在检查后跳过第一个字符:

if sentence[0] == '+' or sentence[0] == '-' or sentence[0].isdigit():
    count = 1
    sentence = sentence[1:]   # here

while循环之后的检查导致值返回False,因为您正在检查整个句子。你知道吗

if sentence.isdigit() == True:

用这个代替?你知道吗

if sentence[count].isdigit() == True:

相关问题 更多 >