R B
R B

Reputation: 21

Print something outside of for loop for last iteration

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?

Upvotes: 2

Views: 68

Answers (4)

ukBaz
ukBaz

Reputation: 7984

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()

Upvotes: 1

Talha Tayyab
Talha Tayyab

Reputation: 27535

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.

Upvotes: 1

Ajay Pun Magar
Ajay Pun Magar

Reputation: 468

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

Upvotes: 1

Vaibhav lodha
Vaibhav lodha

Reputation: 46

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')

Upvotes: 1

Related Questions