Limit Python number input 3

Asked

Viewed 4,261 times

1

Using the following code I want to limit from 0 to 2000 the number that can be informed by the variable in a

import collections
num = int(input('Digite um número inteiro: '))    #Inputar número inteiro
binario = bin(num)[2:]     #Cortar o 0b
sequence = binario
collection = collections.Counter(sequence)
print('O número binário de {} é {}'.format(num,binario))
print('A maior sequência de 0 é {}'.format(len(max(binario.split('1'), 
key=len))))

It would limit the number to be entered in the variable in a.

1 answer

4

Just make a condition:

if 0 <= num <= 2000:
    # Faça algo

If you want to ask the user for a new entry while the value is invalid, you will need an infinite loop:

while True:
    try:
        num = int(input())
        if not 0 <= num <= 2000:
            raise ValueError('Valor fora do intervalo permitido')
        break
    except ValueError as error:
        print(error)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.