Python Forum

Full Version: Basic example Coding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone,
I am new to Python programming and moving from MATLAB to python. I am still getting acquainted to python syntax and was trying a few exercises so that i could get a little comfortable and then start working on my projects. I am having troubles getting a float output. Below have pasted my code any help would greatly appreciated. Code works when there isn't decimal keyed in.

Thanks
Sai

def temp2():
    Fahrenheit = input("Enter temp in F:")
    if Fahrenheit.isdigit():
            fahrenheit_1 = int(Fahrenheit)
            C = (fahrenheit_1-32)*(5/9)
            print("Temp in Celcius is",C)
    elif Fahrenheit.isdecimal():
        fahrenheit_1 = float(Fahrenheit)
        C = (fahrenheit_1-32)*(5/9)
        print("Temp in Celcius is",C)
    else:
            print("Input is wrong format")
str.isdecimal() is not intended to return True when the string is valid float
>>> '100.5'.isdecimal()
False
better use try/except

also you may want to read about string formatting:
https://docs.python.org/3/library/string...i-language
print(f"Temp in Celcius is {C:.2f}")
or

print("Temp in Celcius is {:.2f}".format(C))
def f2c():
    fahrenheit = input("Enter temp in F:")
    try:
        fahrenheit = float(fahrenheit)
    except ValueError:
        print("Incorrect input")
    else:
        celsius = (fahrenheit-32)*5/9
        print(f"Temp in Celcius is {celsius:.2f}")
Buran,
Thanks a lot our for the solution and will make sure i add tags when i post a question with code.