我正在测试用户输入的长度为10,并且仅包含数字。目前,我的代码是:
while True:
number = input("Enter number: ")
try:
if len(number) != 10:
print ("Enter 10 digits\n")
continue
except ValueError:
print ("Enter only numbers\n")
continue
else:
break
该程序将要求用户输入,然后测试其长度为10,并且仅包含整数。当前,用户输入被读取为字符串,因此如果它以“ 0”开头,那么如果您知道我的意思,它将被包含在len()中。例如,如果我输入“ 0123456789”,则该长度将为10而不是9,因为它以“ 0”开头。另外,我想确保如果用户输入了10个字母,由于只允许输入数字,因此会被拒绝。
任何帮助将不胜感激。谢谢你。
实际上,您在代码中都没有检查输入是否为整数。您可以执行以下操作:
while True:
number = input("Enter number: ")
if not number.isdigit(): # check if a string contains a number with .isdigit()
print ("Enter only numbers\n")
continue
elif len(number) != 10:
print ("Enter 10 digits\n")
continue
else:
break
信息str.isdigit()
:
Type: method_descriptor
String Form:<method 'isdigit' of 'str' objects>
Namespace: Python builtin
Docstring:
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句