簡體   English   中英

使用 Python 進行單位轉換

[英]Unit conversion using Python

我正在學習 Python the Hard Way, On Ex-5 Study Drills,它說

嘗試編寫一些將英寸和磅轉換為厘米和公斤的變量。 不要只輸入測量值。 用 Python 計算數學。

到目前為止,我已經這樣做了:

inches = 1
centimeters = 1
convert = centimeters * 2.54
print inches
print centimeters 
print "1 inch is %s centimeters." % convert

現在將顯示 1 英寸的轉換,我將如何更改它以便用戶輸入以英寸或厘米為單位的數量,並且它會正確顯示轉換?

我是否認為它要成功轉換值,我必須手動輸入值,或者有沒有辦法在 Python 中做到這一點?

有用於處理單元的庫。 品脫是 Python 的一種:

import pint

ureg = pint.UnitRegistry()
my_size = 1.74 * ureg.meter
print(my_size)  # 1.74 meter
print(my_size.to(ureg.inch))  # 68.503937007874 inch

優點是變量本身具有有關使用哪個單位的信息。 即使你分開,這也會繼續:

import pint

ureg = pint.UnitRegistry()
distance = 40123 * ureg.meter
time = 1.2 * ureg.hour
speed = distance / time
print(speed)  # 33435.833333333336 meter / hour
print(speed.to(ureg.inch / ureg.hour))  # 1316371.3910761154 inch / hour

您可以使用input()方法(包裝在float()方法中將數據轉換為整數

m_inch = float(input("Enter the amount in inches: ")) # will collection user data in inches

m_cm = m_inch*2.54 # converts from inches to cm

# rest of your code

注意,我使用float類型進行輸入,但您也可以使用int()來包裝....這有幫助嗎?

您可以使用字典來查找指定的單位:

amount, unit = input('Enter amount with units: ').split()[:2]
converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit] 
name = "Bob Jones"
age = 39
height = 74 # in inches
height_in_cm = height * 2.54
weight = 220 # in pounds
weight_in_kg = weight * 0.453592
eyes = "blue"
teeth ="white"
hair = "light brown"

print(f"Let's talk about {name}.")
print(f"He's {height} inches tall which is roughly {round(height_in_cm)} centimeters.")
print(f"He weighs {weight} pounds which is about {round(weight_in_kg)} kilograms.")
print(f"Actually, that's his target weight after six months of intermittent fasting.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on how much coffee he drinks.")
centimeters = int(input("Enter your height in CM "))
meters = centimeters / 100
print ("You are %r meters long" % (meters))

這要求用戶以厘米為單位輸入高度,記住 1m 等於 100cm。 因此,我們將 180 除以 100 得到米,例如,如果用戶輸入 180 厘米,將打印 1.8 米。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM