Home > OS >  How can I generate new random numbers each time in my while loop in Python for a number game?
How can I generate new random numbers each time in my while loop in Python for a number game?

Time:12-28

I've created a number game where it asks the user if they want to play again and then the loop continues. My program uses import random but I want to know how I'd generate new random numbers without having to make variables each time. (I'm a beginner and I don't know what solution to use pls help)

My code works for the most part it's just that when the loop restarts the same number from the last playthrough repeats so the player ends up getting the same results. Here's my code:

`

import random
random_number_one = random.randint (0, 100)

username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}!  Would you like to play a game? (Type 'Yes/No') ".format(username))

while True:
  if start_game == 'Yes' or start_game == 'yes' :
    print("Let's begin!")
    print(random_number_one)
    user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
    if user_guess == 'H' or user_guess == 'h' :
        print("You guessed higher. Let's see: ")
        import random
        random_number_two = random.randint (0, 100)
        print(random_number_two)
        if random_number_two > random_number_one :
          print("You are correct! It was higher!")
          play_again_h = input("Would you like to play again? ('Yes'/'No') ")
          if play_again_h == 'Yes' or play_again_h == 'yes' :
            continue
          else:
            break 
        else:
          play_again = input("You were wrong, it was lower. Would you like to play again? ('Yes'/'No')  ")
          if play_again == 'Yes' or play_again == 'yes' :
            continue
          else:
            break
           
    elif user_guess == 'L' or user_guess == 'l':
      print("You guessed lower. Let's see: ")
      print(random_number_two)
      if random_number_two < random_number_one :
        print("You are correct! It was lower!")
        play_again_l = input("Would you like to play again? ('Yes'/'No') ")
        if play_again_l == 'Yes' or play_again_l == 'yes' :
         continue
        else:
         break
      else:
        play_again_2 = input("You were wrong, it was higher. Would you like to play again? ('Yes'/'No')  ")
        if play_again_2 == 'Yes' or play_again_2 == 'yes' :
          continue
        else:
          break
    else:
       print("Invalid response. You Lose.")
       break

  elif start_game == 'No' or start_game == 'no':
    print("Okay, maybe next time.")
    break
  else:
    print("Invalid response. You Lose.")
    break




`

CodePudding user response:

You have to initialize the random number generator with a seed. See here: https://stackoverflow.com/a/22639752/11492317 and also: https://stackoverflow.com/a/27276198/11492317

(You wrote, you're a beginner, so I give you some hints for cut a few things short...)

import random
import time


def get_random(exclude: int = None):
    next_random = exclude
    while next_random is exclude:
        next_random = random.randint(0, 100)
    return next_random


random.seed(time.time())
username = input("Greetings, what is your name? ")
start_game = None
while start_game is None:
    start_game = input("Welcome to the number game, {0}!  Would you like to play a game? (Type 'Yes'/'No') ".format(username))
    if start_game.lower() in ("yes", "y", ""):
        print("Let's begin!")
        number_for_guess = get_random()
        running = True
    elif start_game.lower() == "no":
        print("Ok, bye!")
        running = False
    else:
        start_game = None

while running:
    print(number_for_guess)
    next_number = get_random(exclude=number_for_guess)
    user_guess = ""
    while user_guess.lower() not in list("lh"):
        user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
    if user_guess.lower() == "h":
        print("You guessed higher. Let's see: ")
        print(next_number)
        if next_number > number_for_guess:
            print("You are correct! It was higher!")
        else:
            print("You were wrong, it was lower.", end=" ")
    else:
        print("You guessed lower. Let's see: ")
        print(next_number)
        if next_number < number_for_guess:
            print("You are correct! It was lower!")
        else:
            print("You were wrong, it was higher.", end=" ")
    play_again = "-"
    while play_again.lower() not in ("yes", "y", "", "no"):
        play_again = input("Would you like to play again? ('Yes'/'No') ")
        if play_again.lower() == "no":
            running = False
print("Well played, bye!")

CodePudding user response:

One solution is to store the new random number being generated in a list and each time when you call random function, check if the output i.e. newly generated number is in the list or not. If it's not, you can continue or else run the random function again.

Please note that you have to put the below line in a loop and break when you have got the new random number-

random_number_two = random.randint (0, 100)

So the code will look like this-

while True:
    random_number_two = random.randint (0, 100)
    if random_number_two not in check_list:
         check_list.append(random_number_two)
         break

Please define empty check_list above in the program. Note that this will slow your execution and you will have to reinitialize the check_list after the player has played 100 times.

  • Related