如何限制输入中的位数? [英] How can I limit the amount of digits in an input?

查看:181
本文介绍了如何限制输入中的位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名正在学习计算机科学课程的学生,对于部分评估,我们必须编写一个程序,该程序将从用户那里获得10位数字,并使用它们来计算第11位数字,以便生成ISBN.用户输入的数字必须限制为一位,如果输入的位数超过一位,则将显示错误消息.这是我正在使用的代码:

I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th number in order to produce an ISBN. The numbers that the user inputs HAVE to be limited to one digit, and an error message should be displayed if more than one digit is entered. This is the code that I am using:

print('Please enter your 10 digit number')
a = int(input("FIRST NUMBER: "))
aa = (a*11)
if len(a) > 1:
    print ("Error. Only 1 digit allowed!")
b = int(input("SECOND NUMBER: "))
bb = (b*10)
if len(a) > 1:
    print ("Error. Only 1 digit allowed!")

ect.

我必须将输入保持为整数,以便在程序的其余部分中进行某些计算,但是当我运行程序时,出现错误,提示类型为'int'的对象没有len()".我假设它是指它是整数且没有长度的事实.有什么方法可以将'a'保留为整数,但将长度限制为1位?

I have to keep the inputs as integers so that some of the calculations in the rest of the program work, but when I run the program, an error saying "object of type 'int' has no len()". I'm assuming that it is referring to the fact that it is an integer and has no length. Is there any way that I can keep 'a' as an integer but limit the length to 1 digit?

(我也知道可能有一种更有效的编写程序的方法,但是我对python的了解非常有限)

(Also I understand that there is probably a more efficient way of writing the program, but I have a fairly limited knowledge of python)

推荐答案

您必须将int转换为字符串,因为int没有length属性.另外,您正在检查数字是否大于1两次,所以我将SECOND NUMBER的检查项切换为b

You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b

print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
    print ("Error. Only 1 digit allowed!")
a = int(a)
aa = (a*10)

b = raw_input("SECOND NUMBER: ")
if len(b) > 1:
    print ("Error. Only 1 digit allowed!")
b = int(b)
bb = (b*10)

或更简单地说:

您可以要求输入数字,并一直询问直到长度为10且输入为数字

Or more simply:

You could ask for the number and keep asking until the length is 10 and the input is a number

num = raw_input('Please enter your 10 digit number:')
while len(num) != 10 or (not num.isdigit()):
    print 'Not a 10 digit number'
    num = raw_input('Please enter your 10 digit number:')
num = int(num)
print 'The final number is: ', num

这篇关于如何限制输入中的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