1

I'm learning Python and I'm lost atm :

from random import randint

x = 10

y = 4

hit = randint(1,100)

while x > 0:

    if hit >= 50:

        print "you hit for %d" % y
        x -= y

    elif hit < 50:

        print "you miss"  

What I'm tryng to do is get a loop going that every time runs a "new" if I hit or if I miss untill x = 0. Thanks.

3 Answers 3

2

If you want a different random number each time through the loop, put the random number generation inside the loop. Move hit = randint(1,100) between the while x > 0: and the if hit >= 50:.

Sign up to request clarification or add additional context in comments.

Comments

2

you have your x -=y only in one of the conditional branches, that means if hit < 50 x-=y will never get run, which will cause an infinite loop, you need to change it to:

while x > 0:
    hit = randint(1,100)

    if hit >= 50:
        print "you hit for %d" % y

    elif hit < 50:
        print "you miss"
    x -= y

you also had your randint outside of the loop, so hit would have always been the same value.
Looking at your code again, x seems to be hp, and the loop will end when hp is depleted, so your x-=y is fine in that case.

1 Comment

Thanks every one. Really helping me out here.
0

If hit is declared outside of the loop, the value will stay the same forever, either ending the program after three times around the loop or never ending. It must be this:

while x > 0:
    hit = random.randint(1,100)
    if hit >= 50:
        print "You hit for %d" % y
        x -= y
    elif hit < 50:
        print "You missed"

Although it is not necessary, because a random integer from 1 to 100 is either < or >= 50, it is good to get in the habit of defensive programming, so maybe put in this little else statement:

    else:
        print "Error, something is wrong"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.