如何在相同的代码中使用字符串和整数?

时间:2016-01-31 18:07:43

标签: python-3.x

所以我开始编写一个代码,只允许用户输入数字,特别是7或8个数字..e34345678 只允许数字的代码:

&ansOne

但是当我尝试使用时:

scanf

它给我一个错误:无法解决的类型:str()和int()。 所以我的问题是如何才允许用户输入数字,只允许输入7或8位数字,不多也不少。

我做了一些研究,发现我必须使用 NumGiven='' while not NumGiven.isnumeric(): NumGiven=(input('Please enter a 7 or 8 digit number:') 但它会给我:' int'对象没有属性' isnumeric。

3 个答案:

答案 0 :(得分:1)

len(NumGiven)返回字符串的长度。

while len(NumGiven)<7 and len(NumGiven)>8:也不正确。数字如何都是&lt; 7和&gt; 8?这是一个等待正确输入的解决方案:

while True:
    NumGiven = input('Please enter a 7 or 8 digit number:')
    if NumGiven.isnumeric() and len(NumGiven) in (7,8):
        break
    else:
        print('Please enter a 7- or 8-digit number.')
# Now the input is valid, convert to integer if needed
num = int(NumGiven)

答案 1 :(得分:1)

您需要使用len()方法来获取字符串的长度。

while len(NumGiven)<7 or len(NumGiven)>8:

在您的代码中,您需要检查NumGiven的值是否小于7 (应该)大于8。 NumGiven的值实际上是一个字符串,尝试将其与数字进行比较是没有意义的。

Re:你的编辑:不,不要使用

NumGiven=int(input('Please enter a 7 or 8 digit number:'))

将其保留为字符串。

答案 2 :(得分:-2)

输入函数读取字符串,因此您可能需要将if转换为int然后执行检查。您还需要检查字符串读取的长度:

NumGiven=input('Please enter a 7 or 8 digit number:')
while len(NumGiven)==7 or len(NumGiven)==8:
   NumGiven=input('Please enter a 7 or 8 digit number:')
else:
   raise TypeError