首页 > 解决方案 > 没有得到想要的输出(条件+函数)

问题描述

我是 Python 新手,一段代码似乎无法按预期工作。这是代码:

#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))

每当我在结果中输入一个整数时,它都会给出该整数的位数。但是,我想显示一条消息“输入不能是整数”。

我的代码中是否有任何错误,或者是否有其他方法可以做到这一点。请回复。谢谢你!

标签: python

解决方案


输入的任何输入始终是字符串。无法检查 int。它总是会失败。您可以执行以下操作。

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if string_input.isdigit():
    print("Input can not be an integer")
else:
    print(length_function(string_input))

输出:

Enter the string: Check
5

Enter the string: 1
Input can not be an integer

推荐阅读