Print something outside of for loop for last iteration - python

I started to make a number guessing game. Here is the code I wrote:
import random
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, 7):
Guess = int(input())
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
The problem is that for the last iteration I get the print for the condition that is met inside of the for loop, as well as the print outside of the loop. Of course I don't want the print 'Too high, take another guess' or something like that if it is the last guess.
How can I only print 'Damnn are you a mindreader' or 'You are wrong' for the last iteration?

You can store number of guesses in a var like N.
N = 7
for Guesstaken in range(1, N):
Guess = int(input())
if Guesstaken == N - 1:
break
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')

It would be better if you had a line to print rules of game, I wasn't sure how many tries you wanted to give. your program counted from 1.....6 and it was just 6 steps so i made it loop 7 times as this
for Guesstaken in range(7):
Guess = int(input())
if Guess < randomnumber and Guesstaken<6:
print('Too low, take another guess!')
elif Guess > randomnumber and Guesstaken<6:
print('Too high, take another guess!')
else:
break

import random
number_of_trials=6
c=0
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, number_of_trials+1):
c+=1
Guess = int(input())
if Guess < randomnumber and c!=number_of_trials:
print('Too low, take another guess!')
elif Guess > randomnumber and c!=number_of_trials:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
here c is a counter to see if the number_of_trials are reached. It will help in not displaying 'Too high, take another guess' or something like that if it is the last guess.

