Python入門

變量

1、定義方式

  • 下劃線(推薦使用) age_of_oldboy = 56
  • 變量名只能是 字母、數字或下劃線的任意組合
  • 變量名的第一個字符不能是數字
  • 關鍵字不能聲明爲變量名['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

2、id、type、value、is、in、hash

  • 身份:即內存地址,能夠用id()來獲取
  • 類型:決定了該對象保存的類型,須要遵循什麼規則,可用type()來獲取該數據類型
  • 值:對象的保存的的真實數據
  • 等號比較的是value
  • is比較的是id
  • id相同,意味着type和value一定相同
  • value相同type確定相同,但id可能不一樣
  • 可變:值變,id不變。可變==不可hash
  • 不可變:值變,id就變。不可變==可hash
  • is運算符用於比較兩個對象的身份
  • in主要用來判斷某一元素是否在某種元素集合中
  • 可hash的就是不可變數據類型,不可hash的就是可變數據類型

3、類型分類

  • 可變類型:在id不變的狀況下,value能夠變,則稱爲可變類型,如列表,字典
  • 不可變類型:value一旦改變,id也改變,則稱爲不可變類型(id變,意味着建立了新的內存空間)

常量

  • 常量即指不變的量,如圓周率 3.1415926..., 在Python中沒有一個專門的語法表明常量,程序員約定俗成用變量名所有大寫表明常量AREAS = 56

程序交互

  • 在python3中 input:用戶輸入任何值,都存成字符串類型
?
1
2
age = input ( 'your age:' ).strip()
print (age, type (age))  #18 <class 'str'>

1、文件頭

  • #!/usr/bin/env python
  • # -*- coding: utf-8 -*-

2、註釋

  • 代碼註釋分單行和多行註釋, 單行註釋用#
  • 多行註釋能夠用三對雙引號""" """

range

  • range用來指定範圍,生成指定的數字。
?
1
2
3
4
5
6
7
for item in range ( 5 , 10 , 2 ):
     print (item)
"""
5
7
9
"""

基本數據類型

  • 數據即變量的值,變量的是用來反映/保持狀態以及狀態變化的,毫無疑問針對不一樣的狀態就應該用不一樣類型的數據去標識

1、數字

一、int整型

  • 定義:age=10 #age=int(10)
  • 用於標識:年齡,等級,身份證號,qq號,個數

2.float浮點型

  • 定義:salary=3.1 #salary=float(3.1)
  • 用於標識:工資,身高,體重

2、布爾

  • 判斷一個條件成立時,用True標識,不成立則用False標識
  • *****None,0,空(空字符串,空列表,空字典等)三種狀況下布爾值爲False*****

3、字符串

  • 定義:name='tom' #name=str('tom')
  • 用於標識:描述性的內容,如姓名,性別,國籍,種族
  • 加了引號的字符就是字符串類型,單引號、雙引號、多引號都同樣,注意單雙引號的嵌套
?
1
2
3
4
5
6
7
8
s = "watch ,'套路'"
#多行字符串必須用多引號
msg = '''
種一棵樹最好的時間是十年前,其次是如今。
全部的成功都是你行動之後對你行動的獎勵。
'''
print (s)  #watch ,'套路'
print (msg)

4、列表

  • 在[]內用逗號分隔,能夠存放n個任意類型的值
  • 定義:students=['tom','rose','jack',] #students=list(['tom','rose','jack',])
  • 用於標識:存儲多個值的狀況,好比一我的有多個愛好
  • 列表嵌套和取值
?
1
2
students_info = [[ 'tom' , 18 ,[ 'sing' ,]],[ 'rose' , 18 ,[ 'play' , 'sleep' ]]]
print (students_info[ 0 ][ 2 ][ 0 ]) #取出第一個學生的第一個愛好 #sing

5、字典

  • 能夠存放多個任意類型的值,又能夠規定值的映射關係的類型
  • 在{}內用逗號分隔,能夠存放多個key:value的值,value能夠是任意類型
  • 定義:info={'name':'tom','age':18,'gender':18} #info=dict({'name':'tom','age':18,'gender':18})
  • 用於標識:存儲多個值的狀況,每一個值都有惟一一個對應的key,能夠更爲方便高效地取值
  • 字典嵌套和取值
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
info = {
     'name' : 'tom' ,
     'hobbies' :[ 'sing' , 'sleep' ],
     'company' :{
         'name' : 'google' ,
         'type' : 'it' ,
         'fund' : 8000000000 ,
     }
}
print (info[ 'company' ][ 'fund' ]) #取公司現金儲備 #8000000000
 
students = [
     { 'name' : 'tom' , 'age' : 18 , 'hobbies' :[ 'sing' , 'play' ]},
     { 'name' : 'rose' , 'age' : 88 , 'hobbies' :[ 'read' , 'sleep' ]},
     { 'name' : 'jack' , 'age' : 99 , 'hobbies' :[ 'swim' , 'watchTV' , 'talk' ]},
]
print (students[ 2 ][ 'hobbies' ][ 1 ]) #取第3個學生的第2個愛好watchTV

流程控制之if...else

?
1
2
3
4
5
6
7
8
9
10
11
12
"""
rose --> 超級管理員
tom  --> 普通管理員
其餘 --> 普通用戶
"""
name = input ( '請輸入用戶名字:' ).strip()
if name = = 'rose' :
     print ( '超級管理員' )
elif name = = 'tom' :
     print ( '普通管理員' )
else :
     print ( '普通用戶' )

流程控制之while循環

1、條件循環

?
1
2
3
4
5
count = 0
while count < = 10 :
     if count % 2 = = 0 :
         print ( 'loop' ,count)
     count + = 1

2、死循環

?
1
2
while True :
     print ( 'hello world' )

3、循環嵌套與tag

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
name = 'tom'
password = '123'
 
tag = True
while tag:
     inp_name = input ( '用戶名: ' ).strip()
     inp_pwd = input ( '密碼: ' ).strip()
     if inp_name = = name and inp_pwd = = password:
         while tag:
             cmd = input ( '>>: ' )
             if not cmd: continue
             if cmd = = 'q' :
                 tag = False
                 continue
             print ( 'run <%s>' % cmd)
     else :
         print ( '用戶名或密碼錯誤' )

4、break與continue

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#break用於退出本層循環
while True :
     print ( 'go...' )
     break
     print ( 'stop' )
#只打印go...  就退出了,下面的 print('stop')根本不執行
 
#continue用於退出本次循環,繼續下一次循環
while True :
     print ( 'go...' )
     continue
     print ( 'stop' )
 
#打印go...  就退出本次循環,本次循環下面的 print('stop')根原本不及執行,就繼續下一次循環,全部一直打印 go... 也就是死循環了

5、while+else和for+else

  • 其它語言else 通常只與if 搭配不一樣
  • 在Python 中還有個while ...else 語句和for ...else 語句
  • while 後面的else 做用是指當while 循環正常執行完,中間沒有被break 停止的話,就會執行else後面的語句
  • for 後面的else 做用是指當for 循環正常執行完,中間沒有被break 停止的話,就會執行else後面的語句
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
count = 0
while count < = 5 :
     count + = 1
     print ( "Loop" ,count)
else :
     print ( "循環正常執行完啦" )
print ( "-----out of while loop ------" )
"""
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦
-----out of while loop ------
"""
 
#若是執行過程當中被break,就不會執行else的語句
count = 0
while count < = 5 :
     count + = 1
     if count = = 3 : break
     print ( "Loop" ,count)
else :
     print ( "循環正常執行完啦" )
print ( "-----out of while loop ------" )
 
"""
Loop 1
Loop 2
-----out of while loop ------
"""

流程控制之for循環

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
for i in range ( 1 , 10 ):
     for j in range ( 1 ,i + 1 ):
         print ( '%s*%s=%s' % (i,j,i * j),end = ' ' )
     print ()
 
"""
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
"""
 
 
max_level = 6
for cur_level in range ( 1 ,max_level + 1 ):
     for i in range (max_level - cur_level):
         print ( ' ' ,end = '') #在一行中連續打印多個空格
     for j in range ( 2 * cur_level - 1 ):
         print ( '*' ,end = '') #在一行中連續打印多個空格
     print ()
 
"""
      *
     ***
    *****
   *******
  *********
***********
"""

規範代碼

斷點調試

無需爲程序全部代碼加斷點,只須要在關鍵代碼加上斷點,以debug模式調試時,程序會停在斷點處。python

基本運算符

1、算數元算:

  

2、比較運算

  

3、賦值運算符

  

4、邏輯運算

  

5、成員運算

  

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#字符串
st = "abcdefg"
s = "d"
if s in st:
     print ( "in st" )
else :
     print ( "not in st" )
 
#列表
lis = [ 1 , 2 , 3 , 4 ]
li = 5
if li in lis:
     print ( "in lis" )
else :
     print ( "not in lis" )
 
#元組
tup = ( 1 , 2 , 3 , 4 )
t = 2
if t in tup:
     print ( "in tup" )
else :
     print ( "not in tup" )
 
#字典 判斷的是key
dic = { 'name' : 'tom' , 'age' : 18 }
d = 'name'
if d in dic:
     print ( "in dic" )
else :
     print ( "not in dic" )
 
#集合
sett = { 18 , 'age' , 'name' , 20 }
se = 'name'
if se in sett:
     print ( "in sett" )
else :
     print ( "not in sett" )

6、其餘

#格式:
  設置顏色開始 :\033[顯示方式;前景色;背景色m
#說明:
前景色            背景色           顏色
---------------------------------------
30                40              黑色
31                41              紅色
32                42              綠色
33                43              黃色
34                44              藍色
35                45              紫紅色
36                46              青藍色
37                47              白色
顯示方式           意義
-------------------------
0                終端默認設置
1                高亮顯示
4                使用下劃線
5                閃爍
7                反白顯示
8                不可見
 
#例子:
\033[1;31;40m    <!--1-高亮顯示 31-前景色紅色  40-背景色黑色-->
\033[0m          <!--採用終端默認設置,即取消顏色設置-->


print('\033[0;32;40m歡迎使用學生選課系統\033[0m')
try:
    num = int(input('請輸入數字選擇功能 :'))
except Exception as e:
    print('\033[31m對不起!您輸入的內容有誤~\033[0m')
顏色

相關文章
相關標籤/搜索