python之數值型別

2022-09-16 00:54:08 字數 2772 閱讀 2358

數值型別分為int型別和float型別#和其他程式語言一樣

python中+,-,*,/的使用同其他程式語言也一樣,遵循先乘除後加減,括號內先執行,略微不同的是/,稍後有介紹

>>> 2 + 2

4>>> 50 - 5*6

20>>> (50 - 5*6) / 4

5.0//the operators +, -, * and / work just like in most other languages (for example, pascal or c);

>>> 17 / 3  # classic division returns a float

5.666666666666667

//此處『/』預設返回的是浮點數型別(相比c語言中的'/',都是整數預設返回整數,類似求整操作,而python中返回float,取整操作為『//』)

>>>

>>> 17 // 3 # floor division discards the fractional part

5//python中的取整操作

>>> 17 % 3 # the % operator returns the remainder of the division

2 //返回餘數

>>> 5 * 3 + 2 # result * divisor + remainder

17

#x**y等於power(x,y)

>>> 5 ** 2 # 5 squared

25//5的平方

>>> 2 ** 7 # 2 to the power of 7

128//2的7次方

>>> width = 20

>>>width

20>>> height = 5 * 9

>>>height

45>>> width * height

900//『=』等號用以給變數賦值

>>> n  # try to access an undefined variable

traceback (most recent call last):

file "", line 1, in nameerror: name 'n' is not defined

//如果沒有事前定義變數,直接使用會出錯

>>> tax = 12.5 / 100

>>> price = 100.50

>>> price * tax

12.5625

>>> price + _

113.0625

//此處_值為上一步price * tax的值12.5625

>>> round(_, 2)

113.06

//此處_值為上一步列印出來的113.0625,操作保留2位小數

t = true

f = false

print(type(t)) # prints ""

print(t and f) # logical and; prints "false"

print(t or f) # logical or; prints "true"

print(not t) # logical not; prints "false"

print(t != f) # logical xor; prints "true"

hello = 'hello' # string literals can use single quotes

world = "world" # or double quotes; it does not matter.

print(hello) # prints "hello"

print(len(hello)) # string length; prints "5"

hw = hello + ' ' + world # string concatenation

print(hw) # prints "hello world"

hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting

print(hw12) # prints "hello world 12"

s = "hello"

print(s.capitalize()) # capitalize a string; prints "hello"

print(s.upper()) # convert a string to uppercase; prints "hello"

print(s.rjust(7)) # right-justify a string, padding with spaces;

print(s.center(7)) # center a string, padding with spaces;

print(s.replace('l', '(ell)'))

# replace all instances of one substring with another substring

# prints "he(ell)(ell)o"

print(' world '.strip()) # strip leading and trailing whitespace;

Python 數值型別

python中有三種數值型別 數值型別變數會在賦值時自動建立 示例 a 6 int b 8.8 float c 6j complex要驗證python 物件的型別,可使用type 函式 示例 print type a print type b print type c 整型,是乙個整數,正或負,沒有...

Python 數值型別

1 變數命名規則 推薦 使用 具有固定含義的英語單詞縮寫,srv server skt socket,一般以posix命名規則為主 駝峰命名法 大駝峰 名稱以單詞自動連線,且每個單詞首字母均大寫 小駝峰 類似大駝峰,但每乙個字母小寫 posix寫法 多個單詞用下劃線連線 單詞全小寫 my first...

Python 數值型別

python中有三種數值型別 數值型別變數會在賦值時自動建立 示例 a 6 int b 8.8 float c 6j complex要驗證python 物件的型別,可使用type 函式 示例 print type a print type b print type c 整型,是乙個整數,正或負,沒有...