question regarding secret number python game - python

I'm wondering what´s happening with my code, because I want to print just in the end if we found the secret number, but I get it every time.
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
we should not be able to see it (print) unless we get the right result

If you try to simulate the code in your loop top to bottom, you will see that the final print line is always read at the end, because there's nothing stopping it from reaching that point. You are going to want to either wrap it around a condition (e.g. if/else):
if user_winner == True:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
You can also consider placing the print line under an already existent if statement that you wrote:
if guess_number == answer:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
elif ...
However, since Python reads it from top to bottom, you would also need to move the block of code you have handling the attempt_word variable.

The problem is that the congratulations part is not in an if statement and so prints every time a number is input. You can either move that up to the first if statement or leave it where it is but put it inside a new if statement.
First solution is you move the congratulations part up to where you first test to see if it's correct like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
Or for the second solution you test to see if you get the correct result a second time before printing congratulations like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
if guess_number == answer:
print("Congratulations!! You did it in " + str(attempts) + attempt_word)

Related

How to make random.randit get new number, every time the game starts again

i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)

how to congratulate player with using hint and without using it differently

i would like to know how to tell the computer to print different input for player using hint
and for someone who doesn't used it to congratulate them
import random
words = dict(
python = "type of snake",
honda = "type of car",
spanish = "type of language",)
word = list(words)
var = random.choice(word)
score = 0
chance = 5
x = list(var)
random.shuffle(x)
jumble = "".join(x)
print("the jumble word is :", jumble,)
while True:
guess = input(" this is my guess :")
if guess == "hint":
print(words[var])
if guess == var:
print("well done you only used ", score,"to guessed it ")
break
else:
print("try again")
score +=1
if score == chance:
print("better luck next time")
break
What about adding a boolean, say hintUsed, that keeps track of whether or not the user used a hint:
hintUsed = False
while True:
guess = input(" this is my guess :")
if guess == "hint":
hintUsed = True # change hintUsed to True !!
print(words[var])
And then, to congratulate:
if guess == var:
if hintUsed:
#print a message
else:
#print another message
break

Popping from a list & Subtracting from a Function (Hangman)

I've am having trouble with the last two specifications of this program.
1) Guesser initially gets 6 misses (7th strike and they are out). If they win that game, they play again, but with only 5 misses, etc. The game ends when they fail to guess the word in the specified number of guesses or until they win a game in which they have 0 misses.
- I've tried but I don't know how to have all of my numbers from the other functions reflect the new change. I would like to keep the option to replay so they can quit at anytime.
2) Before each guess display a list of letters that have not yet been guessed.
- I know this one is simpler and I should know it but I think I've fried my brain.
I've still have documentation to do so I apologize for any errors. Any cleanup is always appreciated. Thanks in advance.
import random
import string
word_list = ["no", "hi", "bee", "car", "seat", "bear", "see", "chip"]
available_letters = string.ascii_lowercase # pop guessed letter from here
used_letters = [] # Add it to here, and display avaiable_letters each time a letter is guessed.
missed_letters = ""
correct_letters = ""
secret_word = random.choice(word_list).lower()
def get_random(word_list):
secret_word = random.choice(word_list).lower()
return secret_word
def display_board(missed_letters, correct_letters, secret_word):
print("Current Score:")
for letter in missed_letters:
print(letter)
print()
blanks = '-' * len(secret_word)
for i in range(len(secret_word)):
if secret_word[i] in correct_letters:
blanks = blanks[:i] + secret_word[i] + blanks[i+1:]
for letter in blanks:
print(letter)
print()
def get_player_guess(guessed):
while True:
guess = input("Enter a letter: ") # try guess = input(blah blah).lower()
guess = guess.lower()
if len(guess) != 1:
print("1 Letter at a time!")
elif guess in guessed:
print("Whoops, you already guessed that one!")
elif guess not in "abcdefghijklomnopqrstuvwxyz":
print("Letters only please!")
else:
return guess
def replay_game():
replay = input("Do you want to play again? y or n ")
if replay == "y":
play_game(missed_letters, correct_letters, secret_word)
else:
print("Bye!")
def play_game(missed_letters, correct_letters, secret_word):
count = 0
chance = 7
game_over = False
print("Welcome To Hangman.")
while True:
display_board(missed_letters, correct_letters, secret_word)
guess = get_player_guess(missed_letters + correct_letters)
if guess in secret_word:
correct_letters = correct_letters + guess
done = True
for i in range(len(secret_word)):
if secret_word[i] not in correct_letters:
done = False
break
if done:
print("You win!")
game_over = True
else:
missed_letters = missed_letters + guess
count += 1
chance -= 1
if count == 1:
print("You've got " + str(count) + " Strike. You have " + str(chance) + " Chances left")
elif count > 1 and count < 6:
print("You've got " + str(count) + " Strikes. You have " + str(chance) + " Chances left")
elif count == 6 and chance == 1:
print("You've got " + str(count) + " Strikes. You have " + str(chance) + " Chance left")
if len(missed_letters) == 7:
display_board(missed_letters, correct_letters, secret_word)
print("Sorry! You've run out of guesses! The right word was " + secret_word + "!")
game_over = True
if game_over:
if replay_game():
missed_letters = ""
correct_letters = ""
secret_word = get_random(word_list)
else:
break
play_game(missed_letters, correct_letters, secret_word)
At the moment, you aren't changing the word when replay_game is called because the text after if replay_game at the end is never being called.
For the first problem, I would record the total number of chances for the game as an input variable into play_game and change replay_game to just return true or false and move the other code into play_game
def replay_game():
replay = input("Do you want to play again? y or n ")
# Changed to just return true or false depending on input.
if replay == "y":
return True
else:
print("Bye!")
return False
Then change the start of play_game to
def play_game(missed_letters, correct_letters, secret_word, total_chances=7):
count = 0
# chance is now variable
chance = total_chances
game_over = False
and at the end of play_game, replace:
if len(missed_letters) == 7:
with
if chance == 0:
and change the call to if game_over to
if game_over:
if replay_game():
missed_letters = ""
correct_letters = ""
secret_word = get_random(word_list)
play_game(missed_letters, correct_letters, secret_word, total_chances - 1)
else:
break
This will mean your code which was resetting the letters will get called now, and each restarted game starts with one less chance than the previous.
You'll have to add some handling for the case where they win with no misses allowed.
For the second problem, just add the following to display board:
print("Available letters:")
print(','.join(sorted(set(available_letters) - set(missed_letters) - set(correct_letters))))
This makes a set of each of the three groups of letters, and then takes away those already guessed, before displaying them in one line, alphabetically sorted and comma separated.
Regarding the function display_board I would clean the code a bit to substitute the '_' in blanks with the correct letter when it was correctly guessed:
for i in range(len(secret_word)):
if secret_word[i] in correct_letters:
blanks[i] = secret_word[i]
It looks cleaner and does less reassignments of elements in blanks.

