Python之while循環

基本語法:code

while  condition:input

    code...it

else:io

   code...循環

示例:語法

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

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

2.計算1-100全部數之和word

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

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 = 0while count < 3:    username = input("請輸入用戶名:")    password = input("請輸入密碼:")    if username == "wangjie" and password == "123456":        print("歡迎登錄")        break    else:        print("用戶名或密碼錯誤")    count = count + 1else:    print("請稍後再試")

相關文章
相關標籤/搜索