Home > Back-end >  adding a loop to high and low game
adding a loop to high and low game

Time:01-23

#Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random

# declarations
num1 = (random.randint(0, 10))
num2 = (random.randint(0, 10))
guess = ""
# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
guess = input('-->')
if guess == 'h':
    if num1 < num2:
        print("you guessed it! the number is:", num2)
    else:
        print("Nice guess but the number is:", num2)
elif guess == 'l':
    if num1 > num2:
        print("you guessed it! the number is:", num2)
    else:
        print("Nice guess but the number is:", num2)
else:
    print("Not an exceptable entry")

I made this and it works but I want to create a loop so the user can play all they want. I am new to this ..any suggestions would be appreciated

CodePudding user response:

After copy paste your code in my IDE I realize you miss the conception for this code.

You should start this with the idea of breaking the loop if right, continue if wrong.

This isn't a good practice but I found a quick way to answer your need without refactoring your code:

Add you entire code (except the import of random module) inside

while True:

And add break control statement after each good answer.

I tested it and it's work but I recommend you to search for similar project to compare with your, it will be a good point for later in your adventure.

CodePudding user response:

Using functions here would be a good idea, I'd recommend putting your main code in a function called 'play' for example and also create a function which prompts the user if he wants to play again.

Then create a while loop which calls your 'play' function, and update the condition of your main loop after each 'play' with the prompt function.

This is how I have done it.

# Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random

# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")


def play():
    # declarations
    num1 = (random.randint(0, 10))
    num2 = (random.randint(0, 10))
    print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
    guess = input('-->')
    if guess == 'h':
        if num1 < num2:
            print("you guessed it! the number is:", num2)
        else:
            print("Nice guess but the number is:", num2)
    elif guess == 'l':
        if num1 > num2:
            print("you guessed it! the number is:", num2)
        else:
            print("Nice guess but the number is:", num2)
    else:
        print("Not an exceptable entry")


def promptAgain():
    print("Play again? y/n")
    response = input().lower()
    if response == 'n':
        return False
    elif response == 'y':
        return True
    else:
        print("Not an exceptable entry")
        return promptAgain()


again = True
while again:
    play()
    again = promptAgain()

CodePudding user response:

Since you only allow higher or lower input you need to ensure the same number is not randomly selected twice. I.e., if num1 is 8 then num2 should not be able to also be 8 (your current code doesn't prevent this).

Consider utilizing random.sample to achieve this:

"""Daniel Gardner's Higher/Lower Game."""
import random

MIN_RAND_VALUE = 0
MAX_RAND_VALUE = 10
GUESS_PROMPT = '--> '
HIGH_GUESS = 'h'
LOW_GUESS = 'l'


def get_yes_no_input(prompt: str) -> bool:
    """Returns True if the user enters yes."""
    allowed_responses = {'y', 'yes', 'n', 'no'}
    user_input = input(prompt).lower()
    while user_input not in allowed_responses:
        user_input = input(prompt).lower()
    return user_input[0] == 'y'


def higher_or_lower_game_loop() -> None:
    num1, num2 = random.sample(range(MIN_RAND_VALUE, MAX_RAND_VALUE   1), 2)
    print('The first number is', num1,
          'Enter h for higher or l for lower to guess the second number.')
    guess = input(GUESS_PROMPT)
    while guess not in {HIGH_GUESS, LOW_GUESS}:
        print('Not an exceptable entry, you must enter h or l')
        guess = input(GUESS_PROMPT)
    if guess == HIGH_GUESS:
        if num1 < num2:
            print('You guessed it! the number is:', num2)
        else:
            print('Nice guess but the number is:', num2)
    elif guess == LOW_GUESS:
        if num1 > num2:
            print('You guessed it! the number is:', num2)
        else:
            print('Nice guess but the number is:', num2)


def main() -> None:
    print('Welcome to my high/lower game.',
          'You will guess the second number in the game,',
          'is it higher or lower than the number presented?')
    while True:
        higher_or_lower_game_loop()
        play_again = get_yes_no_input('Play again? ')
        if not play_again:
            break
    print('Goodbye!')


if __name__ == '__main__':
    main()

Example Usage:

Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
The first number is 8 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 5
Play again? yes
The first number is 10 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 8
Play again? n
Goodbye!
  • Related