Вызов ValueError в функции - PullRequest
0 голосов
/ 28 июня 2018

Я написал этот код, и когда я отправляю его в мой MOOC, он выдает ошибку, но все нормально в моем терминале?

def suggest(product_idea):
    return product_idea + "inator"

try:
    product_idea = input("What is your product idea? ")
    if len(product_idea) <= 3: #to catch the exception of people trying to use LESS THAN 3 characters
        raise ValueError("Your product Idea is too short. Please re-submit with more than 3 characters.") #raise is used here to capture the error
except ValueError as err: #this is to handle the error from line 8
        print("Oh no! That's not a valid value. Try again...")
        print("({})".format(err)) #this is to handle the error from line 8
else:
        print("Great idea!")

Вот ошибка, которую я получаю от MOOC (Treehouse):

Bummer: Oh no, there were 2 problems with your code, check the preview pane for more information
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
EE
======================================================================
ERROR: test_exception_not_raised (__main__.TestRaiseExecution)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 23, in test_exception_not_raised
  File "/workdir/utils/challenge.py", line 20, in execute_source
    exec(src)
  File "", line 5, in 
EOFError: EOF when reading a line

======================================================================
ERROR: test_exception_raised (__main__.TestRaiseExecution)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 30, in test_exception_raised
  File "/workdir/utils/challenge.py", line 20, in execute_source
    exec(src)
  File "", line 5, in 
EOFError: EOF when reading a line

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (errors=2)

Ответы [ 2 ]

0 голосов
/ 15 марта 2019

Похоже, вы вставили часть 'else' оператора 'if else' в неправильный блок кода. Он относится к категории «Try» в вашем блоке Try.

    def suggest(product_idea):
        return product_idea + "inator"

    try:
        product_idea = input("What is your product idea? ")
        if len(product_idea) <= 3: #to catch the exception of people trying to use LESS THAN 3 characters
            raise ValueError("Your product Idea is too short. Please re-submit with more than 3 characters.") #raise is used here to capture the error
        else:
            print("Great idea!")

    except ValueError as err: #this is to handle the error from line 8
            print("Oh no! That's not a valid value. Try again...")
    print("({})".format(err)) #this is to handle the error from line 8

Кроме того, я создал другую версию вашего кода, в которой созданная вами функция offer () вызывается в блоке Try.

    def suggest(product_idea):
        print(product_idea + "inator")

    try:
        product_idea = input("What is your product idea? ")
        if len(product_idea) <= 3: #to catch the exception of people trying to use LESS THAN 3 characters
            raise ValueError("Your product Idea is too short. Please re-submit with more than 3 characters.") #raise is used here to capture the error
        else:
            suggest(product_idea)
            print("Great idea!")

    except ValueError as err: #this is to handle the error from line 8
            print("Oh no! That's not a valid value. Try again...")
    print("({})".format(err)) #this is to handle the error from line 8

Надеюсь, это поможет!

0 голосов
/ 28 июня 2018

используйте raw_input("What is your product idea? ") вместо input("What is your product idea? ")

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...