Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用返回来中断循环的最佳方法_Python 3.x_While Loop_Return_Code Structure_Function Definition - Fatal编程技术网

Python 3.x 使用返回来中断循环的最佳方法

Python 3.x 使用返回来中断循环的最佳方法,python-3.x,while-loop,return,code-structure,function-definition,Python 3.x,While Loop,Return,Code Structure,Function Definition,首先,我不是以英语为母语的人,如果有语法错误,请原谅 我是一个真正的新手,刚刚开始学习编程——我选择Python3作为我的第一语言。所以请宽大点:) 我已经试着自己寻找答案,但没有成功。 更好或更正确的“风格”是什么。运行时是否可能有差异。谢谢大家! 第1版: def newUsername(db): isUser = True while isUser: username = input('Set an username:...') if not

首先,我不是以英语为母语的人,如果有语法错误,请原谅 我是一个真正的新手,刚刚开始学习编程——我选择Python3作为我的第一语言。所以请宽大点:) 我已经试着自己寻找答案,但没有成功。 更好或更正确的“风格”是什么。运行时是否可能有差异。谢谢大家!

第1版:

def newUsername(db):
    isUser = True
    while isUser:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            isUser = False
    return username
def newUsername(db):
    while True:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            return username
第2版:

def newUsername(db):
    isUser = True
    while isUser:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            isUser = False
    return username
def newUsername(db):
    while True:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            return username

第二个版本会更好


这更好,因为您没有使用额外的变量&也减少了一个表达式,您可以在其中为该变量赋值。

因为这是工作代码,您可以将其发布到@o11c Sry,这是我关于堆栈溢出的第一个问题。我会记住这一点。顺便说一句,我还能移动帖子吗,还是太晚了。谢谢。我也这么想,但我不确定。