Как мне заставить мою функцию возвращать что-то кроме ссылки? - PullRequest
0 голосов
/ 16 февраля 2019

Когда я запускаю эту функцию, она возвращает None и ссылку вместо намеченного значения.

Я уже использую "return", который должен заставить функцию вернуть намеченное значение, нокак я уже говорил, он по-прежнему возвращает ссылку.

def querydate():
    querydate = int(input("Please enter a year between 2000 and 2017 for 
    processing injury data "))

    numberchoice0 = querydate
    while numberchoice0 is querydate:
        try:
            while int(numberchoice0)<2000:
                print("oopsie, that year is before those for which this 
                       query searches.")
                quit()
            while int(numberchoice0)>2017:
                print("oopsie, that year is after those for which this 
                       query searches.")
                quit()
        except ValueError:
            print ('That was not an integer!')
            affirmations = ('YES', 'Y')
            answer = input("Do you want to continue? (Yes/Y/y):\n")
            if answer.strip().upper() in affirmations:
                continue
        else:
            return querydate()

print(querydate())

def verify():
    verify = input("please enter 'yes' or 'no' ")
    if verify == "no":
        print("You should be more careful about inputting data!")
        quit()
    while verify != "yes":
        print(verify, "is not an appropriate input. If you answered 'YES' 
              or 'Yes' please enter 'yes'")
        continue
    if verify == "yes":
        print("Great! Let us continue")

verify()

Я ожидаю, что вывод будет числом между 2000 и 2017, но когда я печатаю querydate(), он возвращает "None", и когда яссылка querydate() с verify() фактически возвращает <function querydate at 0x000001F1DCFB9A60>

1 Ответ

0 голосов
/ 16 февраля 2019

return не заставляет функцию возвращать намеченное значение , его необходимо явно указать в соответствии с тем, что хочет вернуть.

Вы хотеливывод от 2000 до 2017, поэтому вам нужно вернуть значение, которое возвращает это.

def querydate():
    qDate = int(input("Please enter a year between 2000 and 2017 for 
    processing injury data "))

    numberchoice0 = qDate
    while numberchoice0 is qDate:
        try:
            while int(numberchoice0)<2000:
                print("oopsie, that year is before those for which this 
                       query searches.")
                quit()
            while int(numberchoice0)>2017:
                print("oopsie, that year is after those for which this 
                       query searches.")
                quit()
        except ValueError:
            print ('That was not an integer!')
            affirmations = ('YES', 'Y')
            answer = input("Do you want to continue? (Yes/Y/y):\n")
            if answer.strip().upper() in affirmations:
                continue
        else:
            return qDate #returning the integer instead of None

print(querydate())

def verify():
    verify = input("please enter 'yes' or 'no' ")
    if verify == "no":
        print("You should be more careful about inputting data!")
        quit()
    while verify != "yes":
        print(verify, "is not an appropriate input. If you answered 'YES' 
              or 'Yes' please enter 'yes'")
        continue
    if verify == "yes":
        print("Great! Let us continue")

verify()

Кроме того, поскольку вы явно ничего не возвращали, ссылка на querydate() с verify() должна вернуть адресная ссылка , но если вы вернули целое число, например querydate или numberchoice0, то он возвращает год из диапазона 2000-2017.

Редактировать:

Наскольковаш TypeError: 'int' object is not callable обеспокоен, это происходит из-за того, что имена локальной переменной и имя функции совпадают.Итак, сначала идентификатор querydate относится к функции querydate(), затем он входит в функцию и теперь он ссылается на переменную querydate и больше не относится к функция при назначении переменной querydate.Таким образом, изменение имени одного из идентификаторов устраняет проблему.

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