0

I'm trying to write a program that uses a while loop to repeatedly ask a user to input a positive integer until they do but my code keeps printing the number after the while look asks a second time and I don't want that. This is my code below:

num = int(input("Enter a positive integer: "))

while num <= 0:
    print(int(input("Enter a positive integer: ")))

print(f"{num} is positive.")

this is what prints when I execute the code:

Enter a positive integer: -4

Enter a positive integer: -3

-3

Enter a positive integer: -6

-6

Enter a positive integer:

Lava_lakes
  • 13
  • 1
  • 3
  • Because you print the number with `print` function. Also, you don't write the users input to `num` inside of the loop, so `num` never changes after the first line – Yevhen Kuzmovych Aug 04 '22 at 10:35

3 Answers3

0
num = int(input("Enter a positive integer: "))

while num <= 0:
    num = int(input("Enter a positive integer: "))
    
print(f"{num} is positive.")

This could be a possible solution.

This solution only prints when the user enters any positive integer.

Finix
  • 1
  • 3
0

Can use a while True loop instead, then break the loop when your condition (positive integer inputted) is satisfied:

while True:
    num = int(input("Enter a positive integer: "))
    if num > 0:
        print(f"{num} is positive")
        break
hlin03
  • 125
  • 7
-1
num = int(input("Enter a positive integer: "))

while num <= 0:
    num = int(input("Enter a positive integer: "))

print(f"{num} is positive.")

This should work. Your while-loop is checking if the number is positive, but you are not changing the number based on the new input.

Felix G
  • 724
  • 5
  • 17