學習python 語法(一)

2021-08-11 03:27:47 字數 2251 閱讀 8932

1 . 通過下標遍歷tuple、list、dict

vowels='aejouy';

for i in

'powerful':

if i in vowels:

print(i)

words=('cool','powerful','readable');

for i in range(0,len(words)):

print((i,words[i]))

d=;for key,val in sorted(d.items()):

print('key: %s has value: %s' % (key,val))

oeu

(0, 'cool')

(1, 'powerful')

(2, 'readable')

key: a has value: 1

key: b has value: 1.2

key: c has value: 1j

2 . 通過公式 π=

2∏i=

1∞4i

24i2

−1求π

pi=1;

for i in range(1,30000):

pi=pi*4*i**2/(4*i**2-1);

2*pi

3.141566473323762
3 . python全域性變數

x=5;

defaddx

(y):

return x+y

defsetx

(y):

x=yprint('x is %d' % x)

defsetxx

(y):

global x #訪問全域性變數x

x=yprint('x is %d' % x)

addx(10)

setx(10)

print(x)

setxx(10)

print(x)

x is 10

5x is 10

10

4 . 函式引數(不定長度的list,tuple,dict)

def

variable_args

(*args,**kwargs):

#需要加上*

print ('args is', args)

print ('kwargs is', kwargs)

variable_args(1,2,3,'a','b',x=1,y=2)

args is (1, 2, 3, 'a', 'b')

kwargs is

5 . 函式幫助文件

def

funcname

(params):

"""concise one-line sentence describing the function

extended summary which can contain multiple paragraphs.

"""#function body

pass

funcname?

6 .import

可以通過 import,import … as…, from … import … 載入模組或模組中的函式、變數

import os

osos.listdir('../')

#不要使用 from os import *,這使得**不易閱讀,

#不知道函式來自**,且可能導致變數覆蓋

import numpy as np

np.linspace(0,10,6)

array([  0.,   2.,   4.,   6.,   8.,  10.])
import scipy

print(scipy.__file__)

print(scipy.__version__)

f:\anaconda3\lib\site-packages\scipy\__init__.py

0.19.1

參考

scipy-lectures

Python學習筆記 (一)python語法

python識別符號 語法 由字母,數字,下劃線組成 不能以數字開頭 python中的識別符號區分大小寫。行和縮排 python中以縮排作為 塊的標誌,不再採用c語言的 多行語句 python中以新行作為語句的結束符號,如果語句過長需要多行顯示的時候可以使用反斜槓 連線 注意 若語句中包含,或者 就...

Python 學習筆記之語法(一)

python對語法格式要求很嚴格,因此,在編寫時一定要注意這些問題,比如下面就是這樣的問題 traceback most recent call last file line 1,in file d anzhuang anaconda lib site packages spyderlib widg...

python學習筆記一(語法)

持續更新中1 list,tuple,dict,set dict為字典,可以主動修改key,定義方式如下 a 1,b 2,c 4,5 set為不可存在重複選項的list 2 函式接收可變引數可使用如下方法 def calc numbers sum 0 for i in numbers sum i i ...