Sophie Moritz
Sophie Moritz

Reputation: 31

While Loops to Count Down to Zero

I'm currently trying to use simple while loops to count down from a given positive number to zero and then stop. If the number isn't a positive number then it should loop and ask again. I've gotten most of it down, but I can't make it count down to zero. Right now it just stops at 1.

For this problem, zero is not counted as a positive number. If zero is entered, it should loop back to the initial prompt.

This is the code I have so far:

# set loop variable
looking_for_positive_number = True

# get positive number
while (looking_for_positive_number == True):
    reply = input("Enter positive number: ")
    int_reply = int(reply)

# count down from given positive number to 0, loop back to reply if not
    while int_reply > 0:
        print(int_reply)
        int_reply = int_reply - 1
        looking_for_positive_number = False

This is what it returns (I used 5 as the positive number):

Enter positive number: 5
5
4
3
2
1

Ideally, it should return something like this (also used 5 here):

Enter positive number:  5
5
4
3
2
1
0

I don't know what I'm missing/what I'm doing wrong. Any help would be appreciated. Thanks in advance!

EDIT: I figured it out, I just had to include an if statement in the nested while loop. Final code looks like this:

# set loop variable
looking_for_positive_number = True

# get positive number
while (looking_for_positive_number == True):
    reply = input("Enter positive number: ")
    int_reply = int(reply)

# count down from given positive number to 0, loop back to reply if not
# ZERO DOES NOT COUNT AS POSITIVE NUMBER -- SHOULD LOOP BACK IF 0 IS ENTERED
    while int_reply > 0:
        print(int_reply)
        int_reply = int_reply - 1

        # want to print 0 after we get down to 1 (but not include 0 in our initial loop)
        if int_reply == 0:
            print(0)

        # finish and exit loop
        looking_for_positive_number = False

Upvotes: 0

Views: 3138

Answers (2)

rhurwitz
rhurwitz

Reputation: 2737

The Python range function could simplify your logic (slightly). Using a negative step value it will count down instead of counting up.

Example:

while True:
    number = int(input("Enter a postive integer value: "))
    if number <= 0:
        print("Not a positive number.")
        continue
    for i in range(number, -1, -1):
        print(i)
    break

Output:

Enter a postive number: 5
5
4
3
2
1
0

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54726

# get positive number
while (looking_for_positive_number == True):
    reply = input("Enter positive number: ")
    int_reply = int(reply)
    if int_reply <= 0:
        print( "Not a positive number." )
        continue

# count down from given positive number to 0, loop back to reply if not
    while int_reply > 0:
        print(int_reply)
        int_reply = int_reply - 1
        looking_for_positive_number = False

Upvotes: 3

Related Questions