Python int/str 检查

发布于 2024-10-26 04:46:09 字数 4255 浏览 4 评论 0原文

我有一项家庭作业,并且我已经完成了最低限度的作业,但是在完成它的过程中,我对如何使我的程序变得更好感兴趣。代码的要点是绘制用户定义的形状,并在用户输入无效输入时提供反馈。我想继续这样做,这样如果用户输入高度/宽度或坐标之一的 str ,它就会给出错误,但我无法确切地弄清楚如何做到这一点。这是一门入门课程,所以如果您记住的话,我们只是讨论 while 循环,并且我们已经讨论了 for 循环、if/else/等等。

这是我目前拥有的代码:


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

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. 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

攒一口袋星星 2024-11-02 04:46:09

在这种情况下,您需要使用异常处理。基本上,其想法是获取输入并尝试转换为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')

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. If that fails, a ValueError is raised. 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. Assuming you are using Python 3, you can do something like this to keep asking until the right value is typed in:

# 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')
我们的影子 2024-11-02 04:46:09

我建议使用

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 中,它应该始终返回一个字符串,因此没有任何理由检查返回的对象是否是一个字符串。

I would recommend using

not h.isdigit()

to check if the string, h, doesn't contain an integer. 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 . 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. 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.

情何以堪。 2024-11-02 04:46:09
>>> isinstance('a', int)
False
>>> isinstance(2, int)
True
>>> isinstance('a', int)
False
>>> isinstance(2, int)
True
痴情 2024-11-02 04:46:09

使用 .isdigit().isalnum() 检查,具体取决于您喜欢

  1. 示例< /p>

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

    str_num= 'aaaa 7777' # 注意有空格
    str_num.isalnum() # false
    str_num.isdigit() # false
    
  3. 示例

    <前><代码>str_num='7777'
    str_num.isalnum() # True
    str_num.isdigit() # True
    示例

Use .isdigit() or .isalnum() to check , dependes that you prefer

  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
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文