1. 程式人生 > >Python內置函數用法

Python內置函數用法

tao python span art ... color dict 三位數 div

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])
...
d
i
c
t
i
o
n
a
r
y
View Code

練習實例1:

題目:有四個數字:1、2、3、4,能組成多少個互不相同且無重復數字的三位數?各是多少?

程序分析:可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去 掉不滿足條件的排列。

技術分享圖片
#!/usr/bin/env python
# -*- coding:utf-8 -*-

#例子1
for 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 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 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_pop1
print "第二次刪除的項為:",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內置函數用法