简体   繁体   中英

Having problems with python code that is meant to count every time 100 appears

I'm tying to create a program that will count every time someone inputs the number '100' and the program will end when '0' is inputted, but the code keeps counting '0' too.

getnumber = int(input())
result1 = 1
while True:
    getnumber = int(input())
    if getnumber == 100:
        result1 = result1+1

    if getnumber == 0:
        print(result1)

What has gone wrong here?

The while True will instruct to keep repeating the body of that loop. You thus should add a condition for it. As long as getnumber is not 0 , you want it to keep iterating, so while getnumber should work.

Another mistake is that you do not take the first number you query into account, and that you start result1 with 1 (instead of 0 ).

We can simplify the above to:

getnumber = True
result1 = 0
while getnumber:
    result1 += getnumber == 100
    getnumber = int(input())
print(result1)

Since a bool is a subclass of int , and False and True are 0 and 1 respectively, we thus can add getnumber == 100 to the number.

We use getnumber as a condition to check if we go for another loop. As long as getnumber is not 0 , we perform another loop. We initialize getnumber to True since that is not 100 (and it thus will not be counted), and furthermore it will make a loop.

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