1. 程式人生 > >Python_1基礎知識

Python_1基礎知識

  1. 型別轉換
a =3
a = str(a)
type(a)	#檢視型別
<class 'str'>
  1. 輸出語句
a = 33
print('%d是a的值' % a)
  1. 斷言
    assert 這個關鍵字我們稱之為“斷言”,當這個關鍵字後邊的條件為假的時候,程式自動崩潰並丟擲AssertionError的異常。
assert 5>6
#丟擲的錯誤
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AssertionError
  1. range()
    語法:range([strat] stop[,step =1])
    range(2,10,3)
    a. 這個BIF有三個引數,其中用中括號括起來的兩個表示這兩個引數是可選的。
    b. step = 1表示第三個引數的值預設值是1.
    c.range這個BIF的作用是生成一個從start引數的值開始到stop引數的值結束的數字序列。
#for 語句
for i in range(1,10,3):
    print(i)
  1. 如果字串中需要出現單引號或雙引號:
# 使用轉義符號(\)對字串中的引號進行轉義
'Let\'s go'
# 使用不同引號
"Let's go"
# 使用三引號
'''Let's go'''
  1. 輸出原始字串
#只需要在字串前邊加一個英文字母 r 即可
path = r'C:\Program Files\FishC\Good'
# 輸出結果
'C:\\Program Files\\FishC\\Good'
#如果非要在字串的最後輸入反斜槓,可以在最後加上‘\\’
path = r'C:\Program Files\FishC\Good' '\\'
# 輸出結果
'C:\\Program Files\\FishC\\Good\\'
  1. 迴圈和分支
import random
#random模組裡randint(),它會返回一個隨機函式。
secret = random.randint(1,10)
temp = input("輸入一個數值:")
guess = int(temp)
# while語句
while guess !=secret:
    temp = input("input again")
    guess = int(temp)
    # if - else 語句
    if guess == secret:
        print("you are right")
    else:
        if guess > secret:
            print("more big")
        else:
            print("more small")
print("Game over")
# break 語句終止當前迴圈,跳出迴圈體
bingo = "right"
answer = input("Please enter your answer:")

while True:
    if answer == bingo:
        break
    answer = input('Please again enter your answer:')
#continue語句終止本輪迴圈,並開始下一輪迴圈
for i in range(10):
    if i%2 !=0:
        print(i)
        continue
    i += 2
    print(i)