
汇率转换3.0:
USD_VS_CNY=6.32
currency_str=input('请输入带货币的单位(美元:USD,人民币:RMB)的金额,或者输入X退出')
while currency_str!='X':
uint =currency_str[-3:]
if uint =='USD':
usd_value_str = currency_str[:-3]
usd_value =eval(usd_value_str)
cny = usd_value* USD_VS_CNY
print('人民币的金额为',cny)
elif uint =='RMB':
cny_value_str = currency_str[:-3]
cny_value =eval(cny_value_str)
usd =cny_value/USD_VS_CNY
print('美元的金额为:',usd)
else:
print('')
currency_str =input('请输入带货币的单位(美元:USD,人民币:RMB)的金额,或者输入X退出')
实现功能:1.汇率转换 2.自定义退出 3.while循环使用
汇率转化5.0:
def convert_currency(im, er):
out = im * er
return out
def main():
currency_str_value = 0
while currency_str_value != "":
USD_VS_RMB = 6.77
# 输入带单位的货币金额
currency_str_value = input('请输入带单位货币的金额: ')
# 获取货币单位
unit = currency_str_value[-3:] # 第一次判断
if unit == 'CNY':
exchange_rate = 1 / USD_VS_RMB
elif unit == 'USD':
exchange_rate = USD_VS_RMB
else:
exchange_rate = -1
if exchange_rate != -1:
in_money = eval(currency_str_value[0:3])
# 使用lambda定义函数
convert_currency2 = lambda x: x * exchange_rate
# 调用lambda函数
out_money = convert_currency2(in_money)
print('转换后的金额是: ', out_money)
else:
print('无法计算')
if __name__ == "__main__":
main()
优点:调用更加方便,效率更快。
课后习题:在线实时汇率转换:
import requests
from lxml import etree
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
}
url = "https://www.huilv.cc/USD_CNY/"
def Get_huilv(url, headers1):
res = requests.get(url=url, headers=headers1, timeout=2)
# print(res.status_code)#打印状态码
html = etree.HTML(res.text)
USD_VS_RMB_0 = html.xpath('//div[@id="main"]/div[1]/div[2]/span[1]/text()')
for a in USD_VS_RMB_0:
b = a
USD_VS_RMB_1 = float(b)
print("实时汇率为:{}".format(USD_VS_RMB_1))
currency_str_value = 0
while currency_str_value != "":
USD_VS_RMB = float(str(USD_VS_RMB_1))
# 输入带单位的货币价格
currency_str_value = input('请输入带单位货币的价格: ')
# 获取货币单位
unit = currency_str_value[-3:].upper() # 第一次判断
if unit == 'CNY':
exchange_rate = 1 / USD_VS_RMB
string = "美元"
elif unit == 'USD':
exchange_rate = USD_VS_RMB
string = "元"
else:
exchange_rate = -1
if exchange_rate != -1:
in_money = eval(currency_str_value[0:-3])
# 使用lambda定义函数
convert_currency2 = lambda x: x * exchange_rate
# 调用lambda函数
out_money = convert_currency2(in_money)
print('转换后的价格是:{} {} '.format(out_money, string))
else:
print('无法计算')
Get_huilv(url, headers)
出现的错误:
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)