2

I'm learning Python currently (love it so far) and have made a little Fahrenheit/Celsius converter.

This is the output upon running it:

Please enter the degrees in Fahrenheit or Celsius to convert: 32

32.0 degrees Celsius is 89.6 degrees Fahrenheit.

32.0 degrees Fahrenheit is 0.0 degrees Celsius.

Do you want to calculate again? (y/n):

Which is how I want it, except if the trailing number after the decimal is a 0 (a whole number), I'd like to drop the .0 entirely (i.e. 5.0 to 5). I'm guessing I'd want an if statement to test if it's equal to zero but how would I go about picking that value?

Full code:

answer = "ERROR"

def calcfc():
""" Calculates F to C and C to F, prints out,
    and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    print("\n{} degrees Celsius is {:.1f} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {:.1f} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()
Community
  • 1
  • 1
Beef Erikson
  • 21
  • 1
  • 5
  • Thanks for the quick response! All look like valid solutions, guess I'll just pick one and run with it. – Beef Erikson May 07 '17 at 07:52
  • split your code in a function `calcfc`, which only calculates the degrees and one that asks for doing it again. get the last two lines of `calcfc` out of this function. – Daniel May 07 '17 at 07:52
  • @Daniel I was wondering if there was a better way of that. I cringed when I used global answer. Thanks, I'll do that. – Beef Erikson May 07 '17 at 08:15

8 Answers8

4

You have to convert the number to a string and test, if it ends with .0:

number = 23.04
text = "{:.1f}".format(number)
if text.endswith(".0"):
    text = text[:-2]
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Please enter the degrees in Fahrenheit or Celsius to convert: 32 32 degrees Celsius is 89.6 degrees Fahrenheit. 32 degrees Fahrenheit is 0 degrees Celsius. Perfect!!! Thanks again :D – Beef Erikson May 07 '17 at 08:12
1

You can get the decimal part of a number as follows:

>> num = 42.56
>> decimal_part = num - int(num)
>> decimal_part = 0.56

This post explores a similar question.

Community
  • 1
  • 1
xssChauhan
  • 2,728
  • 2
  • 25
  • 36
0
args = [89.6, 32.0, 5.5, 10.0, 9.1]

for var in args:
    if var == int(var):
        print int(var) # prints the number without the decimal part
    else:
        print var

OUTPUT

89.6
32
5.5
10
9.1
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Try a number like 32.01? – Allen Qin May 07 '17 at 08:03
  • OP wants to get rid of the 0 after rounding. i.e '{:.1f}'.format(32.01) outputs 32.0 and he wants to have 32 instead. – Allen Qin May 07 '17 at 08:13
  • Your comments are not clear because: first, the OP wants to print `32.01` as `32.01`, not as `32.0` or `32`. And second, I didn't write anywhere that the OP should use string-formatting... – Nir Alfasi May 07 '17 at 08:33
  • Sorry for not being clear. After formatting by {:.1f}, OP wants to convert 5.0 to 5. '{:.1f}'.format(5.01) outputs 5.0 but can't be converted by your code to 5. – Allen Qin May 07 '17 at 08:51
  • @Allen and who says that using formatting is a good idea? This answer suggests to NOT use formatting. – Nir Alfasi May 07 '17 at 17:39
0

Without adding any lines of code to your existing, you can use the g type to accomplish this in the format() call like so

'{0:g}'.format(5.5)

5.5

'{0:g}'.format(5.0)

5
Joe D
  • 378
  • 1
  • 9
0

Setup

ns = [32,32.0,32.04,32.05,32.1,32.45,32.5,32.51,32.6]

Solution

for n in ns:
    print('Before: {:.1f}'.format(n))
    #conditionally set the decimal place.
    print('After: {:.{}f}'.format(n, 0 if n%1 <0.05 else 1 ))

Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.1
After: 32.1
Before: 32.5
After: 32.5
Before: 32.5
After: 32.5
Before: 32.5
After: 32.5
Before: 32.6
After: 32.6
Allen Qin
  • 19,507
  • 8
  • 51
  • 67
0

You can use the modulo operator:

for num in [67.89, 123.0]:
    if num % 1 == 0:
        print(int(num))
    else:
        print(num)

#Output:
67.89
123
Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
0

try this. I have defined a function that strips off .0s from number. While printing I changed {:.1f} to {} as that would format it to a floating point number and there would be a decimal.

answer = "ERROR"

def remove0(initialValue):
  strValue = str(initialValue)

  if ("." in strValue):
    if(int(str(strValue.split(".")[1])) == 0):
      return int(strValue.split(".")[0])
    else:
      return initialValue
  else:
    return initialValue

def calcfc():
    """ Calculates F to C and C to F, prints out,    and asks if user wants to run again """
    try:
        degrees = remove0(float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: ")))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    ftoc = remove0(ftoc)
    ctof = remove0(ctof)

    print("\n{} degrees Celsius is {} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()
pramesh
  • 1,914
  • 1
  • 19
  • 30
0

(Posted solution on behalf of the OP).

Fixed / working code is below and added additional function for repeating as per suggestion (thanks Daniel!). Figured I'd leave in case anyone has a use.

def calcfc():
    """ Calculates F to C and C to F, prints out,
        and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        print("\nPlease enter a valid number.")
        calcfc()

    ctof = (degrees * 9) / 5 + 32
    ftoc = (degrees - 32) * 5 / 9

    # checks if it's a whole number and gets rid of decimal if so
    degrees_text = "{:.1f}".format(degrees)
    ctof_text = "{:.1f}".format(ctof)
    ftoc_text = "{:.1f}".format(ftoc)
    if ctof_text.endswith(".0"):
        ctof_text = ctof_text[:-2]
    if ftoc_text.endswith(".0"):
        ftoc_text = ftoc_text[:-2]
    if degrees_text.endswith(".0"):
        degrees_text = degrees_text[:-2]

    print("\n{} degrees Celsius is {} degrees Fahrenheit.".format(degrees_text, ctof_text))
    print("{} degrees Fahrenheit is {} degrees Celsius.".format(degrees_text, ftoc_text))
    runagain()

def runagain():
    answer = input("\n\nDo you want to calculate again? (y/n): ")
    answer = answer.lower()
    # run again?
    while answer != "y" and answer != "n":
        answer = input("\nPlease enter y for yes or n for no: ")
    if answer == "y":
        calcfc()
    if answer == "n":
        exit()

calcfc()
halfer
  • 19,824
  • 17
  • 99
  • 186