You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无用户输入时返回默认值的实现问题求助

问题分析

你的代码中,hello函数的默认参数"stupid"仅在未传递任何参数时才会生效。但你每次调用hello(name)时,无论用户输入的name是空字符串还是有效值,都会将name作为参数传入。当用户直接回车输入空内容时,name为空字符串,因此hello函数会使用这个空值,导致输出Greetings,。

解决方案

以下是三种可行的修改方式:

方式一:调用时判断输入是否为空

在main函数中检查用户输入的name,若为空则不带参数调用hello,触发默认值:

def main():
    name = input("What is your name? ")
    hello(name) if name else hello()

def hello(x ="stupid"):
    print("Greetings,", x)

main()

方式二:在函数内部处理空参数

修改hello函数,让它在收到空字符串或全空格输入时自动使用默认值:

def main():
    name = input("What is your name? ")
    hello(name)

def hello(x=None):
    x = x if x and x.strip() else "stupid"
    print("Greetings,", x)

main()

方式三:利用or运算符简化逻辑

调用hello时,用or运算符直接替换空值或全空格输入:

def main():
    name = input("What is your name? ")
    hello(name.strip() or "stupid")

def hello(x):
    print("Greetings,", x)

main()

内容的提问来源于stack exchange,提问作者rclouser24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:35:25