Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic example Coding
#1
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")
Reply
#2
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}")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic Coding Question: Exit Program Command? RockBlok 3 504 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  [split] Very basic coding issue aary 4 2,414 Jun-03-2020, 11:59 AM
Last Post: buran
  Very basic coding issue mstichler 3 2,553 Jun-03-2020, 04:35 AM
Last Post: mstichler
  Basic coding question with Python Than999 3 3,058 Jul-17-2019, 04:36 PM
Last Post: jefsummers
  Hey guys can you please help me with some basic coding Stabu 9 6,172 Jul-16-2017, 10:11 AM
Last Post: MyImpsNamesAre
  Incredibly basic coding problem AndyF 12 8,417 Feb-11-2017, 03:52 PM
Last Post: AndyF

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020