Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loop is printing both statements

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading