python应用程序中输入和返回计数单词时出现问题

python应用程序中输入和返回计数单词时出现问题,python,Python,我现在刚刚开始学习,我一直在做一些练习,试图为我所做的基本函数添加一些输入 现在我有这个密码 print("This is an app calculate the lenght of a word") def String_Lenght(word): if type(word) == int: return "Integers can't be counted" elif type(word) == float: return "floats

我现在刚刚开始学习,我一直在做一些练习,试图为我所做的基本函数添加一些输入

现在我有这个密码

print("This is an app calculate the lenght of a word")

def String_Lenght(word):
    if type(word) == int:
        return "Integers can't be counted"
    elif type(word) == float:
        return "floats can't be counted"
    else:
        return len(word)
word = input("enter the word")
print(String_Lenght(word))
问题是我得到了单词的len,但是在我引入一个时,我没有得到int和float的消息,这就是这里的错误


感谢您阅读Python3+中的“word”始终是字符串

所以
类型(word)
总是字符串。因此,您将获得长度。检查以下程序的输出。我使用
importpdb使用硬断点;pdb.set_trace()

而不是尝试检查类型(word)。我认为应该将字符串转换为int/float

我认为转换为浮动是最好的选择

这个问题在Python3中。因为输入的所有数据都是字符串。你可以查一下

$python t.py
这是一个计算单词长度的应用程序
输入单词1
>/Users/sesh/tmp/t.py(6)字符串长度()
->如果类型(字)==int:
(Pdb)单词
'1'
(Pdb)类型(word)
(Pdb)整数(字)
1.
(Pdb)浮动(字)
1
(Pdb)int(asdfads)
***SyntaxError:扫描字符串文字时下线
(Pdb)
回溯(最近一次呼叫最后一次):
文件“t.py”,第13行,在
打印(字符串长度(字))
文件“t.py”,第6行,字符串长度
如果类型(字)==int:
文件“t.py”,第6行,字符串长度
如果类型(字)==int:
文件“/usr/local/ceral/python/3.6.5_1/Frameworks/python.framework/Versions/3.6/lib/python3.6/bdb.py”,第51行,跟踪调度
返回自调度行(帧)
文件“/usr/local/ceral/python/3.6.5_1/Frameworks/python.framework/Versions/3.6/lib/python3.6/bdb.py”,第70行,在调度行
如果自行退出:提出BdbQuit
bdb.bdbguit
(qsic api django)
sesh在sesh MacBook Pro中~/tmp

此问题的原因在于Python输入函数始终返回str类型。 因此,在您的代码类型(word)中,始终返回True。 您应该将代码更改为此

print("This is an app calculate the lenght of a word")

def String_Lenght(word):
    if word.isdigit():
        return "Integers can't be counted"
    elif word.replace(".", "", 1).isdigit():
        return "floats can't be counted"
    else:
        return len(word)


word = input("enter the word")
print(String_Lenght(word))

可以使用ast.literal_eval()函数将字符串计算为整数或浮点数,然后使用代码计算字符串的长度

from ast import literal_eval
print("This is an app calculate the length of a word")
def String_Lenght(word):
    try:
        word = literal_eval(word)
    except ValueError:
        pass
    if type(word) == int:
        return "Integers can't be counted"
    elif type(word) == float:
        return "floats can't be counted"
    else:
        return len(word)
word = input("enter the word")
print(String_Lenght(word))

input()
始终返回字符串。如果您输入
5
它只是一个值字符串
'5'
。您可以使用try/except语句查看输入是否可以转换为int/a浮点。@quant您可以在下面检查我的答案。我想我确实提供了一个更优雅的解决方案。
from ast import literal_eval
print("This is an app calculate the length of a word")
def String_Lenght(word):
    try:
        word = literal_eval(word)
    except ValueError:
        pass
    if type(word) == int:
        return "Integers can't be counted"
    elif type(word) == float:
        return "floats can't be counted"
    else:
        return len(word)
word = input("enter the word")
print(String_Lenght(word))