Here my suggestion. Include a variable to track number of attempt. If the number of guess > 8, display a message, exit the loop. If the user guess the correct number, exit the loop immediately. here is an example:
https://www.jdoodle.com/embed/v0/zQq
Note: To test it, turn on the
Interactive mode then click on Execute button.