Home > Software design >  how to use if condition on more than one line?
how to use if condition on more than one line?

Time:05-10

I'm new to python so I have 1 question about the "if" sentence. I have 3 variables and I need to show 1 message on the screen like the millage is" ", look:

I have 3 city if i write 1 show the millage but if don't exist show "address not found try again" when I use else like the below:

else: print(Fore.GREEN "\nAddress not Found, check address again")

show me the sentence "not found check again" but show the millage too, I don't know if I'm explaining ok, but if someone can help ill B thankful.

destino1 = "Tuscalosa AL"
destino2 = 'Warren OH'
destino3 = "Atlanta GA"


 if address in (destino1):
  print(Fore.WHITE   "\nTotal Miles  ", "\033[34m","935 miles")

 if address in (destino2):
  print(Fore.WHITE   "\nTotal Miles ", "\033[34m", "1600 miles")

 if address in (destino3):
  print(Fore.WHITE   "\nTotal Miles ", "\033[34m", "1107 miles")        



 else:
   print(Fore.GREEN   "\nAddress not Found, check address again")

CodePudding user response:

I think what you want is this kind of structure:

if address in (destino1):
    print(Fore.WHITE   "\nTotal Miles  ", "\033[34m","935 miles")
elif address in (destino2):
    print(Fore.WHITE   "\nTotal Miles ", "\033[34m", "1600 miles")
elif address in (destino3):
    print(Fore.WHITE   "\nTotal Miles ", "\033[34m", "1107 miles") 
else:
    print(Fore.GREEN   "\nAddress not Found, check address again")

CodePudding user response:

Use if - elif - else format.

If I understood you question correctly, you are trying to print milage for a city entered by user but if the city entered is not from the given three, you want to print "not found" statement.

you can do something like this,

if address==destion1:
   print(milage for destion1)
elif address==destion2:
   print(milage for destion2)
elif address==destion3:
   print(milage for destion3)
else:
   print("Not found statement")

Additional suggestions It will be a good practice to use a dict or list instead of declaring 3 variables. And you can shorten the conditional statements, and overall code, like below,

destinations = {"dest1" : "milage1", "dest2" : "milage2", "dest3" : "milage3"}

if address in destinations:
   print(f"Milage for {address} is {destinations[address]})
else:
   print("Destination not found")
  • Related