关于Python语法
内置函数返回类型为关于Python语法,python,python-3.x,user-input,Python,Python 3.x,User Input,内置函数返回类型为str的值 正如在函数get\u input()声明之后的(doc)字符串中指定的: 您需要进行类型转换 因此,必须将其包装在int()中,才能将其转换为整数int Give me one of 1,2 or 3: sid Invalid input! Give me one of 1,2 or 3: 34 Invalid input! Give me one of 1,2 or 3: -7 Invalid input! Give me one of 1,2 or 3: 0 I
str
的值
正如在函数get\u input()
声明之后的(doc)字符串中指定的:
您需要进行类型转换
因此,必须将其包装在int()
中,才能将其转换为整数int
Give me one of 1,2 or 3: sid
Invalid input!
Give me one of 1,2 or 3: 34
Invalid input!
Give me one of 1,2 or 3: -7
Invalid input!
Give me one of 1,2 or 3: 0
Invalid input!
Give me one of 1,2 or 3: 2
Process finished with exit code 0
然后,您可以使用比较运算符来评估它是否位于可接受值的限定范围内:
n = int(input("Enter the number 1,2 or 3? "))
如果您提供了数字,则此功能非常有效:
# Your comparisons are mixed.
# You can use the in operator which is intuitive and expressive
while n not in [1, 2, 3]:
print("Invalid Input, give the number between 1 to 3")
# remember to wrap it in an int() call again
n = int(input ("Enter the number 1,2 or 3? "))
return (n)
但是,如果提供单个字符或字符串(键入str
),则会出现错误:
Enter the number 1,2 and 3? 10
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the number between 1 to 3
这超出了问题的范围,但您可能会这样做
不管怎样,你的健康状况让我很不舒服
您可能正在使用
python2
和通过导入的print\u函数
。(或者不同类型之间的比较会在while
语句中引发TypeError
)
检查您的python版本python-V
[在命令行中]并:
如果使用python 2而不是input()
使用raw\u input()
:
如果我错了,而您确实在使用python3.x
,请按照说明使用int(input())
。其python3.3,谢谢。让我检查一下它是否有效,啊,不太确定3.3
中的这些行为。您可能应该获得最新版本,这样您就不会感到困惑了。它工作正常,除了它不适用于、、之外,请给我1、2或3中的一个:sid无效输入!是的,在输入字符串的情况下,您需要执行一些操作。您的代码可能会抛出一个错误TypeError:unorderable types…
,当您提出一个包括错误和回溯在内的问题时,它不起作用通常信息量不大,即使您强制转换代码,如果用户输入的字符串不能强制转换为int,代码也会崩溃,您也应该使用try/except
Enter the number 1,2 and 3? 10
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? a
ValueError: invalid literal for int() with base 10: 'a'
n = int(raw_input("Enter the number 1, 2, 3: ")