3
\$\begingroup\$

What would make it better? This is my first Python project. Do help in making it better, for me to learn something new.

secret="12345"
guess=""
count=0
limit=3
limited=False
while guess!=secret and not(limited):
 if count<limit: 
 guess=input("Enter guess: ")
 count +=1
 else:
 limit=True
 
if limited:
 print("Out of guesses, You Lose!")
else:
 print("You got it!")
 
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 19, 2022 at 17:25
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

So far, I think your initial approach is good. Your naming is clear and the code is pretty obvious in what it's trying to accomplish. Nice work!

Rethinking while

I think the while loop can actually be reduced to a for/else, because you are looping until a conditional is reached and marking a flag. So I'd do:

# iterate over the range of guesses
for _ in range(limit):
 guess = input('Enter guess: ')
 if guess == secret:
 message = "You got it!"
 break
else:
 message = "Out of guesses, you lose!"
print(message)

Where the else here will only trigger if the loop didn't exit early:

# breaks early, no else fired
for i in range(3):
 break
else:
 print('finished')
# loop completes, else fires
for i in range(3):
 continue
else:
 print('finished')
finished

Style Items

It is good to include whitespace in between operators for assignment and comparison:

# go from this
secret="12345"
guess!=secret
count +=1
# to this
secret = "12345"
guess != secret
count += 1

The not keyword isn't a function and doesn't need parentheses:

not limited

Making code reusable

Right now, you have a hard-coded secret. This is sufficient for getting your program running, but what if you want a new game to have a new secret? Let's create one on the fly using the random module:

import random
from string import digits # imports "0123456789" as a string
def play_game(secret):
 for _ in range(limit):
 guess = input('Enter guess: ')
 
 if guess == secret:
 message = "You got it!"
 break
 else:
 message = "Out of guesses, you lose!"
 
 print(message)
# the 5 here is the length of the secret
secret = "".join(random.sample(digits, 5))
play_game(secret)

Now, the game should generate new secrets every time you play. The only new parameter we have is how long the secret is, which you can add a new prompt for:

# a user will input digits 0-9 ideally
# we can catch this by raising an error if they don't
try:
 secret_length = int(input("How many digits should the secret have: "))
except ValueError:
 # You can loop or raise, up to you on what you want the behavior to do
 # but an error message is always helpful
 raise ValueError("You need to provide a number!")

Wrapping up in a __main__ block

The if __name__ == "__main__" statement is something you'll see a lot of as you see more python programs out in the wild. Basically it is checking to see if the script is being run as the main program, if it is, it executes whatever is in the body of the if. This is called a guard, and can help when code is designed to be both imported and run as standalone.

import random
from string import digits # imports "0123456789" as a string
def play_game(secret):
 for _ in range(limit):
 guess = input('Enter guess: ')
 
 if guess == secret:
 message = "You got it!"
 break
 else:
 message = "Out of guesses, you lose!"
 
 print(message)
if __name__ == "__main__":
 try:
 secret_length = int(input("How many digits should the secret have: "))
 except ValueError:
 raise ValueError("You need to provide a number!") 
 secret = "".join(random.sample(digits, secret_length))
 play_game(secret)

Last, it might be helpful to add a main method so all of these functions aren't hanging around in global namespace. And returning the result of the game might make it more clear as to what is going on.

import random
from string import digits # imports "0123456789" as a string
def play_game(secret):
 for _ in range(limit):
 guess = input('Enter guess: ')
 
 if guess == secret:
 message = "You got it!"
 break
 else:
 message = "Out of guesses, you lose!"
 
 return message
def main():
 try:
 secret_length = int(input("How many digits should the secret have: "))
 except ValueError:
 raise ValueError("You need to provide a number!") 
 secret = "".join(random.sample(digits, secret_length))
 game_result = play_game(secret)
 
 print(game_result)
if __name__ == "__main__":
 main()

This has the added benefit of being easy to loop if you want to play multiple games

if __name__ == "__main__":
 keep_playing = 'y'
 while keep_playing == 'y':
 main()
 
 keep_playing = input("Continue? (y/n) ").lower()

Docstrings

Let's add some documentation to our code. You can add docstrings to both your functions and the module.

# Up at the top of the file, a module-level docstring
"""Play a game of 'Guess the Secret!'
The secret is randomly generated and consists of an N-length string
of digits. You are prompted to pick the secret length
If you run out of guesses you lose, but guess it right and you win
"""
import random
from string import digits
 
def play_game(secret):
 """Plays the game with the secret provided as an argument.
 Secret can be any string
 Returns the result of the game as a message to the player
 """
 for _ in range(limit):
 guess = input('Enter guess: ')
 if guess == secret:
 message = "You got it!"
 break
 else:
 message = "Out of guesses, you lose!"
 return message
~rest of code~
answered Apr 19, 2022 at 17:52
\$\endgroup\$
1
\$\begingroup\$

This is something small, but instead of secret="12345" you can use the random module to pick a different number each time:

import random
secret = random.randint(0,100) #or 0-whatever number you want
Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
answered Apr 19, 2022 at 19:37
\$\endgroup\$
1
  • \$\begingroup\$ convert the number to a string \$\endgroup\$ Commented Apr 20, 2022 at 18:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.