Python快速上手(三)

2022-08-02 03:54:10 字數 2150 閱讀 2510

這一節總結一下python在編碼當中的一些需要注意的地方:

一.常用

1.print語句:在螢幕上橫向輸出指定的字元,如:print 'hello world'。在互動式環境當中》是提示符,不是**的一部分。多個語句可以用逗號『,』隔開。如 print 'hello','world'.

2.if語句:

age=20                            注意:python**的縮排規則,開頭對齊的就是乙個代

if age>15:                              碼塊,縮排為四個空格。if後面用冒號,以後的

print 'your age is ',age            for、while等都是類似的。

print 'end'

3.if...else...

if age>20:

print 'your age is',age

else:

print 'your age is ',age

4.for迴圈:

l=['a','b','c','d']

for l in l:

print l

5.while迴圈:

while x<100:

print 'x'

x=x+1;

6.break語句:退出當前迴圈

x=0

while x<100:

print x

x=x+1

if x>50:

break

print x

7.continue語句:跳過當前後繼續

l=[1,2,3,4,5,6,7,8,9]

for l in l:

if l==5:

continue

print l

8.迴圈巢狀:

for a in ['a','b','c']:

for b in [1,2,3]:

print a+b

二.函式

1.python內建了很多函式,例如:求絕對值abs()、abs(100)、abs(-20),比較函式cmp(1,2),前者a,後者b,a>b返回1,a=b返回0,a文件)

2.函式的定義:

def my_abs(x):            定義函式:def 函式名 (引數):

if x>0:                            方法體....

retunr x                       返回值

else:                     呼叫函式:my_abs(-100)

return -x             返回值為空用:return none

3.函式發揮多值:

def mothed(a,b,c,d):      函式呼叫:e,f=mothed(1,2,3,4)  >>>print e ,f  >>>3 7

return a+b,c+d                 g=mothed(1,2,3,4)   >>>print g >>>(3,7) g是tuple型別

4.遞迴函式:求階乘   5*4*3*2*1

def jiecheng(x):

if x==1:

return l

return x*jiecheng(x-1)

5.定義可變引數:

def  fn(*arg0):          呼叫:def(1,2,3)      def(1)    

print arg0               傳入的資料型別其實就是tuple型別

《Python程式設計快速上手》(三)Python函式

def hello def語句,定義了乙個名為hello 的函式 print howdy 函式體 print howdy 函式體 print hello there 函式體 hello 呼叫 hello 呼叫 hello 呼叫 def hello name name為hello 函式的引數 prin...

python快速上手

資料結構 淺拷貝和深拷貝加減 乘除乘方取餘取整 與c 等程式語言不同之處在於python不需要預先設定資料型別,根據運算自動給定資料型別,這一點與matlab相似。3 2 2 表示2次方 9 10 4 除法自動賦值float型別 2.5 8 3 2 定義 python的函式定義規則與c 不同,通常以...

快速上手python

python真的是很火啊,而且功能很強大。但是寫c寫習慣了,看到沒括號的真的難受。昨天寫了點matlab,然後今天配置了vscode,發現寫c有點手生了,看來還是要多練習。打算自己學一學py,把基礎語法搞一下,其他以後再說。for i in range a,b i從a到b的迴圈 執行語句while ...