|
1 | 1 | #!/usr/bin/env python |
2 | | -"""Python guessing game by @tlystad24 |
3 | | -This program creates a random number between 1 and 100 and has the user guess it. |
4 | | -""" |
5 | | -import random |
6 | | - |
7 | | -def main(): |
8 | | - attempts = 1 |
9 | | - print "How many numbers do you want?" |
10 | | - howMany = input("Ammount: ") |
11 | | - # print "Guess the number between 1 and",howMany,"." |
12 | | - print 'Guess the number between 1 and {}.'.format(howMany) |
13 | | - #randomNumber = 35 <- Number used for debugging and early development. |
14 | | - randomNumber = random.randint(1,howMany) |
15 | | - found = False # flag variable to see if they guessed it. |
16 | | - |
17 | | - while not found: |
| 2 | +# text-based guessing game written in Python by @tlystad24 |
18 | 3 |
|
19 | | - userGuess = input("Your guess: ") |
20 | | - if userGuess == randomNumber: |
21 | | - print "You have guessed the correct number! You used",attempts,"attempts." |
22 | | - found = True |
23 | | - |
24 | | - elif userGuess > randomNumber: |
25 | | - print ("Guess lower!") |
26 | | - attempts = attempts + 1 |
27 | | - else: |
28 | | - print ("Guess higher!") |
29 | | - attempts = attempts +1 |
30 | 4 |
|
| 5 | +# Import random library to generate the number to guess. |
| 6 | +import random |
31 | 7 |
|
32 | 8 |
|
| 9 | +def main(): |
| 10 | + attempts = 1 # Initial count of attempts. Minimum is 1. |
| 11 | + print "How many numbers do you want?" |
| 12 | + # Declare variable to generate random number inside range. |
| 13 | + howMany = input("Ammount: ") |
| 14 | + if howMany == 1: |
| 15 | + print "Pick a number greater than 1!" |
| 16 | + main() # If the number is 1, return to main. |
| 17 | + |
| 18 | + else: # if the number is greater than 1, continue. |
| 19 | + print 'Guess the number between 1 and {}.'.format(howMany) |
| 20 | + randomNumber = random.randint(1, howMany) |
| 21 | + found = False # declare found as false. |
| 22 | + |
| 23 | + while not found: # while the user has not guessed the correct number. |
| 24 | + |
| 25 | + userGuess = input("Your guess: ") |
| 26 | + if userGuess == randomNumber: |
| 27 | + print "You have guessed the correct number! You used", attempts, "attempts." |
| 28 | + found = True # declare found as true which ends the program |
| 29 | + |
| 30 | + elif userGuess > randomNumber: # if the user is less than the generated number |
| 31 | + print ("Guess lower!") |
| 32 | + attempts = attempts + 1 # add one attempt to the counter |
| 33 | + else: |
| 34 | + print ("Guess higher!") |
| 35 | + attempts = attempts + 1 # add one attempt to the counter |
33 | 36 |
|
34 | 37 |
|
35 | 38 | if __name__ == "__main__": |
36 | | - main() |
| 39 | + main() |
0 commit comments