我试图只向用户请求一个字符串,但是每当用户键入一个整数或浮点数时,它都不会执行ValueError代码。
下面是我的代码:
word = input('Enter a string.')
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')发布于 2021-05-18 14:47:04
函数input总是返回一个字符串。您可以通过以下方式之一检查输入是否为数字:
在str类中使用内置方法:
word = input('Enter a string.')
# Check if the input is a positive integer without try except statements:
if word.isnumeric():
# The word contain only numbers - is an positive integer.
print("positive int")尝试转换try expect语句中的变量:
word = input('Enter a string.')
# Check if the input is a positive integer with try except statements:
try:
word = float(word)
print("the input is a float")
except ValueError:
print("the input is a string")发布于 2021-05-18 14:52:18
python中的
valueError将捕获错误,在本例中为-> (Word)。其中word不包含纯数字。
很好,你问了这个疑问。询问错误总是很好的。
发布于 2021-05-18 14:39:22
python中的默认输入函数将您的输入视为“enter code here”,无论您键入的是什么字符串。要将您的输入转换为整数,您必须键入此代码。
word = int(input('Enter a string.'))
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')在这种情况下,您的代码可以正常工作。
https://stackoverflow.com/questions/67580853
复制相似问题