Python編程

特點:

(1):易學:python關鍵字少、結構簡單、語法清晰

       易讀:沒有其他語言通常用來訪問變量、定義代碼塊和進行模式匹配的命令式符號

(2):內存管理器:內存管理是由python解釋器負責的

>>> py_str = 'python'

>>> len(py_str)-----輸出變量字符的長度

6

>>> 't' in py_str---------“t”是否在py_str變量中

True

>>> 'th' in py_str

True

>>> 'to' not in py_str

True

>>> py_str[0]----從左向右取出第一個字符

'p'

>>> py_str[5]

'n'

>>> py_str[-1]

'n'

>>> py_str[3:]

'hon'

>>> py_str[3:5]

'ho'

>>> py_str[1:6]

'ython'

>>> py_str[0:6]

'python'

>>> py_str[0:]

'python'

>>> py_str[:2]

'py'

>>> py_str[::2]---------步長值

'pto'

>>> py_str[::3]

'ph'

>>> py_str[1::3]

'yo'

>>> py_str[::-1]

'nohtyp'

>>> py_str + '   cool'------相加表示拼接

'python   cool'

>>> py_str.upper()------轉換大寫

'PYTHON'

>>> py_str.lower()------轉換小寫

'python'

>>> py_str.isdigit()----判斷是否是數字

False

>>> py_str.center(50, '#')------------居中對齊

'######################python######################'


>>> py_str.ljust(50)------左對齊

'python  


列表

>>> alist = [10, 20, 'dc', 'alice', [1,3]]



字典表示

>>> adict = {'name': 'hanjie', 'age':22}

>>> len(adict)---------兩個字符長對,看中間的逗號分隔

2

>>> adict--------箭直對類型

{'age': 22, 'name': 'hanjie'}

>>> 'name' in adict-----判斷'name'是否在adict

True

>>> adict['age'] = 21--------改變'age'的值

>>> adict

{'age': 21, 'name': 'hanjie'}

>>> adict['email'] = '[email protected]'

>>> adict

{'age': 21, 'name': 'hanjie', 'email': '[email protected]'}------增加變量


if語句:

#coding: utf8

import getpass------------------表示python中的一個模塊

username = raw_input("請輸入用戶名: ")

passwd = getpass.getpass("請輸入用戶密碼: ")---------第一個getpass表示模塊,第二個表示模塊中的一個方法

if username == "bob" and passwd == "123456":---------python中的並且和或者用“and”、“or”表示

    print "Login successful"

else:

    print "Login incorrect"


PYTHON解釋器中的判斷

>>> if 5 > 8:(python判斷是必須要冒號分隔)、if、else是評級;兩個print是一個評級;輸入else時必須要用冒號分隔

...   print 'yes'

... else:

...   print 'no'

... 

no


在python中隨機猜一個數:

#coding: utf8

import random

num = random.randint(1, 10)

answer = int(raw_input("請猜一個數: "))

if answer > num:

    print "猜大了"

elif answer < num:

    print "猜小了"

else:

    print "猜對了"

print num



Python中三引號的區別:列b = "hello,\n

                     world"     

c="""hello'

world!"""  #三引號就相當於雙引號裏面的\n,字符串越多\n就多,使用起來不方便,也不方便查看, 所以就使用三引號來實現


If語句的寫法:

#coding: utf8

import random  #導入random模塊,是產生隨機數的模塊

all_choices = ['石頭', '剪刀', '布'] #定義一個列表,將選擇添加在列表中

win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['石頭', '布']] #定一個用戶贏的列表,列表中的元素仍然是一個列表

prompt = """(0)石頭  #定義一個變量,將提示語寫入這個變量中

(1)剪刀

(2)布

請選擇(0/1/2):"""

computer = random.choice(all_choices) #隨機選一個值

ind = int(raw_input(prompt)) #因爲輸入的是字符串類型,所以將字符串轉變爲整型

player = all_choices[ind] #列表可以取下標,下標對應的列表中的值

print "Your choice: %s, Computer's choice: %s" %(player, computer) #提示信息,友好界面:相當於人出石頭、計算機出布

if player == computer: #如果兩個變量值相等

    print '\033[32;1m平局\033[0m' #輸出平局

elif [player,computer] in win_list: #如果列表在win_list中

    print '\033[31;1m你贏了\033[0m'  #輸入你贏了

else:

    print '\033[31;1m你輸了\033[0m'  #輸出你輸了



pwin = 0  #人贏的次數

