python中的運算符及表達式及常用內置函數


知識內容:

1.運算符與表達式

2.for\while初步了解

3.常用內置函數

 

 

 

一、運算符與表達式

python與其他語言一樣支持大多數算數運算符、關系運算符、邏輯運算符以及位運算符,並且有和大多數語言一樣的運算符優先級。除此之外,還有一些是python獨有的運算符。

1.算術運算符

a=10, b=20

 

 

2.比較運算符

a=10, b=20

 注:  在python3中不存在<>,只在python2中存在<>

 

 

3.賦值運算符

 

 

4.邏輯運算符

and兩邊條件都成立(或都為True)時返回True,而or兩邊條件只要有一個成立(或只要一個為True)時就返回True

not就是取反,原值為True,not返回False,原值為False,not返回True

 1 >>> a = 10
 2 >>> b = 20
 3 >>> a
 4 10
 5 >>> b
 6 20
 7 >>> a == 10 and b == 20
 8 True
 9 >>> a == 10 and b == 21
10 False
11 >>> a == 10 or b == 21
12 True
13 >>> a == 11 or b == 20
14 True
15 >>> a == 11 or b == 23
16 False
17 >>> a == 0
18 False
19 >>> not a == 0
20 True

 

 

5.成員運算符

 

 

6.身份運算符

 

 

7.位運算

 

 

8.運算符優先級

 

注:

(1)除法在python中有兩種運算符: /和//,/在python2中為普通除法(地板除法),/在python3中為真除法,/和//在python2和python3中均為普通除法(地板除法)

示例:

 

(2) python中很多運算符有多重含義,在程序中運算符的具體含義取決於操作數的類型,將在后面繼續介紹。eg: +是一個比較特殊的運算符,除了用於算術加法以外,還可以用於列表、元組、字符串的連接,但不支持不同類型的對象之間相加或連接;  *也是其中比較特殊的一個運算符,不僅可以用於數值乘法,還可以用於列表、字符串、元組等類型,當列表、字符串或元組等類型變量與整數就行*運算時,表示對內容進行重復並返回重復后的新對象

示例:

 

(3)python中的比較運算符可以連用,並且比較字符串和列表也可以用比較運算符

示例:

 

(4)python中沒有C/C++中的++、--運算符,可以使用+=、-=來代替

 1 >>> a = 5
 2 >>> a++
 3   File "<stdin>", line 1
 4     a++
 5       ^
 6 SyntaxError: invalid syntax
 7 >>> a += 1
 8 >>> a
 9 6
10 >>> a--
11   File "<stdin>", line 1
12     a--
13       ^
14 SyntaxError: invalid syntax
15 >>> a-=1
16 >>> a
17 5

 

(5)python3中新增了一個新的矩陣相乘運算符@

示例:

1 import numpy  # numpy是用於科學計算的python拓展庫需要自行使用pip安裝或手動安裝
2 
3 x = numpy.ones(3)       # ones函數用於生成全1矩陣,參數表示矩陣大小
4 m = numpy.eye(3)*3      # eye函數用於生成單元矩陣
5 m[0, 2] = 5             # 設置矩陣上指定位置的值
6 m[2, 0] = 3
7 print(x @ m)
8 
9 # 輸出結果:  [6. 3. 8.]
View Code

 

 

9.表達式的概念

在python中單個任何類型的對象或常數屬於合法表達式,使用上表中的運算符將變量、常量以及對象連接起來的任意組合也屬於合法的表達式,請注意逗號(,)在python中不是運算符,而只是一個普通的分隔符

 

 

 

二、for\while初步了解

python中提供了for循環和while循環(注: 在Python中沒有do..while循環)

1. for循環

for循環的格式: 

for iterating_var in sequence: statements(s)

 

 

2.while循環

while循環的格式: 

while 判斷條件: 執行語句……

 

示例:

 1 # for
 2 # 輸出從1到10的整數:
 3 for i in range(1, 11):      # range(1, 11)是產生從1到10的整數
 4     print(i, end=' ')
 5 print()     # 換行
 6 
 7 # while
 8 # 計算1到100的和:
 9 i = 0
10 number_sum = 0
11 while i < 100:
12     i = i + 1
13     number_sum = number_sum + i
14 print(number_sum)
15 
16 # 輸出結果:
17 # 1 2 3 4 5 6 7 8 9 10 
18 # 5050

 

 

 

三、常用內置函數

1. 內置函數的概念

python中的內置函數不用導入任何模塊即可直接使用,可以在命令行中使用dir(__builtins__)查看所有內置函數

