[英]using multiple parameters in python function
這是我要解決的問題:
定義一個名為food的函數,該函數接收兩個參數:一個整數值,該值表示一天中的時間(以小時為單位),范圍為0到24;一個布爾值,表示一個人是否喜歡糖果(真)(錯)。 該函數應返回一個帶有消息的單個字符串,如下所示。
如果早於6,則消息應顯示“無食物”(無論是否喜歡甜食的人)。
如果包含的極限值在6到10之間,則該消息應顯示“早餐”,並且如果該人喜歡糖果,則在早餐一詞之后,還應添加逗號和“果醬”一詞,否則(如果該人不喜歡糖果,現在是早餐時間),早餐一詞后應有一個逗號和“咖啡”一詞(逗號后不能有空格)。 然后,如果時間在11到15之間(包括極端時間),則消息應顯示“午餐”,並且該人喜歡糖果。 另外,在“午餐”一詞之后將有一個逗號,然后是“甜點”一詞。 同樣,如果在15點之后或22點之前,該消息將顯示“晚餐”,並且與午餐類似,如果該人喜歡吃糖果,則會出現一個逗號,然后是“甜點”。 如果它是22或更高版本,則返回的消息應再次為“ no food”。
例如
food(4,False) should return "no food"
food(7,True) should return the message "breakfast,marmalade"
food(7,False) should return "breakfast,coffee"
food(12,True) should return "lunch,dessert"
food(20,False) should return "dinner"
例如,以下代碼片段:
print food(7,True)
應該產生輸出:
breakfast,marmalade
這就是我所擁有的,我被卡住了! 請幫助。
def food(input,boolean):
time = int(input)
food_type = ""
if time >= 0 and time < 6 or time >= 22:
food_type = "no food"
if time >= 6 and time <= 10:
food_type = "breakfast"
if time >= 11 and time <= 15:
food_type = "lunch"
if time >= 16 and time < 22:
food_type = "dinner"
dessert = ""
if boolean == "True" and food_type == "breakfast":
dessert = "marmalade"
if boolean == "False" and food_type == "breakfast":
dessert = "coffee"
if boolean == "True" and food_type == "lunch":
dessert = "dessert"
if boolean == "True" and food_type == "dinner":
dessert = "dessert"
return dessert
return food_type
print food(7,True)
您有兩個問題:
(1)在一個函數中,您不能(有意義地)有兩個return語句; 返回值求值時,函數結束。 你想寫的是
return (desert,food_type)
一次獲得兩個。 按照書面規定,您將返回“沙漠”,並且永遠沒有機會獲得“ food_type”
有關詳情,請參見此帖子:
也許這是關於返回的教程(python文檔不是學習return語句的好手,它們有點技術性):
http://learnpythonthehardway.org/book/ex21.html
(2)您正在將字符串與布爾值進行比較。 你的意思是
if boolean == True:
不
if boolean == "True":
def food(input,boolean):
time = int(input)
food_type = ""
if time >= 0 and time < 6 or time >= 22:
food_type = "no food"
if time >= 6 and time <= 10:
food_type = "breakfast"
if time >= 11 and time <= 15:
food_type = "lunch"
if time >= 16 and time < 22:
food_type = "dinner"
dessert = ""
if boolean == True and food_type == "breakfast":
dessert = "marmalade"
if boolean == False and food_type == "breakfast":
dessert = "coffee"
if boolean == True and food_type == "lunch":
dessert = "dessert"
if boolean == True and food_type == "dinner":
dessert = "dessert"
return (dessert, food_type)
# return food_type
print food(7,True)
產生(“果醬”,“早餐”),如果您想使用其中之一,則應像這樣使用
raw = food(7, True)
print raw[0]
print raw[1]
它會產生
marmalade
breakfast
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.