2014-10-03 73 views
-1

我试图从第一行提取输入的某个部分并使用它来计算问题,然后将它们放回到一起。从输入中提取某些数据

例如,

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 

我想提取英镑和工作,首先还是我在看这个问题?下面是问题描述:

为以下问题编写伪代码和Python 3.3程序。一只猴子正在喂食一些食物。以磅为单位读取起始重量:盎司。还可以读取lbs:ozs中的结尾重量(你可能会认为这比起始重量小)找出差异并以lbs:ozs打印猴子消耗的食物量。一些示例数据如下所示(与相应的输出)

提示:所有值转换成盎司首先使用“查找”命令来查找。“:”在输入数据(见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 
+0

获得如下用户输入:'i = input('请输入食物的起始重量,以磅为单位,后面是盎司:')'。将输入转换为英镑和盎司,如下所示:磅,盎司= map(int,i.split(':'))'。这是非常基本的东西。考虑阅读[python教程](https://docs.python.org/3/tutorial/)。 – 2014-10-03 19:39:19

+0

这是我的第一个编程课。我只是很难理解find命令。仍然不能解决这个问题。 – 2014-10-05 23:21:29

回答

0

试试这个:

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) 
+0

所以这将第一个输入分成两个不同的输入?每当我尝试打印只是磅,它给我两磅和盎司。也不理解除了行。第一次编程课,所以我刚刚开始! – 2014-10-05 22:02:26

+0

在这种情况下,是'.split(':')'将用户输入分成两个值。 [文档str.split。](https://docs.python.org/3.3/library/stdtypes.html#str.split)如果用户输入无效的输入,'except(ValueError)as err:'将被执行,它不能被转换为数字,比如'5:a'或'7'。 – 2014-10-06 06:33:37

0
# 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)) 

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