python全部语法_python基本语法
python:跨平臺、面向對象的動態編程語言
發布時間:1991年
發明:guido
van rossum
python的語言特點
1、開源免費
2、腳本語言,解析執行
3、跨平臺
4、簡潔美觀
5、一切皆對象
6、可擴展的膠水語言
解析執行原理:
1、編輯文本文件
2、意識編譯字節碼,形成pyc源碼
3、在pvm虛擬機執行
4、在cpu執行,打印到屏幕
解析器cpython、jpython、ironpython
------------------------------------------------------------------------------------------------------------------
1、python環境準備
執行命令:python
--version 打印出版本號
2、python安裝
1、預安裝:linux、unix、macos一般都是自帶安裝python
2、源碼安裝
3、安裝包安裝
rpm、msi(windows)
a)、源碼編譯安裝
tar
xjvf python-3.3.2.tar.bz2
cd
python-3.3.2
./configure
make
make
install
ln
-s /usr/loacl/bin/python3 /usr/bin/python
3、基本語法
1、>>>
print('hello')
>>>
是主提示符
2、
... print 'hello'
...是輔助提示符
3、>>>
exit()
退出
root@localhost#
python
('hello')
hello
>>>if
1 + 1 == 2: 冒號不是分號
'hello'
...
hello
>>>exit()就退出來了。
4、python的自省
>>>
help(str)遇到問題可以help
>>>type('hello')
>>>isinstance('hello',str)
>>>dir(str)
5、模塊導入
1、import
m
print m.plus(1,2)
2、from
m import plus
plus(1,2)
示例:m.py ,new.py
def plus(a,b):import m
return a + bprint m.plus(1,2)
def plus2():
exit()打印結果 3
6、導入系統模塊
1、import
sys.path
from os import *
7、導入私有模塊
1、import sys
2、 path
= '/root/dir/' 把模塊的目錄添加到path中,方便查找加載
3、 sys.path.append(path)或者直接sys.path.append("root/dir/")
4、 from
m import plus2
-------------------------------------------------------------------------------------------------------------------
8、變量的使用
內建數據類型:
1、boolean--> exam_is_pass = true
2、integer--> person_number = 100
3、float--> weight = 65.18
4、string--> greet_msg = "welcome to visit
itercast"
5、list--> score_list = [12, 25, 56, 78]順序存儲相當于數組,字符串和數字混合
6、tuple -->
index_tuple(0, 1, 2, 3, 4)不能改變的數組
7、dict -->age_dict
= { 'bob': 18, 'lucy': 16} 字典
8、set--> index_set = set([0, 1, 2, 3])集合,和數學里面的集合一樣沒有順序
9、none
空字符串‘ ’ 、空元組()、空列表[]、空字典{} ,在邏輯判斷的時候都是false
>>>
'i love "itercast"'
'i love "itercast"'
>>>
"i love \"itercast\""
'i
love "itercast"'
>>>
str1 = '''i love
...
"itercast"
...
'''
>>>
str1
'i
love \n"itercast"\n'
字符串和list之間的轉換:
>>>
list1 = str1.split()
>>>
list1
>>>
['i', 'love', '"itercast"']
往list里面添加字符串
list1.append('!')
or ("!")
往list里面添加數字
list1.append(8)
------------------------------------------------------------------------------------------------------------
9、 字典使用:
字典名 =
{’關鍵字‘:值,...}
字典名.get('關鍵字',默認值)
賦值:自頂名['關鍵字']
= 值
字典名.keys()將關鍵字返回出一個列表
字典名.values()將字典的值返回出一個列表
字典名.copy()age_dict2 = age_dict.copy()
>>>
del age_dict['bob']
>>>
age_dict2.popitem()彈出第一項
>>>
bob in age_dict2
在腳本里面寫:
dirt = {'bob':10, 'lucy':20, 'jim':30}定義字典
print dirt['bob']
dirt['abc']=40添加元素
dirt
deldirt['bob']
字典內置函數&方法
Python字典包含了以下內置函數:
1、cmp(dict1,
dict2):比較兩個字典元素。
2、len(dict):計算字典元素個數,即鍵的總數。
3、str(dict):輸出字典可打印的字符串表示。
4、type(variable):返回輸入的變量類型,如果變量是字典就返回字典類型。
Python字典包含了以下內置方法:
1、radiansdict.clear():刪除字典內所有元素
2、radiansdict.copy():返回一個字典的淺復制
3、radiansdict.fromkeys():創建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值
4、radiansdict.get(key,
default=None):返回指定鍵的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果鍵在字典dict里返回true,否則返回false
6、radiansdict.items():以列表返回可遍歷的(鍵,
值) 元組數組
7、radiansdict.keys():以列表返回一個字典所有的鍵
8、radiansdict.setdefault(key,
default=None):和get()類似, 但如果鍵不已經存在于字典中,將會添加鍵并將值設為default
9、radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict里
10、radiansdict.values():以列表返回字典中的所有值
false
實例:
>>>dirt
= { 'bob':10, 'lucy':20, 10:10}
>>>
dirt['jim'] = 30
返回關鍵字的列表
>>>
dirt.keys()
['jim',
'bob', 10, 'lucy']
返回值得列表
>>>
dirt.values()
[30,
10, 10, 20]
list復制:
>>>
dir1 = dirt.copy()
>>>
dir1.values()
[10,
30, 10, 20]
>>>
dir1.keys()
['bob',
'jim', 10, 'lucy']
list刪除關鍵字
del
dirt['bob']
list彈出第一個關鍵字
dirt.popitem()
Python表達式:
=賦值
==等于
>,<大于號和小于號
>=,<=大于等于和小于等于
And邏輯與
Or邏輯或
Not邏輯非
if
1==1 and 2==2:
print 'hello'
else:
print 'error'
python的邏輯分支:
If條件判斷語句:if條件判斷語句:
. . . .。。。。
else:elif條件判斷語句:
. . . .。。。。
. . . .else:
.。。。。。。。
Python沒有switch語句
ifsys.argv[1] == '-s':
time.sleep(10);
elif sys.argv[1] == '-q':
quit();
else:
print('error')
例子:
sex =
'boy'
age =
19
if
sex == 'boy':
print 'hi,boy'
elif
sex == 'girl':
if age < 18:
print 'hi,girl'
else:
print 'hi,lady'
else:
print 'weather is good'
'end'
python循環:
for循環:
例一:
IndentationError: unexpected indent
>>>
for i in ['bob', 'lucy', 'jim']:
...print i,
...
bob
lucy jim
>>>
for i in ['bob', 'lucy', 'jim']:
...print i
...
bob
lucy
jim
例二:
for name,age in (('afe',18), ('fleajf',16)):
>>>
for name,age in (('afe',18), ('fleajf',16)):
...print name,age
...
afe 18
fleajf
16
While循環:
>>>
i = 0
>>>
while i < 10:
...print i,
...i += 1
迭代器:
>>>
obj = range(5)
>>> itera = iter(obj)相當于obj._iter_()
>>>
try:
...while True:
...print itera.next(),
...
except StopIteration:
...pass
...
0 1 2
3 4
python函數定義:
1、不帶參數函數的定義
函數定義
函數調用
def函數名()
函數體。。。
函數名()
實例:def
welcome():
print( ' I love it')
2、帶參數函數的定義
函數定義
函數調用
def函數名(參數列表):
函數體。。。
函數名(參數列表)
例子:
>>> def
welcome(who,action):
...print(who + ' ' + action)
...
>>>
welcome('wang','nihao')
wang nihao
3、Python變成參數:參數會自動轉變成一參數命名的元組或字典
函數定義1
函數定義2
def函數名(*args):轉換成元組
函數體。。。
函數名(v1,v2,v3)
def函數名(**args):轉換成字典
函數名。。。
函數名(k1=v1,k2=v2)
例1:
例2
例1:
>>> def
welcome(*args):
...print args
...
>>>
welcome('jim','is','thinking')
('jim', 'is',
'thinking')
>>> def
welcome(**args):
...print args
...
>>>
welcome(who='jim',state='is',action='thinking')
{'action': 'thinking',
'state': 'is', 'who': 'jim'}
4、參數默認值
>>>
def welcome(who,state='is',action='sleeping'):
...print who,state,action
...
>>>
welcome('jim','was')
jim
was sleeping
第一個參數必須有,第二個和第三個可以沒有,沒有就用默認值
5、函數的返回值
def函數名(函數列表)
def函數名(參數列表)
def函數名(參數列表)
函數體。。。
函數體。。。
函數體。。。
return
obj
return
返回obj對象
返回none
返回none
面向對象基礎--類
Python種一切都是對象,雷和對象是面向對象的基礎
定義類
類的實例化
class類名稱():默認繼承object
·····
class類名稱(father):
·····
實例名=類名稱()
例子:
定義一個類
實例化monk類
查看實例化類的類型
class monk:
def__init__(self,name,age):
self.name = name
self.age = age
yc_monk
= mokn('yancan',20)
yc_monk.name #成員變量
yc_monk._class_
type(yc_monk)
類的方法:
類的方法
實例化方法的調用
class類名稱
。。。
def方法名(self,參數列表)
。。。
實例名.方法名(參數列表)
例子
class monk:
def
__init__(self, name, age):
self.name
= name
self.age
= age
def
net(self):
"i love webo"
def
play(self, str):
"play with",str
m1 =
monk("yancan", 19)
print m1.name
m1.net()
m1.play("monkey")
python文件IO
print方法:輸出數據到標準輸出
raw_ipnut方法:從標準輸入讀數據
從標準輸入讀取內容
將用戶輸入的信息輸出到標準輸出
>>>
input = raw_input('prompt@ ')
prompt@nihaowoshi
>>>
print(input)
nihaowoshi
file類-讀文件
創建一個file類實例f,以只讀模式打開文本文件
>>>f = file('1.txt', 'r')
通過f實例讀取文件內容
>>>
f.read()
關閉文件實例,釋放資源
>>>
f.close()
使用open函數打開文件,返回一個file類實例
>>>
f= open('1.txt', 'r')
讀取全部,返回字符串
>>>
f.read()
一次只讀取一行
>>>
f.readline()
讀取全部返回列表
>>>
f.readlines()
已追加模式打開文件,返回一個file類實例
>>>
f = file('1.txt','a')
向文件寫入字符串
>>>
f.write('I love you\nEnd')
刷新緩沖區
>>>
f.flush()
>>>
f.close()
"r"------->只讀
"w"------->只寫
"a"------->追加
"b"------->二進制
"r+","a+"------->更新
總結
以上是生活随笔為你收集整理的python全部语法_python基本语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode4两数相加
- 下一篇: 编译3.0的linux内核,Ubuntu