Nauč se Python > Kurzy > Beginners course PyLadies > Testing > Exceptions

Exceptions – Řešení [0]

Possible solution for the calculator:

while True:
    try:
        side = float(input('Enter the side of a square in centimeters: '))
    except ValueError:
        print('That was not a number!')
    else:
        if side <= 0:
            print('That does not make sense!')
        else:
            break

print("The perimeter of a square with a side of", side,"cm is ", side * 4,"cm.")
print("The area of a square with a side of", side,"cm is", side * side, "cm2.")

Possible solution for 1-D ticktactoe:

def load_number(field):
    while True:
        try:
            position = int(input('Which position do you want to fill? (0..19) '))
        except ValueError:
            print('This is not a number!')
        else:
            if position < 0 or position >= len(field):
                print('You can not play outside the field!')
            elif field[position] != '-':
                print('That position is not free!')
            else:
                break

    field = field[:position] + 'o' + field[position + 1:]
    return field


print(player_move('-x----'))

Toto je stránka lekce z kurzu, který probíhá nebo proběhl naživo s instruktorem.