1. 程式人生 > >一步一步學Python-基礎篇

一步一步學Python-基礎篇

class 亂碼 eight mov 字符串 if else 10個 顯示 ref

1、安裝

  地址:https://www.python.org/downloads/windows/

  安裝完成過後,配置環境變量,比如:path後面計入;C:\Python27(可能需要重啟一下)

  然後cmd輸入python,顯示如下,說明安裝成功

  技術分享

2、基礎知識(記錄寫特列)

  0、空值是Python裏一個特殊的值,用None表示。None不能理解為0,因為0是有意義的,而None是一個特殊的空值。

  1、字符串:用單引號或雙引號都行,比較特殊的是三個單引號是多行文本,中間可以換行

  2、如果字符串包含很多轉移的字符,可以用r‘23\wer\2‘可以加r前綴,相當於c#裏的@

  3、如果打印有亂碼可以使用print u‘中文‘加u前綴,以Unicode表示的字符串

  4、u、r這些可以結合起來用,比如:
    ur‘‘‘Python的Unicode字符串支持"中文",         

      "日文",         

      "韓文"等多種語言‘‘‘

  5、py文件可以填一行# -*- coding: utf-8 -*-告訴Python解析器,以utf-8編碼讀取源碼

  6、if else語法

if age >= 18:
     print adult
else:
     if age >= 6:
          
print teenager  else:    print kid

  7、循環

L = [Adam, Lisa, Bart]
  for name in L:
       print name
N = 10
x = 0
while x < N:
    print x
    x = x + 1
sum = 0
x = 1
while True:
    sum = sum + x
    x = x + 1
    if x > 100:
        break
print sum
for x in L:
    if x < 60:
        continue
    sum = sum + x
    n = n + 1
for x in [A, B, C]:
    for y in [1, 2, 3]:
        print x + y

  8、字典

# 字典特點 dict的第一個特點是查找速度快,無論dict有10個元素還是10萬個元素,查找速度都一樣。而list的查找速度隨著元素增加而逐漸下降。不過dict的查找速度快不是沒有代價的,dict的缺點是占用內存大,還會浪費很多內容,list正好相反,占用內存小,但是查找速度慢。由於dict是按 key 查找,所以,在一個dict中,key不能重復
# 定義字典
d = {
    Adam: 95,
    Lisa: 85,
    Bart: 59
}
# 訪問
print d[Adam]
# 判斷key是否存在
if Paul in d:
    print d[Paul]
#使用dict本身提供的一個 get 方法,在Key不存在的時候,返回None
print d.get(Bart)
#更新
 d[Paul] = 72
#遍歷
for key in d:
    print key
#遍歷value
for v in d.values():
    print v

  9、元祖

t = (Adam, Lisa, Bart)
t[0] = Paul
#因為()既可以表示tuple,又可以作為括號表示運算時的優先級
>>> t = (1,)
>>> print t
(1,)
# 元祖可包含list
 t = (a, b, [A, B])
L = t[2]
>>> L[0] = X
>>> L[1] = Y
>>> print t
(a, b, [X, Y])

 10、set

#由於set存儲的是無序集合,所以我們沒法通過索引來訪問。
 s = set([Adam, Lisa, Bart, Paul])
#用 in 操作符判斷,返回True
Bart in s 
#遍歷
s = set([Adam, Lisa, Bart])
for name in s:
print name
#添加
s = set([1, 2, 3])
s.add(4)
#不存在remove會報錯
s.remove(7)

 11、函數

# 返回多值
import math
def move(x, y, step, angle):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
#調用
x, y = move(100, 100, 60, math.pi / 6)
print x, y
151.961524227 70.0
#遞歸
def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
#默認參數
def power(x, n=2,c=4):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
#跳過調用
power(1,c=3)
#可變參數,直接把變量 args 看成一個 tuple 就好了
def fn(*args):
    print args

def func(a, b=5, c=10):
print ‘a is‘, a, ‘and b is‘, b, ‘and c is‘, c

func(3, 7)
func(25, c=24)
func(c=50, a=100)

 11、DocStrings

def printMax(x, y):
    ‘‘‘打印我的文檔內容Prints the maximum of two numbers.
The two values must be integers.‘‘‘
    x = int(x) # convert to integers, if possible
    y = int(y)

    if x > y:
        print x, is maximum
    else:
        print y, is maximum

printMax(3, 5)
print printMax.__doc__ 

說明:部分內容來自慕課網和Python手冊內容

一步一步學Python-基礎篇