手记

python3.6循环使用

一、if判断

首先来测试一下这段代码:

>>> password = input("please your password:")

please your password:123                  //此时密码的输入是明文,不安全

可以导入getpass模块来避免这种情况的出现

>>> import getpass

>>> password = getpass.getpass("please your password:")

please your password:                     //此时再输入密码就不会显示了



刚才输入了密码,我现在想要判断一下输入的密码是正确还是错误,如果对就打印欢迎,不正确的话就提示错误

#!/usr/local/python/bin/python3.6

_username = "test"

_password = "test"

username = input("please your username:")

password = input("please your password:")

if username == _username and password == _password:

  print("welcome user {name} login...".format(name=username))

else:

  print("Password mistake!!!")


进行测试:

[root@salt-master ~]# python3.6 user.py 

please your username:test

please your password:test

welcome user test login...

[root@salt-master ~]# python3.6 user.py 

please your username:sa

please your password:sas

Password mistake!!!


下面再用if判断写一个猜测年龄的小脚本

#!/usr/local/python/bin/python3.6

year_old = 66

guess_age = int(input("please input age:"))

if guess_age == year_old:

  print("Yes")

elif guess_age > year_old:

  print("big")

else:

  print("small")


测试:

[root@salt-master ~]# python3.6 user.py 

please input age:66

Yes

[root@salt-master ~]# python3.6 user.py 

please input age:23

small

[root@salt-master ~]# python3.6 user.py 

please input age:100

big


二、while循环

上面的代码执行起来的话,只猜测一次就退出,现在实现一下让用户猜三次,如果猜不对才退出

#!/usr/local/python/bin/python3.6

year_old = 66

count = 0

while count < 3:

  guess_age = int(input("please input age:"))

  if guess_age == year_old:

    print("Yes")

    break

  elif guess_age > year_old:

    print("big")

  else:

    print("small")

  count += 1

else:

  print("you have too....")


三、for循环

如果把上面的小脚本改成for循环的话,应该写成以下代码:

#!/usr/local/python/bin/python3.6

year_old = 66

for i in range(3):

  guess_age = int(input("please input age:"))

  if guess_age == year_old:

    print("Yes")

    break

  elif guess_age > year_old:

    print("big")

  else:

    print("small")

else:

  print("you have too....")


小知识:range()可以设置步长,比如打印偶数

for i in range(0,10,2):

  print(i)


以上代码还可以改为输入三次之后询问用户还要不要继续玩儿的效果:

#!/usr/local/python/bin/python3.6

year_old = 66

count = 0

while count < 3:

  guess_age = int(input("please input age:"))

  if guess_age == year_old:

    print("Yes")

    break

  elif guess_age > year_old:

    print("big")

  else:

    print("small")

  count += 1

  if count == 3:

    aa = input("do you want to keep guess:")

    if aa != "N":

      count = 0

else:

  print("you have too....")


continue:跳出本次循环,进入下一次循环

break:结束循环

0人推荐
随时随地看视频
慕课网APP