简体   繁体   中英

program to count number of 0's and 1's

x = int(input('ENTER A NUMBER '))
count = 0
while x > 0:
    digit = x % 10
    if digit == 0 or digit == 1:
        count += 1
        x //= 10
print('THE NUMBER OF ONES OR ZEROES TOGETHER ARE: ', count)

If I run the above program with x//10 inside the if loop, the output only comes true if the user enters number containing 0's and 1's, any other input and I do not get the output at all.

x = int(input('ENTER A NUMBER '))
count = 0
while x > 0:
    digit = x % 10
    if digit == 0 or digit == 1:
        count += 1
    x //= 10
print('THE NUMBER OF ONES OR ZEROES TOGETHER ARE: ', count)

This code works just fine. I am confused.

In the first snippet, the call:

x //= 10

is made inside the if-statement , so it is only executed when the current digit being evaluated is either a 0 or a 1 . This means that when it doesn't meet this condition, x is never modified, so the same test is run over and over again - never ending.

In the second snippet, the same call is made outside of the scope of the if-statement so regardless of what the current digit is, x is modified to have one less character and the next character is evaluated rather than the same one as was happening in the first snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM