我需要创建一个名为poundsToMetric的python函数,它将以磅为单位的权重转换为千克和克。
例如,而不是打印出2.2千克,正确的答案将是2千克和200克
可以帮助您完成以下转换:
1磅= 2.2千克1千克= 1000克
你的程序应该提示用户输入磅数,并以千克和克为单位输出结果。
def poundsToMetricFunction(kilograms, grams):
pounds = float(input("enter the amount of pounds: ")
kilograms = pounds * 2.2
grams = kilograms * 1000
print('The amount of pounds you entered is ', pounds,
' This is ', kilograms, ' kilograms ', 'and', grams,
'grams')
我知道这是不正确的,但我试图找出我做错了什么,我的意思是,我知道这可能都错了,但我是新手,我想我只是需要一些反馈,我可以添加什么,或者如果我有正确的信息,我应该使用什么格式的正确语法
你的函数有几个问题:
- 当然,你仍然需要裁剪公斤和克,这样数字就不会"重叠"。你可以把一个转到
int
,从而去掉十进制数字,另一个取1000的模,去掉所有超过一公斤的东西。 - 您的语法错误似乎来自
input
行中缺少)
。 - 你把磅换算成公斤是错的,应该是
/ 2.2
,而不是* 2.2
- 这些函数参数没有意义; 相反,您应该将磅传递给函数并返回千克和克,并在转换函数之外进行输入和打印。
像这样:
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))
只是为了修复你的语法,我将提供(正如其他人提到的缩进有点偏离,所以我也已经修复了):
def poundsToMetricFunction(kilograms, grams):
#You were missing a bracket on the following line
pounds = float(input("enter the amount of pounds: "))
kilograms = pounds * 2.2
grams = kilograms * 1000
print('The amount of pounds you entered is ', pounds,
' This is ', kilograms, ' kilograms ', 'and', grams,
'grams' )
如果这仍然不是你想要的,你可能需要提供更多的信息,你想要它做什么。例如,您给函数kilograms, grams
的参数目前没有做任何事情。
你的缩进是关闭的,函数内的所有内容都应该比def多缩进一次。这是因为在调用之后缩进的所有内容都是函数的一部分。循环也是一样。
第二,不要浮动你的输入函数,你可以浮动你的变量,例如: kilograms = float(pounds) * 2.2
第三,你需要调用一个函数。这个函数实际上不会输出任何东西,直到你给它两个参数,千克和克:
poundsToMetricFunction(20,30)