User input Exit to break while loop

I'm doing an assignment for the computer to generate a random number and have the user input their guess. The problem is I'm supposed to give the user an option to input 'Exit' and it will break the While loop. What am I doing wrong? I'm running it and it says there's something wrong with the line guess = int(input("Guess a number from 1 to 9: "))
import random
num = random.randint(1,10)
tries = 1
guess = 0
guess = int(input("Guess a number from 1 to 9: "))
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess == str('Exit'):
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
The easiest solution is probably to create a function that gets the displayed message as an input and returns the user input after testing that it fulfils your criteria:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
You can call this from within your main program like
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
or
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")
You are trying the parse the string 'Exit' to an integer.
You can add a try/except around the casting line and handle invalid input.
import random
num = random.randint(1,9)
tries = 1
guess = 0
guess = input("Guess a number from 1 to 9: ")
try:
guess = int(guess) // try to cast the guess to a int
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
except ValueError:
if guess == str('Exit'):
print("Good bye")
else:
print("Invalid input")

Hangman with Arrays in Python 3.2

import random
GameWords = ['COMPUTER', 'PYTHON', 'RUBY', 'DELPHI', 'LAPTOP', 'IDEALS', 'PERL']
#Program will pick a word to use
word = random.randint(0,6)
ChosenWord = GameWords[word]
ChosenWord = list(ChosenWord)
#This will generate a playfield
playField = "_" * len(ChosenWord)
playField = list(playField)
#Array for bad guesses
BadGuess = "_" * len(ChosenWord) * 2
BadGuess = list(BadGuess)
print(" Bad Guesses", BadGuess)
print("\n Hidden Word ", playField, end = "")
#Get the number of letters in the word
WordLength = len(ChosenWord)
#Give two times the number of letters in a word for guessing.
NumChances = WordLength * 2
print("")
print("\n Number of Chances", NumChances)
print("\n This is number of letters in word", WordLength, "\n")
#Need a loop for the guess
flag = True
GoodCounter = 0
b = 0
while flag == True:
#Input a player's guess into two diffrent arrays
#Array for bad guess one for good guess
PlayerGuess = input("\n Guess a letter: ")
PlayerGuess = PlayerGuess.upper()
#Player cannot enter more than one letter
if len(PlayerGuess) != 1:
print("Please enter a single letter.")
#If the player do not enter a letter
elif PlayerGuess not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print("Please enter a LETTER.")
#If the player guess wrong
# b is used for indexing
elif PlayerGuess not in ChosenWord:
for b in range(0):
if ChosenWord[b] != PlayerGuess:
BadGuess[b] = PlayerGuess
b = b + 1
print("this is b", b)
print("You have guessed wrong")
print("Letters you have missed", BadGuess)
NumChances = NumChances - 1
print("You have", NumChances, "left!")
if NumChances == 0:
flag = False
print("You have lost!")
else:
flag = True
#If the player guess correctly
# i is used for indexing
elif PlayerGuess in ChosenWord:
for i in range(WordLength):
if ChosenWord[i] == PlayerGuess:
playField[i] = PlayerGuess
print("\n Letters you have HIT! ", playField, end = "")
print("You have guessed correctly")
GoodCounter = GoodCounter + 1
if GoodCounter >= WordLength:
flag = False
print("You have won!")
else:
flag = True
Now I have a new problem my BadGuess array will not display the letters on the play field. I tried to use the same code I used for the playField array but it did not work.
What do I need to do to get the bad guesses to be stored in the BadGuess array and display on the play field?
I don't know if this is what you're asking, but if you want all the bad guesses stored in the array, you have to increment the bad variable.
If you want to replace the blanks, there are many ways to do so, but I'd create a loop that tests to see if a letter is the same as in the word at a given index, and then replace it in the array if it does.
Something like:
for i in range(WordLength):
if ChosenWord[i] == playerGuess:
playField[i] = playerGuess
Hope this helps.

Categories

Resources