Python入门练习 - 简单的计量单位转换

练习1: 货币转换

tempStr = input('Please input an amount stating with RMB or USD: ').strip()
tempSign = tempStr[0:3].upper()
tempNum = tempStr[3:]

def isfloat(value):
    try:
        float(value)
        return True
    except:
        return False


rate = 6.78
if isfloat(tempNum):
    tempNum = float(tempNum)
    if tempSign == "RMB":
        result = tempNum / rate
        print('USD{0:.2f}'.format(result))
    elif tempSign == 'USD':
        result = tempNum * rate
        print('RMB{0:.2f}'.format(result))
    else:
        print('input invalid.')
else:
    print('Are you kidding?')

练习2:温度转换

tempStr = input('Input a temperature starting with C or F').strip()
tempSign = tempStr[0].upper()
tempNum = tempStr[1:]


def isfloat(value):
    try:
        float(value)
        return True
    except:
        return False


if isfloat(tempNum):
    tempNum = float(tempNum)
    if tempSign == "F":
        result = (tempNum - 32) / 1.8
        print('C{0:.2f}'.format(result))
    elif tempSign == 'C':
        result = tempNum * 1.8 + 32
        print('F{0:.2f}'.format(result))
    else:
        print('Temperature sign is missing or invalid.')
else:
    print('Are you kidding?')

你可能感兴趣的:(Python入门练习 - 简单的计量单位转换)