標籤:err dom 練習 body 輸入 view 程式 需要 port
1.Python raw_input()函數
作用: raw_input() 用來擷取控制台的輸入,將所有輸入作為字串看待,返回字串類型。
注意:
input() 和 raw_input() 這兩個函數均能接收 字串 ,但 raw_input() 直接讀取控制台的輸入(任何類型的輸入它都可以接收)。而對於 input() ,它希望能夠讀取一個合法的 python 運算式,即你輸入字串的時候必須使用引號將它括起來,否則它會引發一個 SyntaxError 。
除非對 input() 有特別需要,否則一般情況下我們都是推薦使用 raw_input() 來與使用者互動。
python3 裡 input() 預設接收到的是 str 類型。
View Code
2.Python range()函數
文法:
range(start,stop[,step])
參數說明:
- start: 計數從 start 開始。預設是從 0 開始。例如range(5)等價於range(0, 5);
- stop: 計數到 stop 結束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5
- step:步長,預設為1。例如:range(0, 5) 等價於 range(0, 5, 1)
例子:
>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1,11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> range(0,20,5) #步長為5[0, 5, 10, 15]>>> range(0,14,3)[0, 3, 6, 9, 12]>>> range(0,-10,-2) #負數[0, -2, -4, -6, -8]>>> range(0)[]>>> range(1,0)[]>>> range(5,1)[]
View Code
以下是 range 在 for 中的使用,迴圈出dictionary 的每個字母
>>> x=‘dictionary‘>>> for i in range(len(x)):... print(x[i])...dictionary
View Code
練習執行個體1:
題目:有四個數字:1、2、3、4,能組成多少個互不相同且無重複數位三位元?各是多少?
程式分析:可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去 掉不滿足條件的排列。
#!/usr/bin/env python# -*- coding:utf-8 -*-#例子1for i in range(1,5): for j in range(1,5): for k in range(1,5): if (i!=j) and (i!=k) and (j!=k): print i,j,k#輸出:1 2 31 2 41 3 21 3 41 4 21 4 32 1 32 1 42 3 12 3 42 4 12 4 33 1 23 1 43 2 13 2 43 4 13 4 24 1 24 1 34 2 14 2 34 3 14 3 2
View Code
3.List中的pop()方法:pop() 函數用於移除列表中的一個元素(預設最後一個元素),並且返回該元素的值。
#!/usr/bin/env python# -*- coding:UTF-8 -*-list=[‘abc‘,‘jack‘,‘Taobao‘]list_pop1=list.pop(0)list_pop2=list.pop(1)print "第一次刪除的項為:",list_pop1print "第二次刪除的項為:",list_pop2 #注意:第一次刪除後,剩餘的列表 元素中list.pop(1)為‘Taobao‘,不是‘jack‘print "列表現在為:",list
View Code
4.Python random模組中的uniform()函數和randint()函數
uniform()方法將隨機產生一個實數,在[x,y)範圍內,即不包括y,文法:
import random
random.uniform(x,y)
randint()函數隨機產生一個範圍內的整數N,在[a,b]範圍內,a<=N<=b。
文法:
import random
random.randint(0,9)
Python內建函數用法