0

When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?

The output should look like this

Hello Megan the four games avaliable are:
0   Mario Cart
1   Minecraft
2   Angry Birds
3   Grabd Theft Auto
What number game do you want? h 
Please choose a valid number 

What number game do you want? 23
Please choose a number between 0 and 3

What number game do you want? 1
You have chosen Minecraft

Instead, the output is

Hello the four games avaliable are:
0   Mario Cart
What number game do you want? 2
1   Minecraft
What number game do you want? h
Please enter a valid value

The code i am using is:

#Ask user what game they would like to play
def game () :
    global gametype,gamelist
    gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
    gamecount = 0
    print ("Hello the four games avaliable are:")
    while gamecount < 4:
        print (gamecount," ",gamelist[gamecount])
        gamecount = gamecount + 1


        try:
            gametype = int(input("What number game do you want? "))

            while gametype <0 or gametype >3:
                print (" Please enter a value between 0 and 3")

        except ValueError:
                print ("Please enter a valid value " )

                return gametype

game ()

I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.

SECOND TRY

I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.

#Ask user what game they would like to play
def game () :
    global gametype,gamelist
    gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
    gamecount = 0
    print ("Hello the four games avaliable are:")

    while gamecount < 4:
        print (gamecount," ",gamelist[gamecount])
        gamecount = gamecount + 1

    while True:
        try:
            gametype = int(input("What number game do you want? "))

            if 0 <= gametype <= 3 :
                return game
            print ("Please enter a value between 0 and 3 ")

        except ValueError:
                print ("Please enter whole number from 0 to 3 " )
                return game

game ()
  • 3
    Please fix the indentation in your code. The way you present it, it's not valid Python, because `try` and `except` are not on the same indentation level. – IonicSolutions Aug 04 '18 at 07:19
  • Also, the `while` loop will never terminate, but run indefinitely if the condition is fulfilled. – IonicSolutions Aug 04 '18 at 07:19
  • Last, can you please show us the exact error the Python interpreter shows? Usually, there will be a clear hint on what is wrong. – IonicSolutions Aug 04 '18 at 07:21
  • The problem is not in the code you show above, but in `yup.py` and it is exactly what the interpreter says: The variable `name` you are trying to print is not defined (has not been introduced and set to any value). – IonicSolutions Aug 04 '18 at 07:28
  • It looks like you need to review Python's rules on indenting code. Correct indentation is _vital_ in Python! – PM 2Ring Aug 04 '18 at 07:30
  • i fixed those errors but now everything is not printing –  Aug 04 '18 at 07:36
  • Check your indentation. I'm sure by tracing the program flow you can see where it goes wrong. You're almost there! – IonicSolutions Aug 04 '18 at 07:49
  • @IonicSolutions I have changed my indentations but i still don't know what to do –  Aug 04 '18 at 07:56
  • 1
    @michelle It looks like you're a bit lost. But I can tell that you're trying hard to make this work, so I'll post an answer shortly. In future, please post the _exact_ code that you're trying to run, and make sure the indentation is _identical_ to what's on your machine. And when you get an error message please include the full error message in your question, starting from the Traceback line. Put the error message into a code block to preserve the formatting. – PM 2Ring Aug 04 '18 at 07:58
  • You should take a look at Kevin's great question & answer: [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). Some of that code may be a bit advanced for you at this stage, but it's well worth studying and bookmarking that page for future reference. – PM 2Ring Aug 04 '18 at 08:09
  • BTW, you don't want `return game`. That returns the `game` function object itself. You need to return `gametype`, and you should _only_ do that when `gametype` is valid, so you shouldn't return it inside that `except ValueError` block. – PM 2Ring Aug 05 '18 at 10:10

1 Answers1

1

I think you want something like this:

gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]

def game(name):
    """ Ask user what game they would like to play """
    print ("Hello, {}, the four available games are:".format(name))
    for gamenum, gamename in enumerate(gamelist):
        print(gamenum, ":", gamename)

    while True:
        try:
            gamenum = int(input("What number game do you want? "))
            if 0 <= gamenum <= 3:
                return gamenum

            print("Please enter a value between 0 and 3")
        except ValueError:
            print ("Please enter a whole number from 0 to 3")

name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])    

demo output

What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds

The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.


If you have to print the list of games using a while loop then you can do it like this:

gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]

def game(name):
    """ Ask user what game they would like to play """
    print ("Hello, {}, the four available games are:".format(name))
    gamenum = 0
    while gamenum < len(gamelist):
        print(gamenum, ":", gamelist[gamenum])
        gamenum += 1

    while True:
        try:
            gamenum = int(input("What number game do you want? "))
            if 0 <= gamenum <= 3:
                return gamenum

            print("Please enter a value between 0 and 3")
        except ValueError:
            print ("Please enter a whole number from 0 to 3")

name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])    

I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • is there anyway to do it without the enumerate? –  Aug 04 '18 at 22:36
  • @michelle Sure! But using `enumerate` is the neat & Pythonic way to do it. You can also do it with `for gamenum in range(4):`. See if you can figure it out. You could also do it with a `while` loop, like you were trying to do before, but that's the messiest way. – PM 2Ring Aug 04 '18 at 23:23
  • I tried changing it, I have added it at the bottom of my question, would you be able to look at it. I think I need it in the while loop as a requirement –  Aug 04 '18 at 23:30
  • @michelle You have to be careful when coding to make sure you type keywords & variable names *exactly*. You need `while` to be all lower case. You use capital `W`, so here on Stack Overflow it gets printed in light blue instead of dark blue. – PM 2Ring Aug 04 '18 at 23:42
  • thank you, that made it work now but i believe there is a problem with my 'except ValueError' because when i put in a letter it prints ("Please enter a whole number from 0 to 3") but it does not reask the question like with the 'if' –  Aug 04 '18 at 23:53
  • @michelle Yeah. You've made a few other changes that messed things up. Try to make your new version closer to mine. I can't do much at the moment because I'm on my phone. – PM 2Ring Aug 04 '18 at 23:59
  • i have no idea how to do that, sorry i'm really new and i don't understand a lot but would you be able to tell me what to change or i can wait –  Aug 05 '18 at 00:16
  • @michelle You need to make your program the same as mine, except for the loop that prints the game numbers and names. Make sure you don't mess up the indentation. – PM 2Ring Aug 05 '18 at 00:23
  • @michelle I added a new version to my answer. – PM 2Ring Aug 05 '18 at 10:07