[英]Asking for 10-digit numbers
I am testing that the user input is of length 10 and only contains numbers. 我正在测试用户输入的长度为10,并且仅包含数字。 At the moment, my code is:
目前,我的代码是:
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
The program will ask for user input, then test that it is of 10 length and only contains integers. 该程序将要求用户输入,然后测试其长度为10,并且仅包含整数。 Currently, user input is read as a string so that if it began with a '0', then this would be included in len(), if you know what I mean?
当前,用户输入被读取为字符串,因此,如果它以“ 0”开头,那么如果您知道我的意思,它将被包含在len()中。 For example, if I inputted '0123456789', this would be seen to have a length of 10 and not 9 because it begins with '0'.
例如,如果我输入“ 0123456789”,则该长度将为10而不是9,因为它以“ 0”开头。 Also, I wanted to ensure that if the user entered 10 letters, this would be declined because only numbers are allowed.
另外,我想确保如果用户输入10个字母,由于只允许输入数字,因此将拒绝该字母。
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you.
谢谢。
At no point in your code do you actually check that the input is an integer.. You could do something like this: 实际上,您在代码中都没有检查输入是否为整数。您可以执行以下操作:
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
Info on str.isdigit()
: 有关
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.
while True:
number = input("Enter number: ")
try:
number = int(number)
except ValueError:
print ("Enter only numbers")
else:
if 10 > number//10**9 > 0 :
print ("Enter 10 digits")
continue
else:
break
You can checking for an error while casting to a number (integer) 您可以在强制转换为数字(整数)时检查错误
try:
if len(number) != 10 and int(number):
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
Note that the flaw in len(number) is that the nine firsts digit could be 0. 请注意,len(number)的缺陷在于,九个首位数字可能为0。
To ensure that is a valid number beetwen 1000000000 and 999999999 you can do the following: 为确保有效的数字beetwen 1000000000和999999999,您可以执行以下操作:
import math
while True:
try:
if math.floor(math.log10(int(number)))+1 == 10:
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.