'除了 ValueError' 没有执行

时间:2021-05-18 06:15:49

标签: python valueerror

我只是想向用户询问一个字符串,但每当用户输入一个整数或一个浮点数时,它都不会执行除了 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.')

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

  • input() python 中的函数总是只将输入作为字符串。所以你的代码永远不会抛出异常。

    valueError 将在这种情况下捕获错误 -> int(word)。其中单词不包含纯数字。

  • 始终将您的陈述用双引号括起来。例如。 input("请输入名称:")

好的,你问了这个疑问。提出错误总是好的。

答案 2 :(得分:-1)

默认情况下,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.')

在这种情况下,您的代码正在运行。

相关问题