使用原始输入的函数

时间:2016-07-29 15:19:23

标签: python function

我正在尝试到目前为止我学到的东西,我想用object创建一些互动的东西。

我想要做的是创建一个能够根据输入创建不同方向的对话的功能。但是,我无法弄清楚如何使函数接受raw_input()作为其参数。

以下是我编写的代码;

raw_input

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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."

答案 2 :(得分: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.正确的缩进对于您的代码工作至关重要 2.在定义函数drinktype()之后,你需要实际调用它来让它运行。 (最后一行是调用函数)