简体   繁体   English

Python int / str检查

[英]Python int/str checking

I have a homework assignment and I've done the bare minimum of the assignment, but while working on it, I became interested in how to make my program better. 我有一个家庭作业,并且我已经完成了最少的作业,但是在进行作业时,我对如何使我的程序变得更好感兴趣。 The point of the code is to draw a user defined shape and provide feedback if they enter invalid inputs. 代码的重点是绘制用户定义的形状,并在输入无效输入时提供反馈。 I want to go ahead and make it so if a user enters a str for the height/width or one of the coordinates it gives an error, but I am unable to figure out exactly how to do it. 我想继续做下去,所以如果用户输入一个str作为高度/宽度或坐标之一,它将给出一个错误,但是我无法弄清楚该怎么做。 It's an intro class so if you'd keep in mind we're just getting to while loops and we've gone over for loops, if/else/etc. 这是一个入门课程,因此,如果您要牢记,我们只是进入while循环,而对于if / else / etc,我们已经进行了循环。

Here's the code I currently have: 这是我目前拥有的代码:


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()

You'd want to use exception handling in this case. 在这种情况下,您想使用异常处理。 Basically the idea is to take the input and try to convert to an int . 基本上,这个想法是接受输入并尝试将其转换为int If that fails, a ValueError is raised. 如果失败,则会引发ValueError Otherwise you will get back the converted value. 否则,您将取回转换后的值。 Remember, the input will always be given to you as a str , so you can't simply test if it's an int . 请记住,输入将始终以str形式提供给您,因此您不能简单地测试它是否为int Assuming you are using Python 3, you can do something like this to keep asking until the right value is typed in: 假设您使用的是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')

I would recommend using 我建议使用

not h.isdigit()

to check if the string, h, doesn't contain an integer. 检查字符串h是否不包含整数。 It won't work for floating point numbers because what it is really checking for is if each digit is in the 0-9 range and the . 它不适用于浮点数,因为它真正要检查的是每个数字是否在0-9范围内,以及. won't be recognized (correctly) as a digit. 将不会(正确)识别为数字。

For instance the line 例如线

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

would become 会成为

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

By the way, I'm assuming that you are using Python 3.x because otherwise your code wouldn't work because input works differently in Python 2.x. 顺便说一句,我假设您使用的是Python 3.x,否则您的代码将无法工作,因为input在Python 2.x中的工作方式有所不同。 In Python 3.x, it should always return a string, so there isn't any reason to check that the returned object is a string. 在Python 3.x中,它应始终返回字符串,因此没有任何理由检查返回的对象是否为字符串。

>>> isinstance('a', int)
False
>>> isinstance(2, int)
True

Use .isdigit() or .isalnum() to check , dependes that you prefer 使用.isdigit().isalnum() 进行检查.isalnum()您的偏好

  1. Example

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM