Python 3.4.3版。为什么我的程序在输入错误后不保存字典键?

2024-06-16 10:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

def add_goose_group():
    goose_group_name = input('Insert the name of the raft ')
    goose_group_name = str(goose_group_name)
    if goose_group_name.isdigit() == False and (' ' in goose_group_name) == False:
        return goose_group_name
    else:
        add_goose_group()

第一个if条件检查输入中是否只有数字,第二个if条件检查输入中是否有空格。当我尝试这段代码时,它会正确地检查输入是否符合这些标准,但在代码的返回部分(至少我认为这就是问题所在)不会返回任何东西。当另一个函数将goose\u group\u name添加到字典的键位置时,它不会打印出None

为什么它不保存从用户获取的输入并将其置于关键位置


Tags: ofthe代码nameaddfalse密码input
2条回答

Why does it not save the input taken from the user and put it into the key position?

你到底在哪里有一个对象来存储这个输入

也许你需要这样的东西:

def add_goose_group():
    while True:
        goose_group_name = input('Insert the name of the raft ')
        goose_group_name = str(goose_group_name)
        if goose_group_name.isdigit() == False and (' ' in goose_group_name) == False:
            return goose_group_name

dct = {}
dct['user_input'] = add_goose_group()

print(dct)  # outputs {"user_input": "name of inputted raft"}

add_goose_group()将永远循环,直到用户输入有效的输入(不是数字,也没有空格),并将此输入保存到dct对象中

递归调用的工作方式与任何其他函数调用类似:调用add_goose_group来处理输入无效的情况,但实际上并不处理结果。到达当前函数调用的结尾(您当前中的函数也是这一事实在这里并不重要),并且隐式返回None,就像在Python中到达函数结尾时没有显式return一样

但是,您不应该对此使用递归—而是执行循环

相关问题 更多 >