python汇率兑换

eval()函数:将字符串str当成有效的表达式来求值并返回计算结果。

if __name__ == '__main__'的意思是:当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。

def main():
    exchange_rate = 6.77  # 汇率
    currency_str_value = input("请输入带单位的货币金额(CNY/USD):")

    unit = currency_str_value[-3:]

    if unit == "CNY":
        number = 1 / exchange_rate
    elif unit == "USD":
        number = exchange_rate
    else:
        number = -1

    if number != -1:
        in_money = eval(currency_str_value[:-3])
        convert_currency2 = lambda x: x * number
        out_money = convert_currency2(in_money)
        print("转换后的金额: ", out_money)
    else:
        print("目前版本尚不支持该种货币")

if __name__ == '__main__':
    main()

猜你喜欢

转载自www.cnblogs.com/shirley-lian/p/9669852.html