Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write a program that asks for a whole number again and again until the user types one. The user types abc, 4.5 and 12. What does the program show?
while True, try, break on success, except to ask again.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
Plan. A while True: loop. Inside, try the conversion and break on success. The except ValueError part says to try again.
abc: not a whole number, so the program asks again.4.5: int("4.5") also fails, because 4.5 is not a whole number, so it asks again.12: it works, and the program shows You typed 12.Log in to join the discussion.
Loading…