Python不返回任何值,而是返回True或False

时间:2019-07-03 18:47:30

标签: python python-3.x

我正在创建一个名为isSiete()的函数,该函数将接受txt文件中具有5000个随机数的整数。

如果该数字的第二列数字(“十”列)为“ 7”,则返回True;否则为False。

def isSiete(num):
    numString = str(num)
    numList = list(numString)
    numSum = 0
    for i in numList:
        if ('0' + i)[-2] == '7':
            return True
        else:
            return False

我希望输出为True,但每次都为False。 我尝试了以下测试编号

isSiete(7777) isSiete(4774) isSiete(672)

4 个答案:

答案 0 :(得分:2)

根本不用理会字符串;除以10两次会快一个数量级。

def isSiete(num):
    return num // 10 % 10 == 7

num的大小增加时,算术速度变慢,但是num是17位数字时,算术速度变快。

答案 1 :(得分:1)

您的df['dups'] = df['col1'] + df['col2'] + df['col3'] > 1 始终等于字符('0' + i)[-2]

例如,假设'0' 假设numList == ['A', 'P', 'P', 'L', 'E']i的元素,例如'P'

然后numList

'0' + i == "0P"获得倒数第二个字符
[-2]

请注意,"0P"[-2] == "0"是什么都没有关系。倒数第二个字符 P中的始终为'0' + i

'0'将始终返回('0' + i)[-2] == '7'


我鼓励您学习“模运算符”(False

%是x的余数除以10。 例如,x % 10

通常,74 % 10 == 4x % y除以x的余数

要从数字中提取特定数字,请执行以下操作:

y

例如,假设您想要def extract_digit(number, position): """ position == 1 ......if you want the ones place position == 2 ......if you want the tens place position == 3 ......if you want the hundredths place position == 4 ......if you want the thousanths place and so on... """ small_places = number % (10**position) digit = small_places //(10**(position - 1)) return digit 的百分位:

123456789

最终的结果是:

123456789 % 1000 == 789      
789 // 100 == 7

答案 2 :(得分:0)

您可以简单地使用转换后的字符串来检查您的条件,因为python中的字符串可以用作字符数组:

def isSiete(num):
    numString = str(num)
    tensPosition = len(numString) - 2

    if tensPosition >= 0 and numString[tensPosition] == '7':
        return True
    else:
        return False

答案 3 :(得分:0)

我不确定您是否需要调试代码的帮助,或者是否需要有关工作解决方案的帮助。

在您需要解决方案的情况下:这是一个有效的代码段,可以帮助您实现所需的目标。

def is_siete(num):
    """
    Asserts that the tens of a number is 7. Returns False if not.
    """
    num_as_str = str(num)

    try:

        second_num_as_str = num_as_str[-2]
        second_num_as_int = int(second_num_as_str)

        if second_num_as_int == 7:
            return True

        return False

    except IndexError:
        return False


if __name__ == "__main__":
    print(is_siete(7777))  # True
    print(is_siete(4774))  # True
    print(is_siete(672))  # True
    print(is_siete(17))  # False
    print(is_siete(7))  # False