Courseiva
Control Flow, Loops, Lists and LogiceasyMultiple ChoiceObjective-mapped

PCEP Control Flow, Loops, Lists and Logic Practice Question

A developer is writing a simple number guessing game. The computer picks a random number between 1 and 100, and the user keeps guessing until correct. The developer implements:

secret = random.randint(1,100) guess = 0

while guess != secret:

guess = int(input("Guess: "))

if guess == secret:
        print("Correct!")

else:

print("Wrong, try again.")

The game works, but the developer notices that if the user enters something that is not an integer, the program crashes. Which modification ensures the program handles non-integer input gracefully?

⚠ Common exam trap

Python Institute often tests the distinction between input validation (like `isdigit()`) and exception handling (`try-except`), where candidates mistakenly believe checking for digits is sufficient, ignoring that `int()` can still fail on valid-looking strings like '-5' or ' 10'.

Answer choices

Why each option matters

Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.

Correct answer & explanation

Use a try-except around the input conversion

Wrapping the `int(input(...))` in a `try-except` block catches the `ValueError` that occurs when the user enters a non-integer string. This allows the program to handle the error gracefully (e.g., by printing a message and continuing the loop) instead of crashing. The other options do not prevent the crash when `int()` receives invalid input.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • Use a while True loop with break

    Why it's wrong here

    Does not handle non-integer input.

  • Change the data type of guess to string

    Why it's wrong here

    Then comparison guess != secret would always be True, infinite loop.

  • Use a try-except around the input conversion

    Why this is correct

    Catches ValueError and allows reprompt.

  • Add an if statement to check if input is digit

    Why it's wrong here

    String.isdigit() returns False for negative numbers and floats, still crashes.

About these practice questions

One of 498 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

JA

Written by Johnson Ajibi, MSc IT Security

Senior Network & Security Engineer · founder of Courseiva

This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.