我需要允许用户选择一个值并相应地调用一个函数的帮助。
weight = input('Enter K for kilos or P for pounds : ')
unit = weight
if unit == "K":
def metricTopound(kilograms):
pounds = kilograms * 2.2
ounces = pounds * 16
return int(pounds), ounces % 16
kilograms = float(input("How many Kilos ? "))
lb, o = metricTopound(kilograms)
print('The amount of pounds you entered is {}. '\
'This is {} pounds and {} ounces.'.format(kilograms, lb, o))
elif unit == " P ":
def poundsToMetric(pounds):
kilograms = pounds / 2.2
grams = kilograms * 1000
return int(kilograms), grams % 1000
pounds = float(input("How many Pounds? "))
kg, g = poundsToMetric(pounds)
print('The amount of pounds you entered is {}. '\
'This is {} kilograms and {} grams.'.format(pounds, kg, g))
用户应该能够选择P
来获取以千克为单位的重量,或者选择K
来获取以磅为单位的重量。
答案 0 :(得分:0)
您可能需要预先定义函数:
def metricTopound(kilograms):
pounds = kilograms * 2.2
ounces = pounds * 16
return int(pounds), ounces % 16
def poundsToMetric(pounds):
kilograms = pounds / 2.2
grams = kilograms * 1000
return int(kilograms), grams % 1000
weight = input('Enter K for kilos or P for pounds : ')
unit = weight
if unit == "K":
kilograms = float(input("How many Kilos ? "))
lb, o = metricTopound(kilograms)
print('The amount of kilograms you entered is {}. '\
'This is {} pounds and {} ounces.'.format(kilograms, lb, o))
elif unit == "P":
pounds = float(input("How many Pounds? "))
kg, g = poundsToMetric(pounds)
print('The amount of pounds you entered is {}. '\
'This is {} kilograms and {} grams.'.format(pounds, kg, g))
答案 1 :(得分:0)
return
语句下面的行将永远不会执行" P "
进行比较,因此用户需要先添加空格,然后再添加P和尾随空格。固定代码
def metricTopound(kilograms):
pounds = kilograms * 2.2
ounces = pounds * 16
return int(pounds), ounces % 16
def poundsToMetric(pounds):
kilograms = pounds / 2.2
grams = kilograms * 1000
return int(kilograms), grams % 1000
unit = raw_input('Enter K for kilos or P for pounds : ') #get as string
weight= input("Ener Weight") #get as integer
if unit == "K":
metricTopound(weight)
kilograms = float(input("How many Kilos ? "))
lb, o = metricTopound(kilograms)
print('The amount of pounds you entered is {}. '\
'This is {} pounds and {} ounces.'.format(kilograms, lb, o))
elif unit == "P":
poundsToMetric(weight)
pounds = float(input("How many Pounds? "))
kg, g = poundsToMetric(pounds)
print('The amount of pounds you entered is {}. '\
'This is {} kilograms and {} grams.'.format(pounds, kg, g))