Python6種基礎資料型別 數字型別

2021-09-25 02:21:09 字數 3641 閱讀 3552

標籤:python

複習:a=input(「請輸入乙個數字」)

a=int(a)

print(a,type(a))

#number(數字)

#string(字串)

#list(列表)

#tuple(元組)

#sets(集合)

#dict(字典)

int float complex

int:整數型別float:浮點型

#小數的簡寫方式:省略0,必須一連串都是0

eg. c=.5 ===> c=0.5

d=4. ===> d=4.0000000

#科學計數法

當小數中含有科學計數法中的符號依舊表示浮點型

eg. e=2.9979e8

d=6.18e-1

complex:複數型別 1+2j (含有實部和虛部)

一般用在資料統計和演算法運算

a = complex(1,2)

b = complex(2,3)

c = 3+4j

print(a*b)

-數字型別是不可變型別,一旦建立在記憶體中無法被修改,以後對它的所有操作都是產生乙個新的值

a = 「1」

a = int(a)

a = float(a)

complex(a,b) --> a+bj

+ - * /

% 取餘運算 eg.print(9%8)

// 取整運算 eg.print(9//8)

** 冪運算 eg. print(2**3)

運算優先順序:() 冪運算 * / + -

abs() 取絕對值函式

eg.

a =-1

a =abs

(a)print

(a)

max(a,b,c····) 取最大值

min(a,b,c····) 取最小值

eg.

print

(max(12

,23,32

,21))

print

(min(12

,23,32

,21))

pow(a,b) -->a**b ,a 的 b次方

eg.print(pow(2,3))

round(a,n) 對a四捨五入,保留到第n位小數

eg.print(round(3.1415926,3))

bin() 轉化成二進位制 0b開頭的字串

hex() 轉化成十六進製制 0x開頭的字串

封裝在math模組中的函式

第一步匯入模組 import math

模組名.函式名

ceil() 向上取整

eg.

import math

a =2.1 a = math.ceil(a)

print

(a)print

(math.ceil(2)

)

floor() 向下取整

eg.

import math

a =2.8

a = math.floor(a)

print

(a)print

(math.floor(2)

)

sqrt() 得到算數平方根

eg.

import math

print

(math.sqrt(2)

)

math.pi 常量π

eg.

import math

a = math.pi

print

(a)

三角函式:sin cos tan

eg.

import math

a = math.sin(math.pi)

print

(a)

封裝在隨機數模組裡 random

randint(a,b) 隨機生成a~b之間的乙個整數

random 隨機生成乙個0~1之間的小數

eg.

import random

a = random.randint(1,

10)b = random.random(

)print

(a," , "

,b)

python中的資料型別有複數型別:real+imagj

eg:1+2j等等,使用的時候發現了這個問題:

>>

>1+

2j.real

1.0>>

>1+

2j.imag

3.0>>

>1+

(2j).imag

3.0>>

> a=1+

2j>>

> a.real

1.0>>

> a.imag

2.0>>

>1+

2j(1+

2j)>>

>(1

+2j).imag

2.0>>

>1+

2j.imag

3.0

說明如果複數型別不加括號,會把複數的實數部分和虛數部分的數字相加作為虛部,因此寫複數一定要注意寫成(a+bj)的形式,括號不能不寫。

屬性及其描述

num.real 該複數的實數部分

num.imag 該複數的虛數部分

num.conjugat() 返回該複數的共軛算數

complex()函式

complex()函式用於建立乙個複數或者將乙個數或字串轉換為複數形式,其返回值為乙個複數。該函式的語法為:

class complex(real,imag)

其中,real可以為int、long、float或字串型別;而image只能為int、long、或float型別。

注意:如果第乙個引數為字串,第二個引數必須省略,若第乙個引數為其他型別,則第二個引數可以選擇。例項:

>>> 1 + 1j

(1+1j)

>>> complex(1) #數字

(1+0j)

>>> complex(1,2)

(1+2j)

>>> complex("1") #當做字串處理

(1+0j)

complex("1 + 2j") #會出錯,+號兩邊不能有空格,否則會報錯

>>> complex("1+2.0j")

(1+2j)

第乙個引數為字串,還新增第二個引數時會報錯:

>>> complex("x",15)

typeerror: complex() can't take second arg if first is a string

python 6種標準資料型別

1 數值 數值 a 123 b 567 a,b 123,567 print a,b print a b print a b print a b print a b 2.字串 字串 c hello shagua print c print c 1 3 print c 3 1 輸出序列 print c ...

Python 標準資料型別6種

usr bin python3 python的基本語法和資料型別 python3中 一行有多個語句,用分號分割 print aaa print bbb 基本資料型別,移除long型別 print type 1 print type 1.0 print type str 允許多個變數連續賦值 a b ...

Python 標準資料型別6種

usr bin python3 python的基本語法和資料型別 python3中 一行有多個語句,用分號分割 print aaa print bbb 基本資料型別,移除long型別 print type 1 print type 1.0 print type str 允許多個變數連續賦值 a b ...