2014-10-03 71 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)) 

這應該讓你開始。剩下的就是編寫將磅和盎司換算成磅的代碼,並計算猴子食用了多少食物。祝你好運。