Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ';除ValueError';没有执行_Python_Valueerror - Fatal编程技术网

Python ';除ValueError';没有执行

Python ';除ValueError';没有执行,python,valueerror,Python,Valueerror,我试图只要求用户输入一个字符串,但每当用户输入一个整数或浮点时,它都不会执行except 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.') 由Python中的缺省

我试图只要求用户输入一个字符串,但每当用户输入一个整数或浮点时,它都不会执行except 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.')

由Python中的缺省输入函数考虑输入为“字符串”,无论是<代码>输入代码< /COD> >您键入它是字符串。 要将输入转换为整数,必须键入以下代码

word=int(输入('enterastring'))
尝试:
word1=str(word)
打印(word1)
打印(打字(word1))
除值错误外:
打印('输入的值不是字符串')

在这种情况下,您的代码正在工作。

函数
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")
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")
尝试转换Try expect语句中的变量:

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")
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")
  • python中的input()函数始终仅将输入作为字符串。因此,您的代码永远不会抛出异常

    valueError将捕获本例中的错误->int(word)。其中单词不包含纯数字


  • 请务必将您的陈述用双引号引起来。如。 输入(“输入名称:”)


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

使用
input
函数查询的用户输入值总是作为字符串返回。此外,将整数或浮点转换为字符串也是完全允许的。您的代码根本不会引发任何要捕获和处理的
ValueErrors
。函数
input
返回字符串。用户输入始终返回字符串。不要检查它是否是字符串类型,而是尝试将其转换为float/integer。您应该精确定义在“字符串”中接受的字符,因为它不够精确。如果需要,您可以使用regex(模块re)查找字符串中的数字并打印错误消息。这里不需要异常处理,简单的if可以正常工作。当try块引发错误时,它执行“exception valueError:”,但在您的情况下,它不会引发任何错误。int(…)部分可能引发异常,这应该受到异常处理的保护。此示例不起作用,因为始终可以将数字转换为字符串而不出现异常/错误。如果用户尝试插入字符串,程序将引发异常“始终将语句包含在双引号中。例如输入(“输入名称”):为什么?因为这是编程的最佳实践。字符串中应使用双引号,指定字符时应使用单引号。例如,“C”,“Python很棒。”它提供了更多的说明,许多语言不支持字符串中的单引号。