Using the while loop to give the user 3 attempts for a valid input value
<pre><code>counter = 0
miles = float(input('How many miles do you want converted into kilometers? '))
while miles &lt; 0:
    print('You cannot enter a negative value!')
    miles = float(input('Enter the correct number of miles: '))
    counter = counter + 1
    if counter &gt; 2:
        break
if counter &lt;= 2:
    milesToKm = (miles*1.6)
    print(miles, 'miles is', round(milesToKm,2), 'kilometers')
else:
    print('Error: cannot exceed three attempts')
    exit()
</code></pre>

<p>Hi everybody. This is my fifth week of learning to code. I'm supposed to create a program that will give the user three attempts to enter a valid value. If the value on the third attempt is invalid (a negative number), then it will prompt an error message and terminate.</p>

<p>The problem is that I can enter two invalid values followed by a valid value, and it still gives the error message and terminates. The program should calculate the third valid value and do the mathematics then print the conversion.</p>

<p>For example:</p>

<p>How many miles do you want converted into kilometers? -1</p>

<p>You cannot enter a negative value!</p>

<p>Enter the correct number of miles: -1</p>

<p>You cannot enter a negative value!</p>

<p>Enter the correct number of miles: 5</p>

<p>Error: cannot exceed three attempts</p>

<p>Can you guys help?</p>