Python函数为空白条目提供默认值不起作用

时间:2014-03-03 01:15:12

标签: python function

我一直试图解决这个问题太久了!怎么办?

def fallBack(submission):
    if (submission == ""):
           submission = "fixed!"  
           return(submission)

name = input("What is your name?")
(fallBack(name))

location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")

我一直没有打印出最后一个输入......

4 个答案:

答案 0 :(得分:2)

您需要存储fallBack()的结果。 另外,更改fallBack()以返回原始值(如果它是非空的:

def fallBack(submission):
    if not submission:
        return "fixed!"
    else:
        return submission

然后,像这样使用它:

name = fallBack(input("What is your name?"))

答案 1 :(得分:1)

只需移除fallBack(name)

周围的括号即可
def fallBack(submission):
    if (submission == ""):
        submission = "fixed!"  
    return submission

name = input("What is your name?")
name = fallBack(name)

location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")

另请记住,如果使用python 2.7,则应使用raw_input代替input

答案 2 :(得分:0)

我不确定你想做什么,但我认为这样做会:

def fallBack(submission):
    if (submission == ""):
           submission = "fixed!"  
    return (submission)

name = input("What is your name?")
name = fallBack(name)

location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")

你的两个错误不是在没有任何东西需要修复的情况下返回任何内容,而不是为了确定函数返回的值。

顺便说一句,在Python中有一种更惯用的方法:

name = input("What is your name?")
name = name or 'fixed!'

location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")

第二行测试是否将name转换为布尔值,如果它返回False(对于字符串,它等同于测试它是否为空),将其替换为{{ 1}}

答案 3 :(得分:0)

回报没有很好地对齐!除非提交是空的,否则您不会返回任何内容! : - )

def fallBack(submission):
    if (submission == ""):
        submission = "fixed!"  
    return(submission)