Skip to content

improved code for guessing_game.py #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions guessing_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

def recognize_speech_from_mic(recognizer, microphone):
"""Transcribe speech from recorded from `microphone`.

Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
Expand Down Expand Up @@ -66,11 +65,7 @@ def recognize_speech_from_mic(recognizer, microphone):
word = random.choice(WORDS)

# format the instructions string
instructions = (
"I'm thinking of one of these words:\n"
"{words}\n"
"You have {n} tries to guess which one.\n"
).format(words=', '.join(WORDS), n=NUM_GUESSES)
instructions = (f"I'm thinking of one of these words:\n{', '.join(WORDS)}\nYou have {NUM_GUESSES} tries to guess which one.\n")

# show instructions and wait 3 seconds before starting the game
print(instructions)
Expand All @@ -86,7 +81,7 @@ def recognize_speech_from_mic(recognizer, microphone):
# re-prompt the user to say their guess again. Do this up
# to PROMPT_LIMIT times
for j in range(PROMPT_LIMIT):
print('Guess {}. Speak!'.format(i+1))
print(f'Guess {i+1}. Speak!')
guess = recognize_speech_from_mic(recognizer, microphone)
if guess["transcription"]:
break
Expand All @@ -96,11 +91,11 @@ def recognize_speech_from_mic(recognizer, microphone):

# if there was an error, stop the game
if guess["error"]:
print("ERROR: {}".format(guess["error"]))
print(f"ERROR: {guess['error']}")
break

# show the user the transcription
print("You said: {}".format(guess["transcription"]))
print(f"You said: {guess['transcription']}")

# determine if guess is correct and if any attempts remain
guess_is_correct = guess["transcription"].lower() == word.lower()
Expand All @@ -110,10 +105,10 @@ def recognize_speech_from_mic(recognizer, microphone):
# if not, repeat the loop if user has more attempts
# if no attempts left, the user loses the game
if guess_is_correct:
print("Correct! You win!".format(word))
print("Correct! You win!")
break
elif user_has_more_attempts:
print("Incorrect. Try again.\n")
else:
print("Sorry, you lose!\nI was thinking of '{}'.".format(word))
print(f"Sorry, you lose!\nI was thinking of '{word}'.")
break