shymilk
shymilk

Reputation: 96

Multiple if conditions give me the wrong answer

I have three different cities and I want to print the distances between the cities, depending on the input from the user.

A to B is 100miles A to C is 150miles C to B is 80 miles

I use if statements with multiple conditions to define the variable distance, but it never gives me the right answer :/

I also want to add an else-statement that is triggered if the user enters other cities than a,b, or c - or when the user enters the same city twice.

I've tried setting the parentheses differently and using if instead of elif.

My Code:

AB=100
AC=150
CB=80

city_1=input("Enter city 1 ")
city_2=input("Enter city 2 ")

if (city_1=="A" or "B") and (city_2=="A" or "B") and (city_1 != city_2):
    distance=100
elif (city_1=="A" or "C") and (city_2=="A" or "C") and (city_1 != city_2):
    distance=150
elif (city_1=="B" or "C") and (city_2=="B" or "C") and (city_1 != city_2):
    distance=80

if city_1==city_2 or (city_1 or city_2 != "A" or "B" or "C"):
    print("You did not enter a viable match.")

#print(distance)

Depending on what the user has entered, the result should show: 100, 150, or 80

However, my code shows me for A-C 100 instead of 150.

Any hints?

Upvotes: 1

Views: 96

Answers (1)

Christian Legge
Christian Legge

Reputation: 1043

Python isn't a human and it doesn't understand language like one. So when you read:

if city equals "A" or "B"

You probably understand that what is meant is that city can be equal to either A or B. But what Python sees is this:

if 
    city equals "A"
    OR
    "B"

It's treating "B" as its own condition here, as or is a keyword that separates conditions. And a non-empty string evaluates to true, so those conditions are evaluating to true no matter what.

There are a couple ways to fix this:

if city1 == "A" or city1 == "B"
if city1 in ["A", "B"]
if city1 in {"A", "B"}

Upvotes: 3

Related Questions