python-3.x 打印最后一次迭代的for循环外的内容

ne5o7dgx  于 2023-03-13  发布在  Python
关注(0)|答案(4)|浏览(132)

我开始做一个数字猜谜游戏。下面是我写的代码:

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

问题是对于最后一次迭代,我得到了for循环内部满足的条件的print,以及循环外部的print。当然,如果这是最后一次猜测,我不想得到'Too high,take another guess'或类似的结果。
我怎么能在最后一次迭代中只打印“该死的,你是一个读心者吗?”或者“你错了”?

dffbzjpn

dffbzjpn1#

你可以把猜测的次数存储在一个变量中,比如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')
nnsrf1az

nnsrf1az2#

这将是更好的,如果你有一行打印游戏规则,我不知道有多少尝试,你想给予。你的程序计数从1 ...... 6,它只是6步,所以我让它循环7次,因为这

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
olhwl3o2

olhwl3o23#

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

这里c是一个计数器,用来查看是否达到了number_of_trials。2如果是最后一次猜测,它将有助于不显示“太高,再猜一次”或类似的信息。

vcudknz3

vcudknz34#

代码中的主循环将被重复 while 将有另一个猜测。
您还希望只在有另一个猜测将要发生时打印出“太高”或“太低”消息。
另一种方法是测试正确答案或猜测次数过多,并在打印这些消息之前更改another_guess的状态。
例如:

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

如果你有野心把这个游戏,并添加图形用户界面,它可能是有益的分离出用户界面,游戏状态,游戏逻辑.

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

相关问题