python中单位转换_Python入门练习 - 简单的计量单位转换

这篇博客提供了两个Python练习,分别涉及货币和温度单位的转换。用户输入以RMB或USD开头的金额,程序会进行汇率转换;输入以C或F开头的温度,程序则会进行摄氏度和华氏度之间的转换。通过这些练习,初学者可以巩固Python的基本操作和条件判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习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?')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值