python - 没有得到想要的输出(条件+函数)
问题描述
我是 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))
每当我在结果中输入一个整数时,它都会给出该整数的位数。但是,我想显示一条消息“输入不能是整数”。
我的代码中是否有任何错误,或者是否有其他方法可以做到这一点。请回复。谢谢你!
解决方案
输入的任何输入始终是字符串。无法检查 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
推荐阅读
- python - 如何在 python 中使用 selenium 从动态 url 中获取数据字段
- javascript - 将函数“generateToken”导入Node js中的中间件时出错
- python - Python包探索(urllib)(Windows)(Python3.9.6)
- docker - Intellij Docker 调试器挂起并显示消息“警告:验证自动检测到的连接”
- python - 为 DataFrame 重塑数组
- c# - 如何在 LINQ to Entity Select tag {} 中使用 Join 和 count?
- python - Python aiohttp ClientSession 请求内存泄漏?
- java - 为什么我的 Gradle Build 不适用于 Lombok?
- python - 覆盖 Wagtail 删除确认消息
- html - VBA web Scraping - 将 HTMLdoc 转换为 XML,但在单击按钮时遇到错误