1. 程式人生 > >while循環 ,格式化輸出及運算符

while循環 ,格式化輸出及運算符

位數 lse not in not 代碼 32位 () 馬化騰 true

1. 循環
while 條件:
代碼塊(循環體)
else:
當上面的條件為假. 才會執行

執行順序:
判斷條件是否為真. 如果真. 執行循環體. 然後再次判斷條件....直到循環條件為假. 程序退出

死循環
count = 1
while count <= 5:
    print("噴死你..")

count = 1
while count < 101:
    print(count)
    count = count + 2

2. break和continue

讓用戶一直去輸入內容, 並打印. 直到用戶輸入q的時候退出程序
while True:
    content = input("請輸入一句話,(輸入q退出程序):")
    if content == ‘q‘:
        break   # 打斷. 終止當前本層循環
    print(content)


flag = True
while flag:
    content = input("請輸入一句話,(輸入q退出程序):")
    if content == ‘q‘:
        flag = False   # 打斷. 終止當前本層循環
    print(content)
else:
    print("123")

break: 停止當前本層循環
continue: 停止當前本次循環. 繼續執行下一次循環

3. 格式化輸出
%s 占位字符串
%d 占位數字

name = input("請輸入名字:")
age = input("請輸入年齡:")
job = input("請輸入你的工作:")
hobby = input("請輸入你的愛好:")

s = ‘‘‘------------ info of %s -----------
Name  : %s
Age   : %s
job   : %s
Hobbie: %s
------------- end -----------------‘‘‘ % (name, name, age, job, hobby)

print(s)

如果你的字符串中出現了%s這樣的格式化的內容. 後面的%都認為是格式化.如果想要使用%. 需要轉義 %%
print("我叫%s, 我已經學習了2%%的python了" % (name))

4. 邏輯運算符
and: 並且, 兩端同時為真. 結果才能是真
or: 或者, 有一個是真. 結果就是真
not: 非真既假, 非假既真

順序: () => not => and => or

x or y:
如果x是零, 輸出y
如果x是非零, 輸出x

print(1 or 2) # 1
print(1 or 0) # 1
print(0 or 1) # 1
print(0 or 2) # 2

x and or 結果和or相反

True: 非零
False: 零

print(3>4 or 4<3  and  1==1) # False
print(1 < 2  and  3 < 4 or 1>2 ) # True
print(1 > 1  and  3 < 4 or 4 > 5 and  2 > 1  and  9 > 8 or 7 < 6) # False
print(not  2 > 1  and 3 < 4  or 4 > 5  and 2 > 1  and 9 > 8  or 7 < 6) # False
print(1 and 2>3) #False   2>3是假,False看成0,
                1 and false 把如果是or 返回1,and和or相反,返回false

5. 編碼
1. ascii. 最早的編碼. 至今還在使用. 8位一個字節(字符)
2. GBK. 國標碼. 16位2個字節.
3. unicode. 萬國碼. 32位4個字節
4. UTF-8. 可變長度的unicode.
英文: 8位. 1個字節
歐洲文字:16位. 2個字節
漢字. 24位. 3個字節

6 in 和 not in

content = input("請輸入你的評論:")
if "馬化騰" not in content:
    print("你的言論不和諧")
else:
    print(content)

練習:判斷一個數是否是質數

n = int(input("請輸入一個數:"))
if n == 1:
    print("不知道是不是")
else:
    count = 2
    while count <= n-1: # 質數只能被1和自身整除. 讓這個數從2開始除. 一直除到n-1 如果除開了 一定不是質數 到最後還沒有除開. 一定是質數
        if n % count == 0:
            print("你這個不是質數")
            break
        count = count + 1
    else:
        print("是一個質數")

  

while循環 ,格式化輸出及運算符