logo

Question detail

Write Python code that repeatedly asks the user for a whole number. If the input cannot be converted to an integer, the program should display a message and ask again. When a valid integer is entered, the loop should stop.

Try the question, check the answer, then read the explanation to understand the curriculum point.

At a glance

Question

Type

practice

Style

Topic

Programming

Exam-style question

Try this first

Write Python code that repeatedly asks the user for a whole number. If the input cannot be converted to an integer, the program should display a message and ask again. When a valid integer is entered, the loop should stop.

Model answer

What a good answer should say

  • valid = False while not valid: try: number = int(input("Enter a whole number: ")) valid = True except: print("That input is not a whole number.
  • Try again.")

Explanation

Why this works

The conversion of the input is placed in the try block because it may cause an exception. If an exception occurs, the except block displays a message and valid remains False, so the loop repeats.

When conversion succeeds, valid becomes True and the loop stops.

Common mistake

No common mistake is linked to this question yet.

Related flashcards

No flashcards are published for this page yet.

Related practice questions

No questions are published for this page yet.