While loop is printing both statements

Question:

I have two variables: balance and payment. If the user writes a negative value, I ask the question again.
Problem: in the while loop, when the user inserts a positive value, it still prints the while statement as well as the else statement. I want it to print while statement only when the value is 0 or less than zero. The rest of the code is working fine.

My code:

balance = 0

payment = 0

while balance <= 0:

    balance = int(input('What is your balance?:'))
    print('Kindly insert value again')    # problem in this line

else:
    print('your balance is',balance)

while payment <= 0:

    payment = int(input('How much would you like to save?:'))
    print('kindly write a positive value')
else:
    print("your payment is ", payment)

numpay = balance/payment

print(numpay)
Asked By: Nanao Chan

||

Answers:

The code will always execute the while loop at least one time because the condition is initially met. So the first print statement will always be executed. Then the second one will always be executed once the while statement is exited.

A suggestion for how to make this better:
Get the user input once before starting the while loop so that you only print the "kindly insert value again" if the balance is actually less than 0. So it would look like this:

balance = 0
payment = 0
balance = int(input('What is your balance?:'))
while balance <= 0:
     print('Kindly insert value again')
     balance = int(input('What is your balance?:'))
print('your balance is ', balance)

Then you could do something similar for the payment variable.

Answered By: frankM_DN
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.