您的位置:首页 > 编程语言 > Python开发

一个例子使用条件和循环

2017-03-30 16:25 363 查看
一个例子结合使用while和for、if和else、break和continue,看看他们之间的联系和区别:

def func():
valid=False
count=3
while count>0:
input1=input('Enter password:')
for each in passwordlist:
if input1==each:
valid=True
break
if not valid:
print("Erorr Input!")
count-=1
if count == 0:
return print('invalid input more than 3')
continue
else:
return print('pass success!')

>>> passwordlist=['123456','123','12','1234']
>>> func()
Enter password:1
Erorr Input!
Enter password:2
Erorr Input!
Enter password:3
Erorr Input!
invalid input more than 3
>>> func()
Enter password:123
pass success!


上面的代码还可以使用while-else语句实现,如下面:

(ps:但是我们一般不这样写代码,也不推荐这样写代码,while-else和for-else语句的写法不够清晰,对于不是Python程序员或者Python新手来说不够直观且容易让人误解,而Python语言不就是应该简单直接吗。)

def func():
valid=False
count=3
while count>0:
input1=input('Enter password:')
for each in passwordlist:
if input1==each:
valid=True
break
if not valid:
print("Erorr Input!")
count-=1
continue
else:
return print('pass success!')
else:
return print('invalid input more than 3')
#retrun虽然可以不用,但是毕竟是个函数有个return更友好
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