【问题标题】:Python int/str checkingPython int/str 检查
【发布时间】:2011-07-21 21:12:54
【问题描述】:

我有一个家庭作业,我只完成了最低限度的作业,但是在完成它的过程中,我开始对如何使我的程序变得更好感兴趣。代码的重点是绘制用户定义的形状并在输入无效输入时提供反馈。我想继续这样做,所以如果用户输入 str 作为高度/宽度或其中一个坐标,它会给出错误,但我无法确切地弄清楚如何去做。这是一个介绍类,所以如果你记住,我们只是进入 while 循环,我们已经学习了 for 循环,if/else/etc。

这是我目前拥有的代码:


def draw_user_shape(pen):
    shape = input("Please enter a shape: ")
    while shape != "square" and shape != "rectangle" and shape != "triangle":
        shape = input("Invalid shape, please enter either square, rectangle, or triangle: ")
    if shape == "square":
        h = input("Please enter a height: ")
        while h != int or int(h) < 1:
            h = input("That is an invalid height, please enter an positive integer: ")
        h = int(h)
        c = input("Please enter a color: ")
        while c != str and str(c) != "red" and str(c) != "green" and str(c) != "blue":
            c = input("That is an invalid color, please enter either red, blue, or green: ")
        c = str(c)
        x = input("Please enter an x-coordinate: ")
        while x != int and int(x) == 1:
            x = input("That is an invalid x-coordinate, please enter an integer: ")
        x = int(x)
        y = input("Please enter a y-coordinate: ")
        while y != int and int(y) == int:
            y = input("That is an invalid y-coordinate, please enter an integer: ")
        y = int(y)
        pen.fillcolor(c)
        pen.up()
        pen.goto(x,y)
        pen.down()
        pen.begin_fill()
        pen.goto(x,y+h)
        pen.goto(x+h,y+h)
        pen.goto(x+h,y)
        pen.goto(x,y)
        pen.end_fill()
        pen.up()
    elif shape == "rectangle":
        h = input("Please enter a height: ")
        while h != int and int(h) < 1:
            h = input("That is an invalid height, please enter an positive integer: ")
        h = int(h)
        w = input("Please enter a width: ")
        while w != int and int(w) < 1:
            w = input("That is an invalid height, please enter an positive integer: ")
        w = int(w)
        c = input("Please enter a color: ")
        while c != str and str(c) != "red" and str(c) != "green" and str(c) != "blue":
            c = input("That is an invalid color, please enter either red, blue, or green: ")
        c = str(c)
        x = input("Please enter an x-coordinate: ")
        while x != int and int(x) == 1:
            x = input("That is an invalid x-coordinate, please enter an integer: ")
        x = int(x)
        y = input("Please enter a y-coordinate: ")
        while y != int and int(y) == int:
            y = input("That is an invalid y-coordinate, please enter an integer: ")
        y = int(y)
        pen.fillcolor(c)
        pen.up()
        pen.goto(x, y) 
        pen.down()
        pen.begin_fill()
        pen.goto(x,y+h)
        pen.goto(x+w,y+h)
        pen.goto(x+w,y)
        pen.goto(x,y)
        pen.end_fill()
        pen.up()
    elif shape == "triangle":
        h = input("Please enter a height: ")
        while h != int and int(h) < 1:
            h = input("That is an invalid height, please enter an positive integer: ")
        h = int(h)
        w = input("Please enter a width: ")
        while w != int and int(w) < 1:
            w = input("That is an invalid height, please enter an positive integer: ")
        w = int(w)
        c = input("Please enter a color: ")
        while c != str and str(c) != "red" and str(c) != "green" and str(c) != "blue":
            c = input("That is an invalid color, please enter either red, blue, or green: ")
        c = str(c)
        x = input("Please enter an x-coordinate: ")
        while x != int and int(x) == 1:
            x = input("That is an invalid x-coordinate, please enter an integer: ")
        x = int(x)
        y = input("Please enter a y-coordinate: ")
        while y != int and int(y) == int:
            y = input("That is an invalid y-coordinate, please enter an integer: ")
        y = int(y)
        pen.fillcolor(c)
        pen.up()
        pen.goto(x,y)
        pen.down()
        pen.begin_fill()
        pen.goto(x+w/2,y+h)
        pen.goto(x+w,y)
        pen.goto(x,y)
        pen.end_fill()
        pen.up()

def main():
    import turtle
    pen = turtle.Turtle()
    draw_user_shape(pen)

main()

【问题讨论】:

  • 只是想说我喜欢你主动让你的程序更好。 :)

标签: python loops int string


【解决方案1】:

使用.isdigit() 或.isalnum() 检查,看你喜欢什么

  1. 例子

    str_num= 'aaaa7777'
    str_num.isalnum() # true
    str_num.isdigit() # false
    
  2. 例子

    str_num= 'aaaa 7777' # Note that has spaces
    str_num.isalnum() # false
    str_num.isdigit() # false
    
  3. 例子

    str_num= '7777' 
    str_num.isalnum() # True
    str_num.isdigit() # True
    

【讨论】:

    【解决方案2】:

    在这种情况下,您需要使用异常处理。基本上这个想法是接受输入并 try 转换为int。如果失败,则会引发 ValueError。否则,您将取回转换后的值。请记住,输入将始终作为str 提供给您,因此您不能简单地测试它是否是int。假设您使用的是 Python 3,您可以执行以下操作来不断询问,直到输入正确的值:

    # keep asking for input until we get the right one
    while True:
        myInput = input('give me a number: ')
        try:
            myValue = int(myInput)
            # if we reach this point, that means we got our number
            break # this will jump out of the loop
        except ValueError:
            # if we reach this point, that means the input was bad
            print('invalid input')
    

    【讨论】:

    • 如果你不喜欢我的isdigit 方法,这就是你要走的路。我只是喜欢这样做,因为它更短,但它具有更广泛的适用性。
    • @Justin:您的方式也很有效,只需对现有代码进行最少的更改。我只是倾向于这种方式而不是那种方式。 :)
    • @Ryan:还有一个提示,我会把它放在一个单独的函数中。为您想要执行的每个输入重复此代码块是没有意义的,它只会使您的代码更加混乱。还可以考虑将执行每个形状的代码也移动到单独的函数中。
    【解决方案3】:

    我会推荐使用

    not h.isdigit()
    

    检查字符串 h 是否不包含整数。它不适用于浮点数,因为它真正检查的是每个数字是否在 0-9 范围内,并且 . 不会被(正确)识别为数字。

    比如这条线

    while h != int or int(h) < 1:
    

    会变成

    while not h.isdigit() or int(h) < 1:
    

    顺便说一句,我假设您使用的是 Python 3.x,否则您的代码将无法工作,因为 input 在 Python 2.x 中的工作方式不同。在 Python 3.x 中,它应该总是返回一个字符串,因此没有任何理由检查返回的对象是否是一个字符串。

    【讨论】:

      【解决方案4】:
      >>> isinstance('a', int)
      False
      >>> isinstance(2, int)
      True
      

      【讨论】:

        猜你喜欢
        • 2015-11-14
        • 1970-01-01
        • 1970-01-01
        • 2014-04-23
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-12-12
        相关资源
        最近更新 更多