Code abbreviation with several similar "bye" values

A very simple question, perhaps, but I wrote my first program and did not know what to look for in order to find the answer.

I have a while statement that looks something like this:

while number > 9999 or number < 0 or number == 1111 or number == 2222 or number == 3333...

And I continue, until I get to 9999. A lot of code that can probably be shortened, am I right? Not sure where I could read about grammar for this, so that someone could also link me there!

I would be glad if someone could help! :)

+4
source share
2 answers

Use the modulo operator:

while number > 9999 or number < 0 or (number % 1111 == 0 and number != 0):
+9
source

You can combine the first two operators

number > 9999 or number < 0

into one using set theory

number not in range(0,9999)

:

not number % 1111

, number, 0, - . , 1 % 3 = 1 ( , ), 4 % 2 = 0 ( 4/2 = 2*2, , , 0 ) ..

Python True 1, False 0. , , number , 1111 , . , :

, number = 53. number/1111 = 53/1111 = 53 - 1111. , True ( True == 53!= 0 == False) not a False ( not True False ). while , True.

, True:

while (number not in range(0,9999)) or (not number % 1111):
  # do something

0 , not in range(1,9999).

+3

Source: https://habr.com/ru/post/1627175/


All Articles