简体   繁体   中英

Trying in Python to get a loop running with several if statments

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.

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.

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: .

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM