Python, использующий input() внутри функции для определения типа данных

Я нахожусь в одной из последних глав моего "Введения в информатику с использованием Python". Может кто-нибудь сказать мне, что не так с моим кодом? Результат просто пустой.

#Write a function  called "input_type" that gets user input and 
#determines what kind of string the user entered.

#  - Your function should return "integer" if the string only
#    contains characters 0-9.
#  - Your function should return "float" if the string only
#    contains the numbers 0-9 and at most one period.
#  - You should return "boolean" if the user enters "True" or
#    "False". 
#  - Otherwise, you should return "string".

#Remember, start the input_type() function by getting the user's
#input using the input() function. The call to input() should be
#*inside the* input_type() function.


def input_type(userInput):
    digitTable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    test1 = userInput.find(digitTable)
    if userInput == "True" or userInput == "False":
        return "boolean"
    elif test1 == -1:  # No digits
        return "string"
    elif userInput == "True" or userInput == "False":
        return "boolean"
    else:  # Contains digits
        test2 = userInput.find(".") # find decimal
        if test2 == -1:  # No decimals means it is an integer
            return "integer"
        else:  # Yes if float
            return "float"

userInput = input()
print(input_type(userInput))

3 ответа

Решение

Чтобы решить вашу проблему:

def input_type(userInput):
    digitTable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    test1 = userInput.find(''.join([str(x) for x in digitTable]))
    if userInput == "True" or userInput == "False":
        return "boolean"
    elif test1 == -1:  # No digits
        return "string"
    elif userInput == "True" or userInput == "False":
        return "boolean"
    else:  # Contains digits
        test2 = userInput.find(".") # find decimal
        if test2 == -1:  # No decimals means it is an integer
            return "integer"
        else:  # Yes if float
            return "float"

userInput = input()
print(input_type("0.23"))

Чтобы улучшить свой код и сделать его короче и приятнее, вы можете сделать что-то вроде этого:

import re

def input_type(userInput):
    if userInput in ("True", "False"):
        return "boolean"
    elif re.match("^\d+?\.\d+?$", userInput):
        return "float"
    elif userInput.isdigit():
        return "int"
    else:
        return "string"

res = input()
print(input_type(res))

Работает для меня:)

Вот твоя ошибка. Когда вы запускаете программу, она ждет input(), Вы должны ввести что-то. Так что это держит всю программу. Еще одна проблема с вашей программой. Вы жестко закодировали параметры в print(input_type("0.23")), Поэтому независимо от того, что вы вводите, оно будет одинаковым.

РЕДАКТИРОВАТЬ: еще одно предложение. Пожалуйста, используйте лучшую логику для решения проблемы. Просто подумав об этом и оптимизировав, вы научитесь программировать на любом языке.:)

Другие вопросы по тегам