Skip to content

Nested If Instance

Random generate a number in the range of 1 - 10, and user has 3 opportunities for guessing

Requirements:

  • Using 3 nested if
  • If the number guessing is wrong, will giving hints either the value should be smaller or bigger.
  • using random library

Example

nested-if-example.py

py
import random

correct_answer = random.randint(1, 10)

user_input = int(input("Please guess a number in between 1 - 10: "))

# First trial
if user_input != correct_answer:
    print("Oops, try again. 2 more chances remained")

    # Hints after the first trial
    if user_input > correct_answer:
        print(f"The correct number should be lower than {user_input}")
    else:
        print(f"The correct number should be greater than {user_input}")

    # 2nd trial
    user_input = int(input("Please guess a number in between 1 - 10 (2nd trial): "))

    # 2nd round still incorrect
    if user_input != correct_answer:
        
        print("Oops, try again. 1 more chances remained")
        # Hints after failed 2nd round
        if user_input > correct_answer:
            print(f"The correct number should be lower than {user_input}")
        else:
            print(f"The correct number should be greater than {user_input}")

        # Third trial
        user_input = int(input("Please guess a number in between 1 - 10 (3rd / final trial): "))

        # Results for 3rd trial
        if user_input == correct_answer:
            print("You has guess the number on third trial !")
        else:
            # Failed all 3 chances
            print(f"You failed all 3 times guess, the correct answer should be: {correct_answer}")

    else:
        # 2nd trial was guessing correctly
        print("You has guess the number on second trial !")
    
# First trial = correct    
else:
    print("You has guess the number on first trial !")

Results:

1st trial

Guessing value : 5, 7, 9

Please guess a number in between 1 - 10: 5      
Oops, try again. 2 more chances remained
The correct number should be greater than 5
Please guess a number in between 1 - 10 (2nd trial): 7
Oops, try again. 1 more chances remained
The correct number should be greater than 7
Please guess a number in between 1 - 10 (3rd / final trial): 9
You failed all 3 times guess, the correct answer should be: 8

2nd trial

Guessing value : 5, 3, 2

Please guess a number in between 1 - 10: 5
Oops, try again. 2 more chances remained
The correct number should be lower than 5
Please guess a number in between 1 - 10 (2nd trial): 3
Oops, try again. 1 more chances remained
The correct number should be lower than 3
Please guess a number in between 1 - 10 (3rd / final trial): 2
You has guess the number on third trial !

Improvement

Of course, many line of the codes are actually repeated, it can be optimised by using while looping.