輕便的python

python
解釋型語言
面嚮對象語言
跨平臺語言
簡單,使程序員集中精力於解決問題而不是語言本身。
對比:
Perl只適合小的程序,大的程序就要用python。
配置環境Windows下:
1 去官網下載合適的python版本 下載
2 傻瓜式安裝,並配置系統變量path值爲python的目錄
使用:
控制行,輸入python
或者
開始——》程序——》python——》IDLE(python GUI)
如何運行一個python文件:eg: a.py
進入文件的目錄,python a.py
即可。


>>> print('hello\'world')
hello'world
>>> print("hello")
hello
>>> print('hello")
SyntaxError: EOL while scanning string literal
>>> print('he"l')
he"l
>>> print("hello ' world!")
hello ' world!
>>> 1 + 1
2
>>> 1 * 2
2
>>> 2-3
-1
>>> 3/4
0.75
>>> 3//4
0
>>> 3%4
3
>>> 3**3
27
>>> a = 10
>>> while a < 20:
    a = a + 1
    print(a)

    
11
12
13
14
15
16
17
18
19
20
>>> print("hello python",end='!')
hello python!
>>> print("hello python",end=',')
hello python,
>>> a = 10
>>> while a < 20:
    a = a+2
    print(a,end=" ")

    
12 14 16 18 20

>>>

文件讀寫

my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text) #該語句會寫入先前定義好的 text
my_file.close()

在已有的文件中追加

append_text='\nThis is appended file.'  # 爲這行文字提前空行 "\n"
my_file=open('my file.txt','a')   # 'a'=append 以增加內容的形式打開
my_file.write(append_text)
my_file.close()
""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""
#運行後再去打開文件,會發現會增加一行代碼中定義的字符串

文件讀

file= open('my file.txt','r') 
content=file.read()  
content=file.readline()  # 讀取第一行
content=file.readlines() # 讀所有行
print(content)
""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
"""

# 之後如果使用 for 來迭代輸出:
for item in content:    
  print(item)    
 """
This is my first test.
This is the second line.
This the third line.
This is appended file.
"""


class Calculator:       #首字母要大寫,冒號不能缺
    name='Good Calculator'  #該行爲class的屬性
    price=18
    def add(self,x,y):
        print(self.name)
        result = x + y
        print(result)
    def minus(self,x,y):
        result=x-y
        print(result)
    def times(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
""""
>>> cal=Calculator()  #注意這裏運行class的時候要加"()",否則調用下面函數的時候會出現錯誤,導致無法調用.
>>> cal.name
'Good Calculator'
>>> cal.price
18
>>> cal.add(10,20)
Good Calculator
30
>>> cal.minus(10,20)
-10
>>> cal.times(10,20)
200
>>> cal.divide(10,20)
0.5
>>>
""""

__init__():python中類的構造器,雙下劃線



class Calculator:
    name='good calculator'
    price=18
    def __init__(self,name,price,hight=10,width=14,weight=16): #爲後面三個屬性設置默認值,查看運行
        self.name=name
        self.price=price
        self.h=hight
        self.wi=width
        self.we=weight

 """"
>>> c=Calculator('bad calculator',18)
>>> c.h
10
>>> c.wi
14
>>> c.we
16
>>> c.we=17
>>> c.we
17
""""
input獲取鍵盤輸入

score=int(input('Please input your score: \n'))
if score>=90:
   print('Congradulation, you get an A')
elif score >=80:
    print('You get a B')
elif score >=70:
    print('You get a C')
elif score >=60:
    print('You get a D')
else:
    print('Sorry, You are failed ')
""""
Please input your score:
100   #手動輸入
Congradulation, you get an A
""""
元組和列表
元組tuple,用小括號、或者無括號來表述,是一連串有順序的數字
a_tuple = (12, 3, 5, 15 , 6)
another_tuple = 12, 3, 5, 15 , 6

列表 list是以中括號來命名的:

a_list = [12, 3, 67, 7, 82]


迭代

for index in range(len(a_list)):
    print("index = ", index, ", number in list = ", a_list[index])
"""
index =  0 , number in list =  12
index =  1 , number in list =  3
index =  2 , number in list =  67
index =  3 , number in list =  7
index =  4 , number in list =  82
"""
for index in range(len(a_tuple)):
    print("index = ", index, ", number in tuple = ", a_tuple[index])
"""
index =  0 , number in tuple =  12
index =  1 , number in tuple =  3
index =  2 , number in tuple =  5
index =  3 , number in tuple =  15
index =  4 , number in tuple =  6
"""

列表中的常用方法

a.append(0)  # 在a的最後面追加一個0
a.insert(1,0) # 在位置1處添加0
a.remove(2) # 刪除列表中第一個出現的值爲2的項
a = [1,2,3,4,1,1,-1]
print(a[0])  # 顯示列表a的第0位的值
# 1
print(a[-1]) # 顯示列表a的最末位的值
# -1
print(a[0:3]) # 顯示列表a的從第0位 到 第2位(第3位之前) 的所有項的值
# [1, 2, 3]
print(a[5:])  # 顯示列表a的第5位及以後的所有項的值
# [1, -1]
print(a[-3:]) # 顯示列表a的倒數第3位及以後的所有項的值
# [1, 1, -1]
print(a.index(2)) # 顯示列表a中第一次出現的值爲2的項的索引
print(a.count(-1))#統計-1出現的次數

a.sort() # 默認從小到大排序
a.sort(reverse=True) #從大到小排序
還有多維列表


字典


a_list = [1,2,3,4,5,6,7,8]
d1 = {'apple':1, 'pear':2, 'orange':3}
d2 = {1:'a', 2:'b', 3:'c'}
d3 = {1:'a', 'b':2, 'c':3}
del d1['pear']
print(d1)   
# {'orange': 3, 'apple': 1}
d1['b'] = 20
print(d1)   
# {'orange': 3, 'b': 20, 'pear': 2, 'apple': 1}#這說明字典是一個無序的容器,列表是。

字典還可以以更多樣的形式出現,例如字典的元素可以是一個List,或者再是一個列表,再或者是一個function。索引需要的項目時,只需要正確指定對應的key就可以了。


下載的python模塊會被存儲到外部路徑site-packages,同樣,我們自己建的模塊也可以放到這個路徑,最後不會影響到自建模塊的調用。



set 去重

char_list = ['a', 'b', 'b', 'c', 'c', 'd']
print(set(char_list))

a b c d

unique_char = set(char_list)
unique_char.add('x')
這是在set中添加一個元素。

unique_char.clear() # 使用這種方式將直接清空set
unique_char.remove('y') # 使用這種方式,如果set中不含有要remove的元素,則程序會報錯
unique_char.discard('y') # 使用這種方式刪除元素,即使set中不含有要discard的元素,也不會報錯,只會返回原字符串。

除了上面的幾種用法,還有一種可以比較兩個set的方法:

set1 = unique_char
set2 = {'a', 'e', 'i'}
print( set.difference(set2) )


























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章