0
votes

Program that asks the user to guess generated number between 1 and 9. If player guessed too low, too high or equal there will be a message saying so. Program only finish when player types 'exit'.

I've created three functions.

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

It prints forever your guess is too low..

1
You never ask for another player_input - Nick
What have you already tried, to debug this? - Basya
i ask for player input in function - Luismaia1994
@Luismaia1994, ask for user input inside loop, because you need to keep on asking. - Austin
Print cpu_guess to know what randomly generated number is. - Austin

1 Answers

1
votes

As already mentioned in the comments:

  • Move the player guess inside the while loop.
  • I would suggest a while True loop with a call to exit() on typing 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())

A run might look like

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)