Моя программа не останавливается и возвращает тот же ответ - PullRequest
0 голосов
/ 19 мая 2019

Программа, которая просит пользователя угадать сгенерированное число от 1 до 9. Если игрок угадал слишком низкое, слишком высокое или равное, появится сообщение об этом.Программа завершается только тогда, когда игрок набирает «выход».

Я создал три функции.

import random

#function that creates a random number in between 1 and 9 inclusive
def number_generation():
  computer_number=random.randint(1,9)
  return computer_number
print(number_generation())

#function that asks the player to input number between 1 and 9
def player_number():
  player_num=input('Digit your guess between 1 and 9\n')
  return player_num

def guessing_game():
  w_answers=0
  r_answers=0
  cpu_guess=int(number_generation())
  player_guess=player_number()
  while player_guess!='exit':
    if int(player_guess)>cpu_guess:
      print('You have guessed to high')
      w_answers+=1
    elif int(player_guess)<cpu_guess:
      print('You have guessed to low')
      w_answers+=1
    else:
      print('You have guessed the correct number')
      r_answers+=1
  return w_answers,r_answers
print(guessing_game())

Он печатает всегда, ваше предположение слишком низкое ..

1 Ответ

1 голос
/ 19 мая 2019

Как уже упоминалось в комментариях:

  • Переместите предположение игрока в цикл while.
  • Я бы предложил while True цикл с вызовом exit() при наборе exit
import random

#function that creates a random number in between 1 and 9 inclusive
def number_generation():
    return random.randint(1,9)

#function that asks the player to input number between 1 and 9
def player_number():
    player_num=input('Digit your guess between 1 and 9\n')
    return player_num

def guessing_game():
    w_answers=0
    r_answers=0

    #CPU guess outside the loop
    cpu_guess = int(number_generation())

    #While true loop
    while True:
        #Make the player guess inside
        player_guess = player_number()

        #If exit is typed, exit
        if player_guess.lower() == 'exit':
            break
        #Else compare the guesses
        if int(player_guess)>cpu_guess:
            print('You have guessed to high')
            w_answers+=1
        elif int(player_guess)<cpu_guess:
            print('You have guessed to low')
            w_answers+=1
        else:
            print('You have guessed the correct number')
            r_answers+=1
    return w_answers,r_answers

print(guessing_game())

Пробег может выглядеть как

Digit your guess between 1 and 9
4
You have guessed the correct number
Digit your guess between 1 and 9
2
You have guessed to low
Digit your guess between 1 and 9
6
You have guessed to high
Digit your guess between 1 and 9
8
You have guessed to high
Digit your guess between 1 and 9
exit
(3, 1)
...