微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

isdigit()

如何解决isdigit()

首先,我对编码非常陌生,而且我的代码可能还有很多地方可以做得更好。我的主要问题是,每当我将列表的第一个元素设为非数字时,while 循环都会捕获它,允许我将元素更改为数字,但 isdigit() 仍将其标记为 False,然后再次循环。

预先感谢您的任何帮助。

def matrix_maker():
        count = 1
        validInteger = False
        pre = ""

        a,b,c,d,e,f,g,h,i = input("enter each element of the matrix: ").split()
        m1 = [a,i]

        for i in m1:
            if count == 1:
                pre = "st"
            elif count == 2:
                pre = "nd"
            elif count == 3:
                pre = "rd"
            else:
                pre = "th"

            while validInteger != True:
                if i.isdigit():
                    validInteger = True
                else:
                    s_count = str(count)

                    count = count - 1
                    m1[count] = input("enter a valid integer for the element in the "+s_count+pre+" place: ")
                    count = count + 1

            count = count + 1
            validInteger = False

        print(m1)
      
    matrix_maker()

解决方法

为了帮助您学习编程,这里有一些评论:

  1. 不要将数据项加载到单独的变量中,这就是我们有列表、字符串、字典等的原因。
  2. 不要使用计数器,在 python enumerate() 中,如果/在需要时迭代计数器。无需携带单独的计数器变量。
  3. 您应该将看似无关的代码分离到不同的函数中。
  4. 避免使用 while 循环标志。在 python 中,这在 99.9% 的情况下应该是可以避免的。 while 语句应仅包含保持 while 语句运行所需的逻辑。

更新代码:

def digit2str(digit):
    if digit in [1,2,3]:
        pre = ['st','nd','rd'][digit-1]
    else:
        pre = 'th'
    return str(digit)+pre

def matrix_maker():
    data = input("enter each element of the matrix: ").split()
    for n,element in enumerate(data):
        while not data[n].isdigit():
            data[n] = input("enter a valid integer for the element in the "+digit2str(n+1)+" place: ")
    print(data)
,

你可以试试这个代码。在您的代码段中,我已将“if i.isdigit():”行更改为“if m1[count-1].isdigit():”,因为您想用新输入更新您的条件。因此,它更适合您的情况。

def matrix_maker():
    count = 1
    validInteger = False
    pre = ""

    a,b,c,d,e,f,g,h,i = input("enter each element of the matrix: ").split()
    m1 = [a,i]

    for i in m1:
        if count == 1:
            pre = "st"
        elif count == 2:
            pre = "nd"
        elif count == 3:
            pre = "rd"
        else:
            pre = "th"

        while validInteger != True:
            if m1[count-1].isdigit():
                validInteger = True
            else:
                s_count = str(count)
                count = count - 1
                m1[count] = input("enter a valid integer for the element in the "+s_count+pre+" place: ")
                count = count + 1
        count = count + 1
        validInteger = False
    print(m1)

matrix_maker()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。