|
| 1 | +import random |
| 2 | + |
| 3 | +# the .randrange() function generates a |
| 4 | +# random number within the specified range. |
| 5 | +num = random.randrange(1000, 10000) |
| 6 | + |
| 7 | +n = int(input("Guess the 4 digit number:")) |
| 8 | + |
| 9 | +# condition to test equality of the |
| 10 | +# guess made. Program terminates if true. |
| 11 | +if n == num: |
| 12 | + print("Great! You guessed the number in just 1 try! You're a Mastermind!") |
| 13 | +else: |
| 14 | + # ctr variable initialized. It will keep count of |
| 15 | + # the number of tries the Player takes to guess the number. |
| 16 | + ctr = 0 |
| 17 | + |
| 18 | + # while loop repeats as long as the |
| 19 | + # Player fails to guess the number correctly. |
| 20 | + while n != num: |
| 21 | + # variable increments every time the loop |
| 22 | + # is executed, giving an idea of how many |
| 23 | + # guesses were made. |
| 24 | + ctr += 1 |
| 25 | + |
| 26 | + count = 0 |
| 27 | + |
| 28 | + # explicit type conversion of an integer to |
| 29 | + # a string in order to ease extraction of digits |
| 30 | + n_str = str(n) |
| 31 | + num_str = str(num) |
| 32 | + |
| 33 | + # correct[] list stores digits which are correct |
| 34 | + correct = ['X'] * 4 |
| 35 | + |
| 36 | + # Ensure both n and num have the same length |
| 37 | + while len(n_str) < 4: |
| 38 | + n_str = '0' + n_str |
| 39 | + |
| 40 | + while len(num_str) < 4: |
| 41 | + num_str = '0' + num_str |
| 42 | + |
| 43 | + # for loop runs 4 times since the number has 4 digits. |
| 44 | + for i in range(0, 4): |
| 45 | + # checking for equality of digits |
| 46 | + if n_str[i] == num_str[i]: |
| 47 | + # number of digits guessed correctly increments |
| 48 | + count += 1 |
| 49 | + # hence, the digit is stored in correct[]. |
| 50 | + correct[i] = n_str[i] |
| 51 | + else: |
| 52 | + continue |
| 53 | + |
| 54 | + # when not all the digits are guessed correctly. |
| 55 | + if count == 0: |
| 56 | + print("None of the numbers in your input match.") |
| 57 | + else: |
| 58 | + print("Not quite the number. But you did get", count, "digit(s) correct!") |
| 59 | + print('\n') |
| 60 | + n = int(input("Enter your next choice of numbers: ")) |
| 61 | + |
| 62 | + # condition for equality. |
| 63 | + if n == num: |
| 64 | + # ctr must be incremented when the n==num gets executed as we have the other incrmentation in the n!=num condition |
| 65 | + ctr += 1 |
| 66 | + print("You've become a Mastermind!") |
| 67 | + print("It took you only", ctr, "tries.") |
0 commit comments