The main loop in your code is to be repeated while there is going to be another guess.
You also want to only print out the "too high" or "too low" messages if there is another guess going to happen.
An alternative is to test for a correct answer or too many guesses and change the state of another_guess before those messages are printed.
For example:
import random
NamePlayer = input('Hello what is your name? ')
print(f'Well, {NamePlayer} I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
another_guess = True
guesses = []
while another_guess:
Guess = int(input())
guesses.append(Guess)
if Guess == randomnumber:
another_guess = False
if len(guesses) == 6:
another_guess = False
if another_guess and Guess < randomnumber:
print('Too low, take another guess!')
elif another_guess and Guess > randomnumber:
print('Too high, take another guess!')
if Guess == randomnumber:
print('Damnn, are you a mind reader, ' + NamePlayer)
else:
print('You are wrong')
If you had ambition to take this game and add graphical user interface it might be beneficial to separate out the UI, game state, game logic.
For example:
"""Guess a number game"""
from dataclasses import dataclass, field
from enum import IntEnum
import random
def main():
cli = UI()
player_name = cli.ask_name()
game = Game(Scoreboard(), cli, player_name)
game.play()
class GuessState(IntEnum):
"""Possible states of guess"""
LOW = -1
CORRECT = 0
HIGH = 1
class UI:
"""Handle UI interaction to make it easy to move to different UI"""
def ask_name(self):
"""Ask the players name"""
return input("Hello, what is your name? ")
def ask_guess(self, max_choice):
"""
Ask for guess value. Check input is a valid value before returning
"""
while True:
try:
choice = int(input("Enter guess: "))
if 0 < choice < max_choice + 1:
return choice
print(f"Please enter a guess between 1 and {max_choice}")
except ValueError:
print("You entered something other than a number")
def display_welcome(self, player_name, max_choice, max_guesses):
"""Welcome message and rules"""
print(f"Welcome, {player_name}")
print(f"I am thinking of a number between 1 and {max_choice}.")
print(f"Can you guess it within {max_guesses} guesses?")
def display_turn_result(self, value, result):
"""Display the guessed value and if they are too high or low"""
if result == GuessState.LOW:
print(f"{value} is lower than the number I am thinking of!")
elif result == GuessState.HIGH:
print(f"{value} is higher than the number I am thinking of!")
def display_goodbye(self, player_name, scoreboard):
"""Game over message"""
if scoreboard.any_correct_guesses():
print(f"{player_name} are you a mindreader!")
else:
print(f"You didn't get the number, {player_name}. Please try again")
#dataclass
class Scoreboard:
"""Keep track of the guesses and if active for more guesses"""
guesses: list = field(default_factory=list)
game_active: bool = True
def add_guess(self, choice, state):
"""Add the value and state of a guess"""
self.guesses.append((choice, state))
def get_last_guess(self):
"""Return the value and state of the last guess"""
return self.guesses[-1]
def get_guess_count(self):
"""Return how many guess have been had"""
return len(self.guesses)
def any_correct_guesses(self):
"""Return True if there has been a correct guess"""
return GuessState.CORRECT in [state[1] for state in self.guesses]
def to_display(self, ui: UI):
"""Display the turn result in the UI"""
guess_value, guess_state = self.get_last_guess()
ui.display_turn_result(guess_value, guess_state)
#dataclass
class Game:
"""Game logic"""
scoreboard: Scoreboard
ui: UI
player_name: str
max_rounds: int = 6
max_number: int = 20
def play(self):
"""Play the game"""
self.ui.display_welcome(self.player_name, self.max_number, self.max_rounds)
target_number = random.randint(1, self.max_number)
print("For testing here is the target number:", target_number)
while self.scoreboard.game_active:
self.turn(target_number)
if self.scoreboard.game_active:
self.scoreboard.to_display(self.ui)
self.ui.display_goodbye(self.player_name, self.scoreboard)
def turn(self, target_number):
"""Play a turn"""
choice = self.ui.ask_guess(self.max_number)
if choice == target_number:
self.scoreboard.add_guess(choice, GuessState(0))
self.scoreboard.game_active = False
elif choice < target_number:
self.scoreboard.add_guess(choice, GuessState(-1))
elif choice > target_number:
self.scoreboard.add_guess(choice, GuessState(1))
if self.scoreboard.get_guess_count() == 6:
self.scoreboard.game_active = False
if __name__ == "__main__":
main()

Related

Function and keyword argument

Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return

Python Program Loop

Could someone look at my code and see why I'm getting a syntax error on line 41, please?''' This is program that gives the user the option of playing a number guessing
game where they have the option of unlimited guesses between 1 and 100 or only
5 guesses.
'''
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
Set the Loop
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
count = count+1
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
count = count+1
elif (guess == x):
print ("Congratulations, you guessed the number in", count,
"attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:")
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!)
if (guess == x):
print ("You won!")
else:
print ("You lost!")
elif (guess == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
After correcting some errors it looks like this:
import random
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
count=0
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
count = count+1
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
print(f"Congratulations, you guessed the number in {count} attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:"))
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!")
elif (gameCode == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")

Why does one of my functions just loop back when not meant to?

I am trying to create a simple code guessing game where the user can choose the minimum and maximum number the randomly generated code can be. The user has to try and guess the code to win. When I run my code, the get_range() function works and then it proceeds to the get_guess() function as it should. But when the user enters his/her input for their guess, the code loops back to the start of the get_range() function. Please can anyone help? Thanks in advance. Code:
import random
import string
print("Welcome to Code Crunchers!")
def get_range():
Min = str(input("Enter the minimum number that the code can be: "))
Max = str(input("Enter the maximum number that the code can be: "))
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min != True or Check_Max != True:
print("Input must only contain integers!")
get_range()
elif Min == Max:
print("Minimum and maximum number must not be equivalent!")
get_range()
elif Min > Max:
print("Maximum number must be greater than minimum number!")
get_range()
else:
Random_Number = random.randrange(int(Min), int(Max))
get_guess()
return Random_Number
def get_guess():
Guess = str(input("Enter your guess: "))
Check_Guess = Guess.isdigit()
if Check_Guess != True:
print("Input must only contain integers!")
get_guess()
else:
validate()
return Guess
def validate():
Random_Number = get_range()
Tries = locals()
Guess = get_guess()
Length = len(str(Random_Number))
Digits_Correct = 0
if Guess == Random_Number:
print("Well done! You guessed the number in", Tries, " tries!")
else:
Digits = ["?"] * Length
Tries += 1
for i in range(0, int(Length)):
if Guess[i] == Random_Number[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("Not quite! You got", Digits_Correct, " digits correct.")
print(Digits)
get_guess()
elif Digits_Correct == 0:
print("None of your digits match!")
get_guess()
def play_again():
Choice = input("Do you want to play again (y/n)?")
if Choice != "y" or Choice != "n" or Choice != "Y" or Choice != "N":
print("Please choose a valid option!")
play_again()
elif Choice == "y" or Choice == "Y":
get_range()
elif Choice == "n" or Choice == "N":
exit()
get_range()
Because you're re-calling get_range() in validate():
def validate():
Random_Number = get_range() # <-- Here
...
You might be able to solve this with:
def validate():
Random_Number = random.randrange(int(Min), int(Max))
...
But overall, that will depend on the direction of your code. Hope that helps!
Take a look at this code:
def get_range():
...
else:
...
get_guess()
return Random_Number
def get_guess():
...
else:
validate()
return Guess
def validate():
Random_Number = get_range()
Tries = locals()
Guess = get_guess()
...
Suppose you're in get_guess and get to the else close, so you call validate. Here's what happens:
get_guess calls validate
validate immediately calls get_range
get_range calls get_guess
now we're back in get_guess, see (1)
So your code enters infinite indirect recursion.
Notice how it'll never get past Random_Number = get_range() in validate, and you're calling get_guess in both get_range and validate.
So, before returning the random number to Random_Number = get_range(), get_range will try to get_guess and immediately discard its return value (that's what get_guess() does). Suppose that get_range eventually returns. Now you'll call Guess = get_guess() again, thus asking the user to guess twice. I think there's a logic flaw here.

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...

How to go about repeating or ending a function by a simple yes or no answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")

Categories

Resources