跳到主要內容


Python-變數

Python

資料型態概念說明:

參考資料型態概念-變數內容

Python的資料型態分為無型態、布林數、整數、複數、浮點數、字串六種,None為變數沒存任何狀態,在整數上有四種形式分別為十進位、二進位、八進位、十六進位,在浮點數有兩種表示法分別為小數形式、科學記號形式,字串預設為utf8格式,支援ascii、big5等,如果遇到檔案不是標準的格式建議搜尋一下看是否支援。
Python又有容器資料型態,又可看為資料結構有串列、字典、Tuple、Set四種。
  • 無型態:None
  • 布林數:True、False
  • 整數:10、0b01、0o10、0xAA
  • 複數:1+1j
  • 浮點數:1.1、1e+10
  • 字串:'string'
  • 串列:List = [1,2,3]
  • 字典:{1:1,2:2,:3:3},{1:'1',2:'2',:3:'3'},{'1':'1','2':'2',:'3':'3'}
  • Tuple:(1,2,3),('1','2','3')
  • Set:{'a','b'},{1,2}

基本語法

在直譯器下可以直接使用以下語法進行測試
None
True
False
10
0b10
0o10
0xAA
1+1j
1.1
1e+10
'string'

再用type函式進行檢視各種型態
type(None)
type(True)
type(False)
type(10)
type(0b10)
type(0o10)
type(0xAA)
type(1+1j)
type(1.1)
type(1e+10)
type('string')
type("string')
type('''string string string''')

變數定義

  • 無型態:a = None
  • 布林數:a = True
  • 整數:a = 10
  • 複數:a = 1+1j
  • 浮點數:a = 1.1
  • 字串:a = 'string'
在用type函數去測試a變數的型態

數值運算

      整數、複數、浮點數都適用。

  1. 加法:1+2
  2. 乘法:3*2
  3. 減法:2-1
  4. 除法:2/3
  5. 餘數:3%2
  6. 次方運算:2**2
  7. 除法商取整數:3//2


邏輯運算

  1. and:True and True
  2. or  :True or False
  3. not:not True

比較運算

  1. 大於:2 > 1
  2. 大於等於:2 >= 2
  3. 等於: 2 == 2
  4. 小於: 2 < 1
  5. 小於等於: 2 <= 1

位元運算

a=0b00110011
b=0b00111100

  1. and:bin(a&b)
  2. or  :bin(a|b)
  3. not:bin(~a)
  4. xor:bin(a^b)
  5. shift to left:bin(a<<2)
  6. shift to right:bin(2>>a)

指派運算

      指派運算就是賦予變數數值的運算,如數字運算指派或是位元運算指派可以減少程式撰寫內容,以加法為例如原本a=0,而a+1並存入a,寫成 a = a + 1,可以縮減成 a+=1,其他運算也是使用相同寫法,
  1. 等於指派:a = 2
  2. 數字運算指派: a += 2
  3. 位元運算指派: a >>= 2

字串運算

  • 字串串連:str1 + str2
  • 字串重複:str ** 2
  • 獲取字串特定位置資料: str[0]、str[1:4]、str[-1]>
串列
用中括號包著,可以當作堆疊、佇列,中間使用逗號分隔。

字典

用大括號包著,中間使用逗號分隔,index可以數字、字串。

Tuple

用小括號包著,中間使用逗號分隔。

Set

其儲存內容不能夠重複,用大括弧包著,中間使用逗號分隔,可以用集合概念來運算。

容器資料型態的運算

  • 判斷資料是否存於容器內 : 'a' in list1
  • 判斷資料是否不存於容器內:'a' not in list1

變數定義

在Python這個語言是不需要先行定義變數的的性態的,如要存整數只要a=2即可,也是所謂的泛型

資料型態轉換

數值轉換


float->int::nt(3.14)

int->float:flaot(3)
negative->positive:abs(-3)
int->complex:complex(3)
flaot->complex:complex(3.14)

資料結構轉換

list -> dict
list -> tuple
list -> set

list4 =[['a','we'],['b','are'],['c','a'],['d','family']]
dict2 = dict(list4)
print(dict2)

list5 = [2,3,4,3,43,'232']
tup1 = tuple(list5)
tup2 = tuple(list4)
print(tup1)
print(tup2)

list1 = [2,3,44,3,3,3,33,3,3,23]
set1 = set(list1)
print(set1)
dict -> list
dict -> tuple

dict4 = {'a':1,'b':2,'c':3}
list8 = list(dict4.keys())
print(list8)
list9 = list(dict4.values())
print(list9)


dict5 = {'age':23,'name':'zhangsan','school':'ssdsd','money':230.2323}
tup5 = tuple(dict5)
print(tup5)
tup6 = tuple(dict5.values())
print(tup6)



tuple -> list

tuple -> dict
tuple -> set

tup7 = ('232','23232',2323,'weasdfasd')
list9 = list(tup7)
print(list9)
tup9 = (('a',1),('b',2),('c',3),('d',4))
dict6 = dict(tup9)
print(dict6)
tup8 = ('2323','sdfsdf','2323','sdds','wwe','2323',23,23.33)
set6 = set(tup8)
print(set6)


set -> tuple

set -> list



set4 = set('asdfasdfasdf323')
tup3 = tuple(set4)
print(tup3)
set5 = set([2,3,43,43,433,323,2,43])
tup4 = tuple(set5)
print(tup4)


set2 = set('asdfasdfs2323sdfasdf')
list6 = list(set2)
print(list6)


 投影片-slideshare:Python_變數
 影片-youtube:Python_變數
 程式碼-Github:Python_變數  
下一單元:Python-條件敘述

留言

這個網誌中的熱門文章

Python-程式優化設計-module

class Objects, values and types CPython implementation detail:  For CPython,  The standard type hierarchy User-defined functions __doc__ The function’s documentation string, or  None  if unavailable; not inherited by subclasses Writable __name__ The function’s name Writable __qualname__ The function’s  qualified name New in version 3.3. Writable __module__ The name of the module the function was defined in, or  None  if unavailable. Writable __defaults__ A tuple containing default argument values for those arguments that have defaults, or  None  if no arguments have a default value Writable __code__ The code object representing the compiled function body. Writable __globals__ A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined. Read-only __dict__ The namespace supporting arbitrary function attributes. Writable __closure__ None ...

python-設計模式-原型模式

python 設計模式 原型模式 import copy  class Prototype:     def __init__(self):        self.obj = {}     def Registor(self, key,new_obj):        self.obj[key] = new_obj     def UnRegistor(self, key):        del self.obj[key]    def DeepClone(self, name, **attr):        obj_clone = copy.deepcopy(self.obj.get(name))        obj_clone.__dict__.update(attr)        return obj_clone     def Clone(self, name, **attr):        obj_clone = copy.copy(self.obj.get(name))        obj_clone.__dict__.update(attr)        return obj_clone  class a:     def __init__(self):        self.name = ['a1','a2']  class b:     def __init__(self):        self.name = 'b'...

Python-資料庫-mysql-sqlalchemy

Python 資料庫 mysql-sqlalchemy 安裝 Linux、mac : pip3 install SQLAlchemy windows     :之後補充 第一部分 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory', echo=False) Base = declarative_base() Session = sessionmaker(bind=engine) 第二部分 from test_sqlalchemy import * from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr(self): return "<User(name={})>".format(self.name) 第三部分 from test_sqlalchemy import * from build_model import * Base.metadata.create_all(engine) user1 = User(name='user1', fullname='user1', password='user1') user2 = User(name='user2', fullname='user2...