Python基礎語法
1、hello world
字符串單雙引號即可,'''或"""三引號也可以,通常用于多行文檔原生輸出。
#雙引號
>>>print "hello world"
#單引號
>>>print 'hello world'
#方法調用
>>>print('hello world')
>>>print("hello world")
#,號結尾不換行打印
>>>print "hello world" ,
2、編寫python腳本與中文亂碼
print(100)
print('中國人')
$>python?test.py
#-*- coding:utf-8 -*-
print(100)
print('中國人')
$>python?test.py
3、變量無序聲明,拿來即用
#無需定義變量
>>>x = 1000
>>>print(x)
4、縮進格式定義代碼塊
#以縮進方式代表代碼塊
if True :
pass
print "hello world1"
else :
print "hello world2"
5、一條語句換行
x = 1 + \
2 + \
3 + \
4
6、String
s = 'hello world'
s = "hello world"
#格式原樣輸出,可用于注釋
s = """
hello world
hello world
hello world
hello world
"""
#定義unicode字符方式
s = u"hello \u0061"
s = "hello world"
print s[0] ?#
print s[2:4] #ll,前包后不包
print s[2:] ?#llo world
print s[:4] ?#hell
print s[:-1] #hello worl
print s[:] ?#hello world
#重復幾遍操作
print s * 2 ?#hello worldhello world
#濾除兩邊的空格,等價于trim
" hello world ".strip(" ")
#濾除左邊的指定字符
" hello world ".lstrip(" \r\t\n")
#濾除右邊的字符
" hello world ".rstrip("\r\n;")
#a is 1 , b is 2
s = "a is %d , b is %d"%(1,2)
#a is 1 , b is 2
s = "a is {x} , b is {y}".format(x = 1 , y = 2)
7、變量定義
#變量必須初始化
a= 100
#錯誤,沒有賦值
b
#同時定義多個變量并賦值
a , b , c = 1 , 2 ,3
8、python數據類型
#int
a = 100
#float
a = 100.0
#long
a = 100L
#復數
a = 0 + 1j
#j的平方是-1
print pow(a , 2)
#string
a= "www.baidu.com"
9、list
list表示列表或數組,可以重復,有序,等同于java中的list集合,list內容可以修改。
list = [1,2,3,4]
print list[0]
print list[0:2]
print list[2:]
print list[:4]
print list[:-1]
#重復操作
print list * 2
#重新賦值
list[1] = 100
print list[1]
rows = [1,2,3,4,5,6,7,8,9]
cols = [1,2,3,4,5,6,7,8,9]
#for循環,輸出99表格
for r in rows :
for c in range(1 , r+1) :
if c <= r :
print str(c)+"x" + str(r) + "=" + str(c * r) + str("\t"),
range是范圍對象,指定起始(包括)、結束(不包括)和步長。
# 1,3,5,7,9
r = range(1 , 10 , 2)
#默認步長1
r = range(1 , 4)
10、元組
元組類似于數據表中的一條記錄,每個組員有不同的類型,內容不能修改,使用()表示。
t = (1 , "tom" , 12)
#訪問第一個組員
print t[0]
print t[2:]
#錯誤,不可以賦值
t[1] = "tomas"
11、字典
字典等同于java中的map,使用kv方式存儲。通過key查找v。使用{}構造。
d = {1:"tom1" , 2 : "tom2" , 3 : "tom3"}
#使用的key,不是下標
print d[1]
#可以修改值
d[1] = "tomas"
d = {1:"tom1" , 2 : "tom2" , 3 : "tom3"}
#遍歷所有keys
for k in d.keys():
print k
#遍歷所有values
for v in d.values():
print v
#遍歷所有條目
for k,v in d.items():
print "%d -> %s"%(k,v)
#遍歷所有條目2
for e in d.items():
print "%d -> %s"%(e.key(),e.value())
12、類型轉換
#str()轉成字符創
print str(100) + "2000"
#int()
print int('100') + 200
#float()
print float('100')
#eval()將字符串表示的表達式轉換成表達式運算
print(eval("1 + (1 - (1 * (1 / (1 + 2))))"))
#將對象轉換成string表示
print repr(d)
list = [1,1,1,2,2,3]
set = set(list) ? ?#不重復集合
print set
13、set
set不重復,可以使用list集合來創建set集合。
list = [1,1,1,2,2,3]
#1,2,3
set = set(list)
14、運算符
print 1 + 2
print 1 - 2
print 1 * 2
print 1 / 2 ? ? ? ? #整除
print 1 % 2 ? #取模
print 2 ** 3 ? ? ? ?#冪運算 8
print 1.0 / 2 ? ? ? #小數除 0.5
print 1.0 // 2 ? ? ?#整除 ? 0
15 、進制變換
print hex(97) ? #轉換成十六進制串 ?0x61
print oct(97) ? #轉換成八進制串 ? ?0141
print chr(97) ? #將ascii轉換成字符 a
16、位運算
print 0 & -1 #0
print 0 | -1 #-1
print 0 ^ -1 #-1
print 1 << 1 #2
print -1 >> 1 #-1 ,有符號移動
17、邏輯運算
print True and False #and
print True or False ?#or
print not False ? #not
18、成員運算
list = [1,2,3,4]
print 1 in list ?#True
19、身份運算
身份運算和==相似,“\=\=”判斷對象內容是否相同,is判斷對象是否是同一對象。
a = [1,2,3,4]
b = a[:]
print a is b #False ,不是同一對象
print a == b #True ?,內容相同
20、條件語句
條件語句語法是if ... elif ... else ..。
age = 30
if age < 18 :
print "少年"
elif age > 50:
print "老年"
else :
print "中年"
21、循環
list = [1,2,3,4]
for x in list:
print x
#實現9x9乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print str(col) + "x" + str(row) + "=" + str(col * row) + "\t",
col += 1
row += 1
#百錢買百雞問題
#公雞數
cock = 0
#母雞數
hen = 0
#小雞數
chicken = 0
for x in range(0, 20 + 1):
for y in range(0, 34):
for z in range(0, 301, 3):
sum = x * 5 + 3 * y + z / 3
count = x + y + z
zz = z / 3
if sum == 100 and count == 100:
print "公雞 :%d,母雞:%d,小雞:%d".%(x,y,z)
22、定義函數
普通函數直接調用,不需要通過對象訪問。
#函數需要返回語句
def add(a , b) :
return a + b
#調用函數
print add(1,2)
在類中定義的函數,需要通過對象訪問。
class Foo:
def add(self , a ?, b):
return a + b ;
#調用成員函數
Foo().add(1,2) ;
#*args表示任何多個無名參數,它是一個tuple
#**kwargs表示關鍵字參數,它是一個dict
def foo(*args,**kwargs):
print 'args=',args
print 'kwargs=',kwargs
print '**********************'
#調用
foo(1,2,3)
foo(a=1,b=2,c=3)
foo(1,2,3,a=1,b=2,c=3)
#輸出結果
args= (1, 2, 3)
kwargs= {}
**********************
args= ()
kwargs= {'a': 1, 'c': 3, 'b': 2}
**********************
args= (1, 2, 3)
kwargs= {'a': 1, 'c': 3, 'b': 2}
23、IO操作
# -*-coding:utf-8-*-
f = open("d:\java\1.txt")
lines = f.readlines()
for l in lines:
print l ,
str = \
"""
helll world
helll world
helll world
helll world
helll world
"""
#寫入文件 mode=r | wb |
# w : overwrite覆蓋模式
# a : append追加模式
f2 = open("d:\\java\\2.txt" ,mode="ab")
f2.write(str)
f2.close()
#重命名文件
import os
os.renames("d:\\java\\2.txt" , "d:\\java\\2222.txt")
os.remove("d:\\java\\2222.txt")
os.mkdir()
dir = open("d:\\")
#列出目錄信息
list = os.listdir("d:\\")
for e in list:
print e
#導入其他模塊的成員
from util import *
print add(1,2)
24、模塊判斷與參數提取
#判斷當前文件是否直接運行,還是被其他引用
#直接運行的時候值為"__main__"
if __name__ == '__main__':
print 'hello world'
通過sys的args屬性提取參數列表:
import sys
#提取腳本執行時的參數
arr = sys.args
arr[0]
print?getattr(obj?,?"name")
25、日期函數
import datetime
datetime.datetime.now()
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'''
strftime(format[, tuple]) -> string
將指定的struct_time(默認為當前時間),根據指定的格式化字符串輸出
python中時間日期格式化符號:
%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鐘數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天為星期的開始
%w 星期(0-6),星期天為星期的開始
%W 一年中的星期數(00-53)星期一為星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身
'''
Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。