如何同时确定输入为整数和长度? [英] How do I determine input as an integer and the length, simultaneously?

查看:49
本文介绍了如何同时确定输入为整数和长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我真的是编程新手.我的程序要求用户输入"3位数字" ...,我需要在测试的同时确定数字的长度(确保数字长度不少于3位)是一个整数.这就是我所拥有的:

Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:

while True:
    try:
        number = int(input("Please enter a (3 digit) number: "))
    except:
        print('try again')
    else:
        break

任何帮助,我们感激不尽!:)

any help is appreciated! :)

推荐答案

input()返回一个字符串.因此,您可以先检查该数字的长度,并且长度不是3,然后可以再次询问用户.如果长度为3,则可以通过 int()使用该字符串作为数字. len()为您提供字符串的长度.

input() returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by int(). len() gives you the length of the string.

while True:
    num = input('Enter a 3 digit number.')
    if len(num) != 3:
        print('Try again')
    else:
        num = int(num)
        break

这篇关于如何同时确定输入为整数和长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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