2016-07-29 87 views
1

我正在試驗迄今爲止學到的知識,並且我想創建一些互動式的東西,使用raw_input()在原始輸入中使用函數

我想要做的是創建一個函數,該函數將創建一個會根據輸入變成不同方向的對話。但是,我無法弄清楚如何創建一個函數接受raw_input作爲它的參數。

這是我寫的代碼;

drink = raw_input("Coffee or Tea?") 

def drinktype(drink): 
    if drink == "Coffee": 
    #I WANT TO INSERT A CODE HERE THAT WILL CALL THE FUNCTION coffee(x) 
    elif drink == "Tea": 
     print "Here is your tea." 
    else: 
     print "Sorry." 

x = raw_input("Americano or Latte?") 

def coffee(x): 
    if x == "Americano": 
     return "Here it is."  
    elif x == "Latte": 
     return "Here is your latte." 
    else: 
     return "We do not have that, sorry." 
+2

原樣,此代碼不起作用。請確保您至少遵守Python的語法,並確保您正確縮進。縮進在Python中很重要。 – idjaw

+3

你似乎永遠不會調用你的函數。 –

+0

我改變了縮進,感謝提醒,但我在這裏粘貼代碼時不小心,對不起。我如何調用函數? – sonooob

回答

1

的美式或拿鐵的要求是,你只需要在所請求的咖啡做一些事情;如果用戶請求喝茶,這是無關緊要的。一旦在Coffee案件下移動,您可以簡單地將返回的值傳遞給coffee()。返回值也需要打印。

def drinktype(drink): 
    if drink == "Coffee": 
     kind = raw_input("Americano or Latte?") 
     print coffee(kind) 
    elif drink == "Tea": 
     print "Here is your tea." 
    else: 
     print "Sorry." 

def coffee(x) 
    if x == "Americano": 
     return "Here it is."  
    elif x == "Latte": 
     return "Here is your latte." 
    else: 
     return "We do not have that, sorry." 

drink = raw_input("Coffee or Tea?") 
drinktype(drink) 
+0

感謝您的解釋,它現在可以工作。 – sonooob

0

你在找這樣的嗎?

drink = raw_input("Coffee or Tea?") 

def drinktype(drink): 
    if drink == "Coffee": 
     usercoffeetype = raw_input("What type of coffee do you drink?") 
     coffee(usercoffeetype) 
    elif drink == "Tea": 
     print "Here is your tea." 
    else: 
     print "Sorry." 

x = raw_input("Americano or Latte?") 

def coffee(x) 
    if x == "Americano": 
     return "Here it is."  
    elif x == "Latte": 
     return "Here is your latte." 
    else: 
     return "We do not have that, sorry." 

還只是一個註釋 - 使用像「x」這樣的變量名通常不是一個好主意。它會更好,如果你的變量名稱實際上描述了它擁有,就像這樣:

def coffee(coffeechoice) 
    if coffeechoice == "Americano": 
     return "Here it is."  
    elif coffeechoice == "Latte": 
     return "Here is your latte." 
    else: 
     return "We do not have that, sorry." 
0

貌似你試圖得到類似以下

def coffee(): 
    x = raw_input("Americano or Latte?") 
    if x == "Americano": 
     return "Here it is."  
    elif x == "Latte": 
     return "Here is your latte." 
    else: 
     return "We do not have that, sorry." 

def drinktype(drink): 
    if drink == "Coffee": 
     print coffee() 
    elif drink == "Tea": 
     print "Here is your tea." 
    else: 
     print "Sorry." 


drink = raw_input("Coffee or Tea?") 

drinktype(drink) 

請注意, 1.正確的縮進是至關重要的,你的代碼來定義一個函數drinktype工作後 2.() ,你需要實際調用它來讓它運行。 (最後一行是調用該函數)

+0

哦,我明白了。謝謝。 – sonooob