Python Forum
Basic example Coding - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Basic example Coding (/thread-23277.html)



Basic example Coding - gudlur46 - Dec-19-2019

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")



RE: Basic example Coding - buran - Dec-19-2019

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.html#format-specification-mini-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}")



RE: Basic example Coding - gudlur46 - Dec-19-2019

Buran,
Thanks a lot our for the solution and will make sure i add tags when i post a question with code.