查看所有內置函數:

  1 # __author__ = "wyb"
  2 # date: 2018/3/7
  3 
  4 for item in dir(__builtins__):
  5     print(item)
  6 # python3.6上運行的結果:
  7 # ArithmeticError
  8 # AssertionError
  9 # AttributeError
 10 # BaseException
 11 # BlockingIOError
 12 # BrokenPipeError
 13 # BufferError
 14 # BytesWarning
 15 # ChildProcessError
 16 # ConnectionAbortedError
 17 # ConnectionError
 18 # ConnectionRefusedError
 19 # ConnectionResetError
 20 # DeprecationWarning
 21 # EOFError
 22 # Ellipsis
 23 # EnvironmentError
 24 # Exception
 25 # False
 26 # FileExistsError
 27 # FileNotFoundError
 28 # FloatingPointError
 29 # FutureWarning
 30 # GeneratorExit
 31 # IOError
 32 # ImportError
 33 # ImportWarning
 34 # IndentationError
 35 # IndexError
 36 # InterruptedError
 37 # IsADirectoryError
 38 # KeyError
 39 # KeyboardInterrupt
 40 # LookupError
 41 # MemoryError
 42 # ModuleNotFoundError
 43 # NameError
 44 # None
 45 # NotADirectoryError
 46 # NotImplemented
 47 # NotImplementedError
 48 # OSError
 49 # OverflowError
 50 # PendingDeprecationWarning
 51 # PermissionError
 52 # ProcessLookupError
 53 # RecursionError
 54 # ReferenceError
 55 # ResourceWarning
 56 # RuntimeError
 57 # RuntimeWarning
 58 # StopAsyncIteration
 59 # StopIteration
 60 # SyntaxError
 61 # SyntaxWarning
 62 # SystemError
 63 # SystemExit
 64 # TabError
 65 # TimeoutError
 66 # True
 67 # TypeError
 68 # UnboundLocalError
 69 # UnicodeDecodeError
 70 # UnicodeEncodeError
 71 # UnicodeError
 72 # UnicodeTranslateError
 73 # UnicodeWarning
 74 # UserWarning
 75 # ValueError
 76 # Warning
 77 # WindowsError
 78 # ZeroDivisionError
 79 # __build_class__
 80 # __debug__
 81 # __doc__
 82 # __import__
 83 # __loader__
 84 # __name__
 85 # __package__
 86 # __spec__
 87 # abs
 88 # all
 89 # any
 90 # ascii
 91 # bin
 92 # bool
 93 # bytearray
 94 # bytes
 95 # callable
 96 # chr
 97 # classmethod
 98 # compile
 99 # complex
100 # copyright
101 # credits
102 # delattr
103 # dict
104 # dir
105 # divmod
106 # enumerate
107 # eval
108 # exec
109 # exit
110 # filter
111 # float
112 # format
113 # frozenset
114 # getattr
115 # globals
116 # hasattr
117 # hash
118 # help
119 # hex
120 # id
121 # input
122 # int
123 # isinstance
124 # issubclass
125 # iter
126 # len
127 # license
128 # list
129 # locals
130 # map
131 # max
132 # memoryview
133 # min
134 # next
135 # object
136 # oct
137 # open
138 # ord
139 # pow
140 # print
141 # property
142 # quit
143 # range
144 # repr
145 # reversed
146 # round
147 # set
148 # setattr
149 # slice
150 # sorted
151 # staticmethod
152 # str
153 # sum
154 # super
155 # tuple
156 # type
157 # vars
158 zip
View Code

 

 

2.python中常見及常用的內置函數

注:

dir()函數可以查看指定模塊中包含的所有成員或者指定對象類型所支持的操作;help()函數則返回指定模塊或函數的說明文檔

 

常用內置函數示例:

 1 # __author__ = "wyb"
 2 # date: 2018/3/7
 3 
 4 number = -3
 5 print(abs(number))          # 輸出結果: 3
 6 
 7 print(all([0, -8, 3]))      # 輸出結果: False
 8 print(any([0, -8, 3]))      # 輸出結果: True
 9 
10 value = eval("3+2")         # 計算字符串中表達式的值並返回
11 print(value)                # 輸出結果: 5
12 
13 help(print)                 # 輸出結果: print的文檔(幫助信息)
14 
15 x = 3
16 y = float(x)                # 將其他類型轉換成浮點型
17 z = str(x)                  # 將其他類型轉換成字符串類型
18 print(x, y, z)              # 輸出結果: 3 3.0 3
19 print(id(x), id(y), id(z))  # 輸出x,y,z的地址信息
20 
21 s = "Hello, python!"
22 n = len(s)                  # 求字符串的長度
23 print(n)                    # 輸出結果: 14
24 
25 p = pow(3, 2)               # 求3的2次方
26 print(p)                    # 輸出結果: 9
27 
28 # zip(): 將可迭代的對象作為參數,將對象中對應的元素
29 # 打包成一個元組,然后返回這些元組組成的列表,實例如下:
30 a = [1, 2, 3]
31 b = [4, 5, 6]
32 zipped = zip(a, b)  # zipped -> [(1,4),(2,5),(3,6)]
33 print(zipped)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM