1. 程式人生 > >python入門(二)isinstance、內建函式、常用運算等

python入門(二)isinstance、內建函式、常用運算等

 

1.    isinstance(變數名,型別)                           #判斷什麼型別

 

ps:

只支援輸入兩個引數,輸入3個引數會報錯

>>> isinstance (a,int,float)

Traceack (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: isinstance expected 2 arguments, got 3

 

>>> isinstance (a,int)

True

 

>>> b=1.1234

>>> isinstance(b,float)

True

 

>>> c=1+1j

>>> isinstance(c,complex)

True

 

>>> d=[1,2,3,4]

>>> isinstance(d,list)

True

 

>>> e=(1,2,3,4)

>>> isinstance (e,tuple)

True

 

>>> f="abc"

>>> isinstance(f,str)

True

 

>>> g={1:4,a:b}

>>> isinstance(g,dict)

True

 

>>> h={1,2,3,4}

>>> type(h)

<class 'set'>

>>> isinstance (h,set)

True

 

>>> isinstance(False,bool)

True

 

>>> isinstance(False,bool)

True

 

>>> bool(a)

True

 

>>> bool(1)

True

>>> bool(-1)

True

>>> bool(1+1j)

True

 

>>> bool([])

False

>>> bool({})

False

>>> bool( )

False

>>> bool("")

False

>>> bool(0)

False

 

用途:在實現函式時,需要傳入一些變數,因為python是弱語言型別,實現不需要宣告變數型別就可以使用的。賦予什麼值,就預設為什麼型別。所以在給函式傳參的時候,事先要判斷一下是什麼型別。如果型別不對,就會報錯兒。

>>> a=1

>>> b="2"

>>> a+b

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

 

>>> type=1.2

>>> isinstance(type,float)

True

>>> type(1.2)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'float' object is not callable

型別錯誤:'float'物件不可呼叫

原因:將關鍵字賦了值,在程式碼裡重內建型別.新定義了type,如type=1.2,這時你自己呼叫的是程式碼裡定義的type,而不是python

解決方法:刪掉重新定義的關鍵字del type

 

 

2.    常用的計算:

1)    加+

>>> 1+1

2

2)    減-

>>> 1-1

0

3)    乘*

>>> 56*2

112

4)    除/

>>> 1/2

0.5

>>> 1/3

0.3333333333333333             #自動取小數,而非取整。

>>> 1/0

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero  #0不能做除數:

 

5)    取整//

>>> 1//2

0

>>> 9//2

4

>>> 9//10

0                               #不存在四捨五入的情況,只取商。

 

6)    四捨五入round(數字,保留的位數)

>>> round(1.25,1)                #小數點要保留的位數後面如果是5,5會更加靠近偶數。

1.2                               如果5前面是偶數,那不會進位

>>> round(1.25,0)                  如果5前面是奇數,那就會進位

1.0

>>> round(1.5)                   #如果沒有寫明保留幾位,預設輸出整數

2                               保留0位和保留1的結果一樣。

>>> round(0.5)

0

>>> round(2.675,2)

2.67                            #結果都應該是2.68的,結果它偏偏是2.67,為什麼?這跟浮點數的精度有關。我們知道在機器中浮點數不一定能精確表達,因為換算成一串1和0後可能是無限位數的,機器已經做出了截斷處理。那麼在機器中儲存的2.675這個數字就比實際數字要小那麼一點點。這一點點就導致了它離2.67要更近一點點,所以保留兩位小數時就近似到了2.67。

除非對精確度沒什麼要求,否則儘量避開用round()函式

浮點數精度要求如果很高的話,請用decimal模組

>>> round(-100.55,1)             #負數也可使用round

-100.5

 

7)    取餘%

>>> 8%3

2

>>> 100%3

1

 

8)    取商取餘divmod(,)  

>>> divmod(10,3)

(3, 1)

>>> divmod(9,2)

(4, 1)

>>> divmod(9,2)[0]               #只取商

4

>>> divmod(9,2)[1]               #只取餘

1

 

9)    取最大值max

>>> max([1,2,3,45])

45

>>> max(1,2,3,45)

45

 

10) 乘方**/pow

>>> 2**3

8

>>> 2*2*2

8

>>> 10**3

1000

>>> pow(2,3)

8

>>> pow(10,3)

1000

 

11) 開方math.sqrt

>>> math.sqrt(8)

2.8284271247461903

>>> math.sqrt(4)

2.0

>>> math.pi

3.141592653589793

3.    dir(__builtins__)          #檢視內建函式

 

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

 

12) 與或非

1)    and:

>>> True and True

True

>>> True and False

False

>>> False and True

False

>>> False and False

False

>>> a=10

>>> a<5 and a<11 and isinstance (a,floassss)

False                               #floassss是一個錯誤的字元,但是依然正確輸出False,是因為前面的條件a<5為False,直接輸出False,短路了後面的字元。

>>> 1 and 9                         #如果兩邊都為真,則返回第二個值

9

>>> 5 and 3

3

 

 

2)    or:

>>> True or False

True

>>> True or True

True

>>> False or True

True

>>> False or False

False

>>> a<5 or a<11 or isinstance (a,floassss)

True                              #依然存在短路效應

 

3)    not:

>>> not False

True

>>> not True

False

>>> not(0)

True

>>> not(1)

False

>>> not[]

True

>>> not{}

True

>>> not("")

True

>>> not()

True

>>> 1 and 2 or not 3   #不加括號的情況下 not的優先順序大於and, and的優先順序大於 or

2

>>> (1 and 2) or (not 3)

2

>>> not False        #一般用這個

