克转换成千克怎么算python_如何在Python中将磅转换为千克

该博客介绍了如何在Python中创建一个单位转换函数,包括重量单位(如克、千克、磅等),并提供了从一种单位到另一种单位转换的示例代码。用户可以通过输入字符串进行转换操作,例如将吨转换为盎司。文章还建议增加更多单位类型,如纳米、短吨、石头、升、品脱和桶等。

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

更复杂但更灵活的版本:

units = {

'kg': ('weight', 1.),

'kilo': ('weight', 1.),

'kilogram': ('weight', 1.),

'lb': ('weight', 2.204),

'pound': ('weight', 2.204),

'tonne': ('weight', 0.001),

'carat': ('weight', 5000.),

'gram': ('weight', 1000.),

'dram': ('weight', 564.4),

'ounce': ('weight', 35.27),

'grain': ('weight', 15430.),

'm': ('distance', 1.),

'meter': ('distance', 1.),

'kilometer': ('distance', 0.001),

'km': ('distance', 0.001),

'centimeter': ('distance', 100.),

'cm': ('distance', 100.),

'meter': ('distance', 1.),

'mile': ('distance', 0.0006214),

'chain': ('distance', 0.04971),

'furlong': ('distance', 0.004971),

'league': ('distance', 0.0002071),

'foot': ('distance', 3.281),

'feet': ('distance', 3.281), # irregular plural - must be explicitly specified!

'inch': ('distance', 39.37)

}

def getUnit(unit_name):

if unit_name in units:

return units[unit_name]

# recognize regular plural forms

elif unit_name.endswith('es') and unit_name[:-2] in units:

return units[unit_name[:-2]]

elif unit_name.endswith('s') and unit_name[:-1] in units:

return units[unit_name[:-1]]

# not found?

else:

raise ValueError("Unrecognized unit '{0}'".format(unit_name))

def convert(amt, from_unit, to_unit):

typeA, numA = getUnit(from_unit)

typeB, numB = getUnit(to_unit)

if typeA==typeB:

return amt * numB / numA

else:

raise ValueError("Units are of different types ('{0}' and '{1}')".format(typeA, typeB))

def conversion(s):

"""

Do unit conversion

Accepts a string of the form

"(number) (unitA) [to] (unitB)"

If unitA and unitB are of the same unit-type, returns the converted value.

"""

s = s.strip().lower().split()

if len(s) not in (3, 4):

raise ValueError("Argument string has wrong number of words (should be three or four)")

try:

amt = float(s[0])

except ValueError:

raise ValueError("Argument string must start with a number")

from_unit = s[1]

to_unit = s[-1]

return convert(amt, from_unit, to_unit)

def tryAgain():

s = raw_input('Try again (Y/n)? ').strip().lower()

return 'yes'.startswith(s)

def main():

while True:

s = raw_input("Convert what? (ex: 10 meters to feet) ")

try:

print(": {0}".format(conversion(s)))

except ValueError, v:

print v

if not tryAgain():

break

if __name__=="__main__":

main()

这可以解决诸如10吨到盎司的问题"或者" 30弗隆到脚"。

建议进一步补充:

以距离为单位添加纳米(并测试)。

以重量单位加上短吨和石头(并测试它们)。

以体积为单位添加升,品脱和桶(并测试它们)。

醇>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值