Home > Software engineering >  beginner python on looping back to the start of my simple number guessing game
beginner python on looping back to the start of my simple number guessing game

Time:11-18

This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock:

import random


Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))


def number_game():
    if guess == random_num:
        print(f"You guessed right, the number is confirmed to be {random_num}.")
    else:
        print(f"You guessed the wrong number. Try again.\n")


number_game()

I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to. I tried searching all my resources and am quite stuck on this beginner practice coding. Any help is appreciated.

What I wrote and tried is above... googling and stackoverflow just confused me more.

CodePudding user response:

Honestly, there are many ways to do what you want. But using your code as base, this is one possible solution.

import random


Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)



def number_game():
    guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
    if guess == random_num:
        print(f"You guessed right, the number is confirmed to be {random_num}.")
        return True
    else:
        print(f"You guessed the wrong number. Try again.\n")
        return False


while True:
    guessed_right = number_game()

    if guessed_right:
        quit()
    else:
        number_game()

CodePudding user response:

while True:
    number_game()

Replace the last line of your script with this!

  • Related