Shorten condition that checks if value is one of several possible

Asked

Viewed 67 times

0

Is there any way to shorten the if a == 1 or a == 2 or a == 3 of the code below?

a = int(input('Digite um número: '))

if a == 1 or a == 2 or a == 3:
    print('O Número digitado está entre 1 a 3')
else:
    print('O Número digitado não está entre 1 a 3')

2 answers

4

It is possible to do:

if 1 <= a <= 3:

So you’re saying that 1 has to be less than or equal to a which in turn has to be less than or equal to 3. So reaches the numbers you want.

Python allows this way of using the operator in order to take advantage of the comparison. I find it less intuitive most of the time, but other people may find it different. I think it may not compensate to shorten and leave more confused. Most people get lost in understanding that, you know, but it takes longer.

The good part of it is that it is fast to run, it can be even faster than the original comparison. Comparisons against sequences of numbers will be slower. Depending on what you do if you have more numbers you can get longer.

a = 0
if 1 <= a <= 3:
    print("0")
a = 1
if 1 <= a <= 3:
    print("1")
a = 3
if 1 <= a <= 3:
    print("3")
a = 4
if 1 <= a <= 3:
    print("4")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Vlw! Obg for help!

3

You can use the keyword in.
Use keyword in, in a condition, to check whether a sequence(list, range, string) contains a certain value. Matches function contains(a, b) module Operator:

a = int(input('Digite um número: '))

#se estiver contido na lista
if a in [1, 2, 3]:
    print('O Número digitado está entre 1 a 3')
else:
    print('O Número digitado não está entre 1 a 3')

If the range of values is continues you can instead of using a list use a crease:

a = int(input('Digite um número: '))

#se estiver contido entre 1 e 99
if a in range(1,100):
    print('O Número digitado está entre 1 a 99')
else:
    print('O Número digitado não está entre 1 a 99')
  • Vlw! Obg for help!

Browser other questions tagged

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