Python之while循環


基本語法:

while  condition:

    code...

else:

   code...

示例:

1.輸出1到10,不包括7

n = 1
while n < 11:
     if n == 7:
         pass
     else:
         print(n)
     n = n+1

2.計算1-100所有數之和

n = 1
s = 0
while n < 101:
    s = s + n
    n = n + 1
print(s)

3.計算1-2+3-4+5-6...99

n = 1
s = 0
while n < 101:
    if n % 2 == 0:
        s = s - n
    else:
        s = s + n
    n = n + 1
print(s)

 continue   &&    break

continue表示跳出當前循環,不再執行之后的代碼

break表示跳出整個循環

 示例4:輸入登陸用戶名密碼,只有三次輸錯的機會

count = 0
while count < 3:
    username = input("請輸入用戶名:")
    password = input("請輸入密碼:")
    if username == "wangjie" and password == "123456":
        print("歡迎登陸")
        break
    else:
        print("用戶名或密碼錯誤")
    count = count + 1
else:
    print("請稍后再試")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM