Nellington
Nellington

Reputation: 221

Python Dice Script Failing

I'm a Python newbie and I've run into trouble with a script. The point of the script is to create a dice that rolls a random number between 1 and 6. The script looks like this:

import random
while True:
    roll = input("Wanna roll? y/n: ").strip().lower()
    if roll == "y":
        dice = random.randint(1,6)
        print(dice)
    else:
        again = input("How about now? y/n: ").strip().lower()
        if again == "y":
            dice = random.randint(1,6)
            print(dice)
        else:
            print(again)

So that's the code. Ideally, what I want to happen is for Python to ask "Wanna roll?" and, if the user inputs "y", Python should return a random number between 1 and 6. This bit works fine.

If, however, the user types "n", I want Python to ask "How about now?" If the user types "y", then I want Python to return a random number between 1 and 6. This bit works fine as well.

Where I run into problems is when the user types "n" for the question "Wanna roll?" AND also types "n" for the second question "How about now?" The program SHOULD just keep asking the user "How about now?" over and over and over again until he eventually cracks and types "y" (at which point Python gives him a random number between 1 and 6). However, what happens is that Python returns this:

n
How about now? y/n: 

So it's printing the user's answer ("n") as well as asking the question again.

I can't figure out how to get Python to re-ask the question "How about now?" without also giving the answer the user input.

Apologies if this is an obvious question and/or if the formatting is incorrect/unclear. I've only been at this for a few weeks.

Thanks in advance!

Edit: The expected behaviour of the script is like this:

"Wanna roll? y/n: "

"How about now? y/n: "

"How about now? y/n: "

"How about now? y/n: "

and so on until the user answers the question "How about now?" with a "y" instead of an "n", at which point Python should return a number between 1 and 6 and then ask if the user wants to roll again.

EDIT 2: There was a mistake in the code. I put .script() when I meant to type .strip() - Sorry about that. This isn't the source of my problem because I did get it right when I wrote the script originally. Sorry :-(

Upvotes: 2

Views: 90

Answers (1)

asongtoruin
asongtoruin

Reputation: 10359

How about this?

import random
while True:
    roll = input("Wanna roll? y/n: ").strip().lower()
    while roll != "y":
        roll = input("How about now? y/n: ").strip().lower()

    dice = random.randint(1,6)
    print(dice)

It'll keep asking the user for an input until they reply y.

Upvotes: 1

Related Questions