new to Python and i'm just wondering how to restrict the user input to make sure that they enter 64 bits

at the moment i've got this code

while True:
num = input('Please enter 64-bits')
if len(num=4)
    print ('Accepted')
    break
else:
    print ('Not Accepted, try again')

i know that line 3 is wrong but I'm pretty sure I have to use len in some way, any help is greatly appreciated, thanks!

有帮助吗?

解决方案 2

The answer from falsetru won't work if the number starts with leading zeroes and you want to accept this as valid input.

You may want to use raw_input instead of input -- this way you'll get the raw string that the user enters. Then you can easily test the length of that string, in addition to converting the number with int(<x>, 2). Something like this, for instance:

while True:
    raw = raw_input('Please enter 64 bits: ')
    try:
        num = int(raw,2)
    except ValueError:
        print("Not a valid binary number")
        continue
    if len(raw)==64:
        print ('Accepted')
        break
    else:
        print ('Not Accepted, need exactly 64 bits.  Try again')

其他提示

How about using int.bit_length method? (if you mean num is integer number)

>>> (1).bit_length()
1
>>> (2 ** 10).bit_length()
11
>>> (1 << 63).bit_length()
64

UPDATE

First convert the input string into number using int (with 2 as base).

>>> int('000001', 2)
1
>>> int('000001', 2).bit_length()
1
>>> int('00101', 2)
5
>>> int('00101', 2).bit_length()
3
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top