1. 程式人生 > >python3.6循環使用

python3.6循環使用

python python循環

一、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:結束循環

python3.6循環使用