Python學習筆記

2021-07-28 07:12:46 字數 2857 閱讀 1932

python學習中…

《a byte of python 3》學習摘要

chapter 7 控制流

7.1 if語句

number = 20

guess = int(input('enter an integer ='))

if guess == number:

print('congratulations!')

print('(沒錢)')

elif guess > number:

print('it is higher')

else:

print('it is lower')

print('done')

輸出

>>> 

enter an integer =15

it is lower

done

>>> ******************************== restart ******************************==

>>>

enter an integer =80

it is higher

done

>>> ******************************== restart ******************************==

>>>

enter an integer =20

congratulations!

(沒錢)

done

elif 從句,它事實上把兩個相關聯的if else-if else 語句合併為乙個if-elif-else 語句。這使得程式更加簡單,並且減少了所需的縮排數量。

注:if else elif 後面都要跟有冒號。

7.2 while語句

number = 32

running = true

while running:

guess = int(input('enter an integer ='))

if guess == number:

print('you win')

running = false

elif guess < number:

print('lower')

else:

print('higher')

else:

print('the loop is over')

print('done')

輸出

enter an

integer =98

higher

enter an

integer =88

higher

enter an

integer =1

lower

enter an

integer =32

you win

the loop is over

done

7.3 for迴圈

for i in range(1, 10):

print(i)

else:

print('over')

輸出

>>> 12

3456

789over

range(1,5) 給出序列[1, 2, 3, 4]。預設地, range 的步長

為1。如果為range 提供第三個數,那麼它將成為步長。

for i in range(1, 10, 3):

print(i)

else:

print('over')

輸出

>>> 14

7over

>>>

7.4 break語句

while

true:

s = input('enter something:')

if s == 'quit':

break

else:

print('the length is:',len(s))

print('done')

輸出

enter something:my

name

is anna

the length

is: 15

enter something:quit

done

7.5 continue語句

while

true:

s = input("enter something =")

if s == 'quit':

print('the loop is over')

break

if len(s) < 5:

print('it is too short')

continue

print('it is enough')

輸出

>>> 

enter something =hello liner

it is enough

enter something =as

it is too short

enter something =quit

the loop is over

>>>

continue 語句被用來告訴python 跳過當前迴圈塊中的剩餘語句,然後繼續進行下一輪迴圈。

python教學筆記 python學習筆記(一)

1.eval 函式 eval是單詞evaluate的縮寫,就是 求.的值的意思。eval 函式的作用是把str轉換成list,dict,tuple.li 1 1,2,3 print eval li 1 di 1 print eval di 1 tu 1 2,4,6 print eval tu 1 執...

python學習筆記

coding utf 8 coding utf 8 應該像八股文一樣在每個指令碼的頭部宣告,這是個忠告 為了解決中文相容問題,同時你應該選擇支援 unicode 編碼的編輯器環境,保證在執行指令碼中的每個漢字都是使用 utf 8 編碼過的。cdays 5 exercise 3.py 求0 100之間...

Python 學習筆記

python 學習筆記 def run print running.def execute method method execute run result running.condition false test yes,is true if condition else no,is false ...