Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python - "if" statement not moving to the "else" clause

I'm writing a function for a small game in which a list of jobs is populated each turn. The jobs themselves are objects with a route, time, and pay attribute.

I want the list to be 5 items total and randomly populated by picking from a list of routes and pay grades.

I have a for loop to iterate 5 times, and I'm wanting the pay grade selected to be 5 only if a certain two routes are selected. Otherwise, the pay grades will be a random number between 1 and 4.

When I set the pay grade to 5 in the IF clause, it never makes it to the else clause even if the conditions of the IF are not true. I'm not sure what I'm doing wrong here.

for pick in range(5):
    job = random.choice(random_routes)
    if job == 'Military Base' or 'Raiders':
        pay_key = 5
    else:
        pay_key = random.randint(1, 4)
    pay = pay_grades[pay_key]

    job_postings.append(Job(job, routes[job], pay))

printing the first index attributes from the new job_postings list always returns level 5 pay numbers even if the route picked was not Military Base or Raiders.

Here are the route and pay dictionaries:

routes = {'Boneyard': 5, 'Brotherhood': 6, 'Cathedral': 6, 'Junktown': 4,
          'Military Base': 14, 'Necropolis': 5, 'Raiders': 10, 'Shady Sands': 11}

pay_grades = {
    1: random.randrange(200, 401, 50),
    2: random.randrange(300, 501, 50),
    3: random.randrange(400, 601, 50),
    4: random.randrange(500, 701, 50),
    5: random.randrange(900, 1600, 50),
}
question from:https://stackoverflow.com/questions/65874741/if-statement-not-moving-to-the-else-clause

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem lies on this line:

if job == 'Military Base' or 'Raiders':

The == operator takes precedence over the or operator, which means it's evaluating the same as,

if (job == 'Military Base') or ('Raiders'):

Any non-empty string evaluates to true (compare not '' and not 'abc' in the REPL) and therefore 'Raiders' and this entire conditional expression will always evaluate to true.

What you actually seem to want is,

if job == 'Military Base' or job == 'Raiders':

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...