True

>>> not(False)       #用的是函式,但是兩者輸出結果一樣。

True

 

 

4.    help(函式名)            #檢視函式的用法

>>> help(round)

Help on built-in function round in module builtins:

 

round(...)

    round(number[, ndigits]) -> number

 

    Round a number to a given precision in decimal digits (default 0 digits).

    This returns an int when called with one argument, otherwise the

same type as the number. ndigits may be negative.

 

>>> help(pow)

Help on built-in function pow in module builtins:

 

pow(x, y, z=None, /)

    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

 

    Some types, such as ints, are able to use a more efficient algorithm when

invoked using the three argument form.

>>> pow(2,3)

8

>>> pow(10,10)

10000000000

>>> pow(2,3,2)             #2的3次方後除2取餘=0

0

>>> pow(2,3,3)             #2的3次方後除3取餘=2

2

 

 

>>> help(math)

Help on built-in module math:

 

NAME

    math

 

DESCRIPTION

    This module is always available.  It provides access to the

    mathematical functions defined by the C standard.

 

FUNCTIONS

    acos(...)

        acos(x)

 

        Return the arc cosine (measured in radians) of x.

    pow(...)

        pow(x, y)

 

        Return x**y (x to the power of y).

 

>>> math.pow(2,3)              #與pow不同的是,返回的是小數

8.0

>>> math.pow(2,3,3)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: pow expected 2 arguments, got 3  #注意,math.pow支援輸入兩個函式。

 

 

 

5.    ord                     #返回一個字串的Unicode編碼

Return the Unicode code point for a one-character string.

>>> ord("a")

97

>>> ord("z")

122

>>> ord("A")

65

>>> ord("Z")

90

 

 

6.    chr                     #返回指定序號的字元

Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

>>> chr(97)

'a'

>>> chr(65)

'A'

>>> chr(90)

'Z'

>>> chr(122)

'z'

 

7.    print                    #列印輸出

>>> print("hello world!")

hello world!                 #預設換行輸出

>>> print("hello world",end="")

hello world>>>              #增加end=” ”後,不會換行

 

8.    input                    #輸入

>>> age=input("how old are you?")

how old are you?10

>>> age

'10'

>>> type(age)

<class 'str'>                   #input獲取到的所有資料的型別均是字串

>>> age+10

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: must be str, not int  #字串和數字不能相加

>>> age+"20"

'1020'                       #兩個字串相加,是拼字串

>>> int(age)+10

20                          #將age由str強制轉換成int,可實現輸出數字的相加

 

>>> age+str(10)             #強制型別轉換,也可實現拼字串

'1010'

 

9.    if  else

>>> score=input("請輸入你的數學成績:")

請輸入你的數學成績:98

>>> if int(score)>85:

...     print("優秀")

... elif int(score)>=60 and int(score)<=85:

...     print("及格")

... else:

...     print("差")

...

優秀

 

10.  len()               #求長度

>>> len("gloaryroad")

10

 

>>> len(121212)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: object of type 'int' has no len()     #int型別沒有長度

 

>>> len(1.123)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: object of type 'float' has no len()   #float型別沒有長度

 

>>> len((1,2,3,4))

4

>>> len([1,2,3,4])

4

>>> len({1,2,2,2,2,2})

2                                        #集合中重複的元素不算長度

 

11.  ASCII碼

>>> "a">"A"

True                  #比對的是ASCII碼

a-97

A-65                  #要牢記!

知識點:

1.    集合{}與列表[]在用法上的區別:

集合值:不能重複

>>> h={1,2,3,3,4,4}           #在賦值時可以重複

>>> h

{1, 2, 3, 4}                   #在檢視時,就自動去重了。

 

列表值:可以重複

>>> i=[1,2,3,3,4,4]            #在賦值時也可以重複

>>> i

[1, 2, 3, 3, 4, 4]               #在檢視時也未去重

 

2.    元祖與列表的區別:

List是[],且是可以改變的

Tuple是(),且是不可以

 

 

小練習:

輸入一個數,如果可以被2和5整除,列印ok

>>> a=input("請輸入一個數字:")

請輸入一個數字:10

>>> if int(a)%2==0 and int(a)%5==0:

...     print ("ok")

...

ok

 

 

小練習:

輸入一個數字,如果可以被3或5整除,列印ok

>>> a=input("請輸入一個數字:")

請輸入一個數字:10

>>> if int(a)%3==0 or int(a)%5==0:

...     print ("ok")

...

ok

 

 

小練習:

如果輸入的數字不等於3,返回ok

 

方法1:

>>> a=input("請輸入一個數字:")

請輸入一個數字:4

>>> if int(a)!=3:

...     print ("ok")

...

ok

方法2:

>>> a=input("請輸入一個數字:")

請輸入一個數字:4

>>> if not(a==3):

...     print ("ok")

...

ok

 

 

小練習:

not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9

 

not 1=0

0 and 1 = 0

3 and 4 = 4

5 and 6 = 6

7 and 8 = 8

8 and 9 = 9

0 or 0 or 4 or 6 or 9 = 4

#and運算時,如果第一個為False返回第一個值,否則返回第二個值
#or  運算時,如果第一個為False返回第二個值,否則返回第一個值

 

 

小練習:

輸入一個字串,長度如果大於3列印大於3,長度小於3列印小於3,長度等於3列印等於3

>>> a=input("請輸入一個字串:")

請輸入一個字串:gloaryroad

>>> if len(a)>3:

...     print ("大於3")

... elif len(a)==3:

...     print ("等於3")

... else:

...     print ("小於3")

...

大於3