J.Pain34 - 2 years ago 79
Python Question

# My code is used to find conversions but it isnt working please assist

My code is used to find conversions but when I enter an answer which is meant to be redirected in the if/else statement and print the corresponding function it prints the main one every time.

``````print("Welcome to the unit converter program.")

def miletokm():
miles = int(input("How many miles do you want to convert : "))
km = miles*1.60934
print(str(km) + " km")

def kmtomile():
km = int(input("How many kilometers do you want to convert : "))
miles = km/1.60934
print(str(miles) + " miles")

def ctof():
celsius = float(input("What temperature in °C do you want to convert : "))
farenheit = (celsius*float(1.8))+32
print(str(farenheit) + " °F")

def ftoc():
farenheit = int(input("What temperature in °F do you want to convert : "))
celsius = (farenheit-32)*5
celsius1 = celsius/9
print(str(celsius1) + " °C")

def mainquestion():
conversion = input("This program will convert miles to kilometers if you type miletokm.\nIf you want to convert kilometers to miles then type kmtomiles.\nHowever if you want to convert Celcius to Farenheit type ctof. \nFinally, if you want to convert Farenheit to Celcius type ftoc.")

if mainquestion() in ["miletokm"]:
print(miletokm())

elif mainquestion() in ["kmtomile"]:
print(kmtomile())

elif mainquestion() in ["ctof"]:
print(ctof())

elif mainquestion() in ["ftoc"]:
print(ftoc())
else:
mainquestion()
``````

Every time you call `mainquestion()` it's going to ask the user what they want to convert. So if they enter `ftoc` the first time, the first `if` will fail, and then the `elif` will call `mainquestion()` again, so they'll have to answer the question again. This will go on until they get to the final `elif`.

You can put all the `if/elif/else` code inside `mainquestion()`. They should just test the variable `conversion`.

``````def mainquestion():
conversion = input("This program will convert miles to kilometers if you type miletokm.\nIf you want to convert kilometers to miles then type kmtomiles.\nHowever if you want to convert Celcius to Farenheit type ctof. \nFinally, if you want to convert Farenheit to Celcius type ftoc.")

if conversion in ["miletokm"]:
print(miletokm())
elif conversion in ["kmtomile"]:
print(kmtomile())
elif conversion in ["ctof"]:
print(ctof())
elif conversion in ["ftoc"]:
print(ftoc())
else:
mainquestion()

mainquestion()
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download