Python內建函數用法

來源:互聯網
上載者:User

標籤: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內建函數用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.