Paul Bernella
Paul Bernella

Reputation: 31

Boolean Variables and If statement fails for true statements

Here's the prompt:

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999 – 2002. Given variables modelYear and modelName write a statement that assigns True to recalled if the values of modelYear and modelName match the recall details and assigns False otherwise.

I wrote this code but kept getting wrong answers for the true statements. The false statements came through just fine.

modelYear >= 1999 and modelYear <= 2002
modelName == "Extravagant"
if modelYear == True and modelName == True:
    recalled = True
else:
    recalled = False

Upvotes: 0

Views: 8221

Answers (2)

Alex
Alex

Reputation: 1101

When you have:

modelYear >= 1999 and modelYear <= 2002
modelName == "Extravagant"

You don't store the result of the statements. To make it work you could something like:

year = modelYear >= 1999 and modelYear <= 2002
name = modelName == "Extravagant"
if year and name:
    recalled = True
else:
    recalled = False

But the easier solution would be to do it directly in the if statement like:

if modelYear >= 1999 and modelYear <= 2002 and modelName == "Extravagant":
    recalled = True
else:
    recalled = False

The shortest way of doing it would be:

recalled = modelYear >= 1999 and modelYear <= 2002 and modelName == "Extravagant"

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90889

When you do -

modelYear >= 1999 and modelYear <= 2002
modelName == "Extravagant"

You are just throwing away the result of those boolean expressions, this does not magically make modelYear or modelName boolean values.

Instead of trying to create boolean values, you can simply use the expression in the if block itself. Example -

if 1999 <= modelYear <= 2002 and modelName == "Extravagant":
    recalled = True
else:
    recalled = False

And if inside the if block in your real code, all you do is assign the boolean value, then you can do -

recalled = 1999 <= modelYear <= 2002 and modelName == "Extravagant"

Upvotes: 1

Related Questions