Python基礎學習筆記

1.Python程序結構:

輸入 - 處理 - 輸出 


輸出語句:

print() 函數

format 格式化函數

format(val, 'm.nf')

m.nf,m是佔位符,

例如:

print(format(12.243, '3.2f')) -> _12.24
print(format(0.1245, '2.2%')) -> 12.45%


輸入語句:

raw_input([promot]) 返回的是字符串

re = raw_input()
type(re) -> <type 'str'># 獲取變量的類型
nRe = int(re) 類型轉換


2.變量解析

Python的變量是一個標識符,指向的意思,相當於C++裏面的指針。

是可變的,因此無需進行類型定義。

id()函數可以獲取對象的地址

>>> x = 12
>>> id(x)
20148988
>>> x = 13
>>> id(x)
20148976
>>> y = x# y跟x一樣指向13數據塊
>>> id(y)
20148976
>>>


3.函數庫

type() # 查看變量類型

id() # 返回對象地址

print() # 打印

raw_input() # 輸入字符

help() # 查看函數用法

函數庫導入

import math


math數學函數庫

math.pi 3.1415...

math.sin( math.pi / 6 ) = 0.5

math.pow( 3, 4) == 3**4 == 81


import os #系統相關函數庫

os.getcwd() #獲取當前目錄

os.listdir(os.getcwd()) # 獲取目錄下的文件夾和文件


import socket # 網絡庫函數

ip = socket.gethostbyname('www.baidu.com')

print ip -> 111.13.100.91



4.使用第三方函數庫

網絡上下載第三方庫,例如httplib2

https://pypi.python.org/pypi/httplib2#downloads

下載解壓,執行命令python setup.py install就可以安裝第三方庫了。

python添加到環境變量


import webbrowser as web  # 導入庫別名


5.自定義函數

關鍵字def

# 無參數

def test_fun():

print 'hell world'

# 2個參數

def test_fun_ret(val1, val2):

return val1 + val2 # 函數返回值

# 預定值函數

def test_fun_ret(val1, val2, val3 = 5):

return val1 + val2 + val3

# 函數可以返回多個返回值

def test_fun(n1, n2):

    print n1,

    print n2

    n = n1 + n2

    m = n1 * n2

    p = n1 - n2

    e = n1 ** n2

    return n, m, p, e, 'return'


# 返回時,可以採用以下方式進行獲取多個返回值

val1, val2, val3, val4, val5 = test_fun(10, 2) 

# 或者直接一個變量,此時re爲一個元組(tuple)

re  = test_fun(10, 2) 

print re[0], re[1], re[2], re[3]

type(re) -> <type 'tuple'>


6.if語句

if condition:

statement1

statement2

elif condition2:

statement1

else:

statement1


7.while循環語句

while condition:

statement1

statement2

..

[break]

[continue]

else:

statement1

i = 0

s = 0

# and 邏輯與, or邏輯或

while 1 and i < 100:

s = s + i

i = i + 1

print s

8.中文註釋

# -*- coding:utf-8 -*-

# Python 文件裏面要寫中文,必須添加一行聲明文件編碼的註釋,否則python會默認使用ASCII編碼



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