logo

AQA A-Level Computer Science practice

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 first, then check the answer and practise the same topic again.

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.

Answer and explanation

Concise answer

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

Why this is correct

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.

Use the concise answer above for a quick check, then reveal the full model answer and detailed explanation.

Common mistake

No common mistake is linked to this question yet.

Related flashcards

No flashcards are published for this page yet.

Related practice questions