TheAlmanac
TheAlmanac

Reputation: 19

I have a while loop for a game that won't work for some reason

I am having trouble with making this while loop work, any help/advice would be much appreciated.

here's the loop (its not the full program):

import random

while your_health or enemy_health >= 10:
    print("He is still attacking you.")
    print("you may either:"
          "a-dodge"
          "b-attack back")
    fight_choice_1_1 = input("What do you do?")

    if fight_choice_1_1 == "a":
        d20_1_1 = random.randint(1, 20)
        if d20_1_1 >= 10:
            print("you dodge the attack")
        elif d20_1_1 <= 10:
            your_health -= knife_damage
            print("you get hit")
            if your_health <= 0:
                print("you lose. :(")
            elif enemy_health <= 0:
                print("you win!")

    if fight_choice_1_1 == "b":
        d20_1_1 = random.randint(1, 20)
        if d20_1_1 >= 10:
            print("you get out of the way and hit him")
            enemy_health -= sword_damage
        elif d20_1_1 <= 10:
            print("he hits you, but you get a hit in too")
            your_health -= knife_damage
            enemy_health -= sword_damage
            print("you get hit")
            if your_health <= 0:
                print("you lose. :(")
            elif enemy_health <= 0:
                print("you win!")

Upvotes: 1

Views: 163

Answers (1)

paxdiablo
paxdiablo

Reputation: 881463

Rather than:

while your_health or enemy_health >= 10:

I think you mean:

while your_health >= 10 or enemy_health >= 10:

What you have is proper English as in "while (your health or enemy health) is greater than ten" but the syntax of computer languages is a little more strict.

To the computer, that means "while (your health) or (enemy health is greater than ten)" and, in the context of a truth value, many languages will simply treat a non-zero value as true. Python does follow that convention.

From 5.10 Boolean operations of the online Python docs:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

(my bold). So the statement:

while your_health or enemy_health >= 10:

is effectively (assuming that it's numeric and you never let it drop below zero in your code, reasonable assumptions given its intended purpose):

while (your_health > 0) or (enemy_health >= 10):

In other words, the loop will continue as long as your player has any health, rather than ten or more health points.

Upvotes: 9

Related Questions