cwin = 0  #電腦贏得次數

import random

all_choices = ['石頭', '剪刀', '布']

win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['石頭', '布']]

prompt = """(0)石頭

(1)剪刀

(2)布

請選擇(0/1/2):"""

while pwin < 2 and cwin < 2: #人和電腦贏的次數都不夠兩次時就的循環下面語句

    computer = random.choice(all_choices)

    ind = int(raw_input(prompt))

    player = all_choices[ind]

    print "Your choice: %s, Computer's choice: %s" %(player, computer)

    if player == computer:

        print '\033[32;1m平局\033[0m'

    elif [player,computer] in win_list:

        pwin += 1

        print '\033[31;1m你贏了\033[0m'

    else:

        cwin += 1

        print '\033[31;1m你輸了\033[0m'



Break語句的寫法:

import random

num = random.randint(1, 10)


while True:

    answer = int(raw_input("請猜一個數: "))

    if answer > num:

        print "猜大了"

    elif answer < num:

        print "猜小了"

    else:

        print "猜對了"

        break

print num


For語句的寫法:

import random

num = random.randint(1, 10)

for i in range(3):

    answer = int(raw_input("請猜一個數: "))

    if answer > num:

        print "猜大了"

    elif answer < num:

        print "猜小了"

    else:

        print "猜對了"

        break

else:

    print num

純粹if語句結構

#coding: utf8

import random

computer = random.choice(['石頭', '剪刀', '布'])

player = raw_input('請出拳頭(石頭/剪刀/布): ')

print "your choice: %s, Computer's choice: %s" %(player, computer)

if player == '石頭':

    if computer == '石頭':

        print '平局'

    elif computer == '剪刀':

         print '你贏了'

    else:

         print '你輸了'

elif player == '剪刀':

     if computer == '石頭':

         print '你輸了'

     elif computer == '剪刀':

          print '平局'

     else:

          print '你贏了'

else:

     if computer == '石頭':

         print '你贏了'

     elif computer == '剪刀':

          print '你輸了'

     else:

          print '平局'

#coding: utf8

num = int(raw_input("請輸入您的成績: "))


if num >= 90:

    print "優秀"

elif num >= 80:

    print "好"

elif num >= 70:

    print "良"

elif num >= 60:

    print "及格"

else:

    print "你要努力了"


#coding: utf8

num = int(raw_input("分數: "))

if 60 <= num < 70:

    print '及格'

elif 70 <= num < 80:

    print '良'

elif 80 <= num < 90:

    print '好'

elif num >= 90:

    print '優秀'

else:

    print '你要努力了'

sum = 0

i = 1


while i <= 100:

    sum += i

    i += 1

print sum


while i <= 100:

    sum = sum + i

    i = i + 2

print sum


result = 0

counter = 0


while counter < 100:

    counter += 1

    if counter % 2 == 1:

        continue

    result += counter

print result


sum = 0

i = 2

while i <= 100:

    sum += i

    i += 2

print sum


生成八隨機密碼: for循環

import random

all_chs = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'

result = ''

for i in range(8):

    ch = random.choice(all_chs)

    result += ch

print result


調用函數生成8位隨機密碼

import random

import string


all_chs = string.letters + string.digits #表示大小寫字母和數字的調用


def gen_pass(n=8):

    result = ''

    for i in range(n):

        ch = random.choice(all_chs)

        result += ch

    return result

if __name__ == '__main__':

    print gen_pass()

    print gen_pass(10)


將/bin/ls拷貝到/root/目錄下,簡單寫法

f1 = open('/bin/ls')

f2 = open('/root/ls', 'w')


data = f1.read()

f2.write(data)


f1.close()

f2.close()


while語句的寫法:

src_fname = '/bin/ls'  #定義源文件src_fname

dst_fname = '/root/ls' #定義目標文件dst_fname

src_fobj = open(src_fname)

dst_fobj = open(dst_fname, 'w')


while True:

    data = src_fobj.read(4096)

    if data == '':

        break

    dst_fobj.write(data)

src_fobj.close()

dst_fobj.close()



定義函數的調用的寫法:

import sys

def copy(src_fname, dst_fname):


    src_fobj = open(src_fname)

    dst_fobj = open(dst_fname, 'w')


    while True:

        data = src_fobj.read(4096)

        if data == '':

            break

        dst_fobj.write(data)


    src_fobj.close()

    dst_fobj.close()

copy(sys.argv[1], sys.argv[2])



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