-2

I am currently writing a Fahrenheit to celcius calculator in python with two given options for users to choose between converting "F"(Fahrenheit) and "C" Celcius. I want to make it so that the program will loop back to asking the original question in my program and restarting the question chain if the user picks an option that is not either "F" or "C"

user_choice = input("do you want to convert F or C?: ")

if user_choice == "F":
    x = int(input("Please enter farihneit tempature: "))
    farinheit = (x-32) * 5/9
    print(farinheit)

elif user_choice == "C":
    c = int(input("Please enter celcius tempature: "))
    celcius = (c*1.8) + 32
    print(celcius)

else:
    print("wrong")

I've tried watching youtube videos and reviewing lessons on the web

LSJ32141
  • 49
  • 3

3 Answers3

1

using a while loop will allow the the application to loop continuously.

is_open = True

while is_open:
    user_choice = input("do you want to convert F or C?: ")

    if user_choice == "F":
        x = int(input("Please enter farihneit tempature: "))
        farinheit = (x-32) * 5/9
        print(farinheit)

    elif user_choice == "C":
        c = int(input("Please enter celcius tempature: "))
        celcius = (c*1.8) + 32
        print(celcius)

   else:
        print("wrong")
Ameer
  • 11
  • 3
  • 1
    I would add a further elif to provide an exit option, in case user just wants to quit without determining the conversion: elif user_choice =='X': break – Galo do Leste Jan 24 '23 at 04:37
0

I think the behaviour you're after is best achieved using python's match statement (python 3.10+) as below. You could of course do it using if-else statements, but match may just be a nice (and clean) addition to your toolkit.

while True:
    user_choice = input("do you want to convert F or C?: ")
    match user_choice:
        case "F":
            x = int(input("Please enter farihneit tempature: "))
            farinheit = (x-32) * 5/9
            print(farinheit)
            break
        case "C":
            c = int(input("Please enter celcius tempature: "))
            celcius = (c*1.8) + 32
            print(celcius)
            break
        case _:
            print("wrong input")
            continue
Py_Dream
  • 363
  • 2
  • 10
0

You could simply use a loop

while True:
choice = input("Enter 'F' to convert Fahrenheit to Celsius or 'C' to convert Celsius to Fahrenheit: ")
if choice == 'F':
    fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
    celsius = (fahrenheit - 32) * 5/9
    print("Temperature in Celsius: {:.2f}".format(celsius))
    break
elif choice == 'C':
    celsius = float(input("Enter the temperature in Celsius: "))
    fahrenheit = celsius * 9/5 + 32
    print("Temperature in Fahrenheit: {:.2f}".format(fahrenheit))
    break
else:
    print("Invalid option. Please enter 'F' or 'C'.")