Проверка Python int / str - PullRequest
       8

Проверка Python int / str

1 голос
/ 24 марта 2011

У меня есть домашнее задание, и я выполнил минимум задания, но, работая над ним, я заинтересовался, как улучшить свою программу. Смысл кода состоит в том, чтобы нарисовать определяемую пользователем форму и предоставить обратную связь, если они вводят неверные данные. Я хочу пойти дальше и сделать так, чтобы пользователь вводил str для высоты / ширины или одну из координат, это выдает ошибку, но я не могу понять, как именно это сделать. Это вводный класс, так что, если вы помните, мы просто переходим к циклам while и переходим к циклам, если / 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()

Ответы [ 4 ]

6 голосов
/ 24 марта 2011

В этом случае вы хотите использовать обработку исключений.По сути, идея состоит в том, чтобы взять входные данные и попробовать для преобразования в 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')
3 голосов
/ 24 марта 2011

Я бы порекомендовал использовать

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 он всегда должен возвращать строку, поэтому нет никаких оснований проверять, является ли возвращаемый объект строкой.

2 голосов
/ 24 марта 2011
>>> isinstance('a', int)
False
>>> isinstance(2, int)
True
0 голосов
/ 19 марта 2019

Используйте .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
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...