|
| 1 | +# Import random module |
1 | 2 | import random |
2 | 3 |
|
| 4 | +# Function for Computer Guess |
3 | 5 |
|
4 | | -def compguess(lowval, highval, randnum, count=0): |
5 | | - if highval >= lowval: |
6 | | - guess = lowval+(highval-lowval)//2 |
7 | | - if guess == randnum: |
| 6 | + |
| 7 | +def comp_guess(low_val, high_val, randnum, count=0): |
| 8 | + if high_val >= low_val: # When high_val greater than low_val |
| 9 | + guess = low_val+(high_val-low_val)//2 |
| 10 | + if guess == randnum: # if guess is equals randnum then return the count |
8 | 11 | return count |
9 | | - elif guess > randnum: |
| 12 | + elif guess > randnum:# if guess is greater than randnum the increase the count and call the function recursively again |
10 | 13 | count += 1 |
11 | | - return compguess(lowval, guess-1, randnum, count) |
| 14 | + return comp_guess(low_val, guess-1, randnum, count) |
12 | 15 | else: |
13 | 16 | count += 1 |
14 | | - return compguess(guess+1, highval, randnum, count) |
| 17 | + return comp_guess(guess+1, high_val, randnum, count) |
15 | 18 |
|
16 | 19 |
|
17 | | -randnum = random.randint(1, 100) |
18 | | -count = 0 |
19 | | -guess = 0 |
20 | | -print("\n\n\t\t\tWelcome To The GUESSING GAME Developed by @Satyam Tripathi") |
21 | | -while guess != randnum: |
| 20 | +# Driver Function |
| 21 | +randnum = random.randint(1, 100) # Store any random number b/w 1 and 100 |
| 22 | +count = 0 # Initialize count to 0 |
| 23 | +guess = 0 # Initialize guess to 0 |
| 24 | +while guess != randnum: # Loop till we guess the number |
| 25 | + # Taking input from the user |
22 | 26 | guess = int(input("\nPlease Guess the No. b/w 1 & 100: ")) |
23 | | - if guess > randnum: |
24 | | - print("You Guess \"Higher No.\" !") |
25 | | - elif guess < randnum: |
26 | | - print("You Guess \"Lower No.\" !") |
| 27 | + if guess > randnum:# Check whether number is Greater or not. |
| 28 | + print("You Guess Higher No.") |
| 29 | + elif guess < randnum:# Check whether number is Lower or not. |
| 30 | + print("You Guess Lower No.") |
27 | 31 | else: |
28 | | - print("Greate!, You guess the No. $$$") |
29 | | - count += 1 |
30 | | -print(f"You took: {count} Chances !") |
31 | | -print(f"Computer took: {compguess(0,100,randnum)} Chances !") |
| 32 | + print("Great!, You guess the No.") |
| 33 | + count += 1 # Increase count |
| 34 | +# Display the Final Result |
| 35 | +print(f"You took: {count} Chances!") |
| 36 | +# Call comp_guess function |
| 37 | +print(f"Computer took: {comp_guess(0,100,randnum)} Chances!") |
0 commit comments