Python 在函数中使用 input() 来确定数据类型

Python using input() within function to determine data type

我正在使用 Python 阅读计算机科学导论的最后一章。有人可以告诉我我的代码有什么问题吗?结果只是 BLANK.

#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))

要改进您的代码并使其更短更好,您可以这样做:

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")) 中。所以不管你输入什么,都是一样的。

编辑:另一个建议。请使用更好的逻辑来解决问题。只需考虑并优化它,您就可以在学习如何用任何语言编写代码方面走很长的路。 :)

解决您的问题:

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"))