从输入中提取特定数据

2024-09-28 22:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从第一行中提取我输入的一部分,然后用它来计算问题,然后把它放回原处。在

例如

Please enter the starting weight of food in pounds followed by ounces:8:9

Please enter the ending weight of food in pounds followed by ounces:6:14

我想先减掉赘肉然后再去做,还是我看错了?以下是问题描述:

为以下问题编写伪代码和python3.3程序。一只猴子正在吃东西。读入起始重量伦敦商学院:奥兹。也读在结尾的重量磅:盎司(你可以假设这比起始重量小。找出差异并打印出猴子吃的食物量伦敦商学院:奥兹。下面显示了一些示例数据(以及相应的输出)。在

提示:首先将所有值转换为盎司。使用“find”命令查找输入数据中的“:”(请参见Y:上的sample2)。在

运行1: >

Starting weight of food (in lbs:ozs)=8:9

Ending weight of food (in lbs:ozs)=6:14

Food consumed by the monkey (lbs:ozs)=1:11

Tags: oftheinbyfood猴子enterplease
2条回答

试试这个:

msg = 'Starting weight of food (in lbs:ozs) = '
answer = input(msg).strip()
try:
    pounds, ounces = answer.split(':')
    pounds = float(pounds)
    ounces = float(ounces)
except (ValueError) as err:
    print('Wrong values: ', err)

print(pounds, ounces)
# get input from the user, e.g. '8:9'
start_weight= input('Starting weight of food (in lbs:ozs)=')
# so start_weight now has the value '8:9'

# find the position of the ':' character in the user input, as requested in the assignment: 'Use the “find” command to locate the “:” in the input data'
sep= start_weight.find(':')
# with the input from before ('8:9'), sep is now 1

# convert the text up to the ":" character to a number
start_pounds= float(start_weight[:pos])
# start_pounds is now 8

# convert the text after the ":" character to a number
end_pounds= float(start_weight[pos+1:])
# end_pounds is now 9

# get input from the user, e.g. '6:14'
end_weight= input('Ending weight of food (in lbs:ozs)=')

SNIP # You'll have to figure this part out for yourself, I can't do the entire assignment for you...

# finally, display the result, using "str(number)" to convert numbers to text
print('Food consumed by the monkey (lbs:ozs)=' + str(pounds_eaten_by_monkey) + ':' + str(ounces_eaten_by_monkey))

你应该开始。剩下的就是编写将磅和盎司转换成磅的代码,并计算猴子吃了多少食物。祝你好运。在

相关问题 更多 >