Python 3.5.1 - Give User 3 Invalid Attempts Then Terminate Pgm (simple For Loop)
I need assistance (new student - 2 weeks). I'd like to get the most minimal changes possible to this code that allows a user 3 chances at typing in the incorrect values for each c
Solution 1:
The easiest for you is probably to make a loop for each prompt like in the following pseudo Python code:
# Beginning of prompt
i = 0while i < 3:
result = float(input(<question>))
if <isok>:
print(<result>)
breakelse:
print(<error>)
i += 1# Three failed inputs.if i == 3:
print('Bye, bye!')
sys.exit(1)
at each <...>
you will have to write something sensible for your program.
UPDATE
A variant with for
loop:
# Beginning of prompt
ok = Falsefor i inrange(3):
result = float(input(<question>))
if <isok>:
print(<result>)
ok = Truebreakelse:
print(<error>)
# Three failed inputs.ifnot ok:
print('Bye, bye!')
sys.exit(1)
Remember ok = False
before each for
loop.
UPDATE 2
This is the whole program as I see it, where you get 3 chances on each input. I have taken the liberty of adjusting your print
statements.
import sys
# Beginning of prompt
ok = Falsefor i inrange(3):
miles = float(input('Type miles to be converted to km.\n'))
if miles >= 0:
milesToKm = miles * 1.6print('{} miles is {:.1f} kilometers.'.format(miles, milesToKm))
ok = Truebreakelse:
print('Wrong input, no negatives.')
# Three failed inputs.ifnot ok:
print('Bye, bye!')
sys.exit(1)
# Beginning of prompt
ok = Falsefor i inrange(3):
inch = float(input('Give me inches to convert to cm.\n'))
if inch >= 0:
inchesToCm = inch * 2.54print('{} inches is {:.2f} centimeters.'.format(inch, inchesToCm))
ok = Truebreakelse:
print('Wrong input, no negatives.')
# Three failed inputs.ifnot ok:
print('Bye, bye!')
sys.exit(1)
# Beginning of prompt
ok = Falsefor i inrange(3):
temp = float(input('Give me a Fahrenheit temp to convert to Celsius.\n'))
if temp <= 1000:
celsius = (temp - 32) * (5 / 9)
print('{} degrees Fahrenheit is {:.1f} Celsius.'.format(temp, celsius))
ok = Truebreakelse:
print('Wrong input, too high.')
# Three failed inputs.ifnot ok:
print('Bye, bye!')
sys.exit(1)
print('All OK')
Post a Comment for "Python 3.5.1 - Give User 3 Invalid Attempts Then Terminate Pgm (simple For Loop)"