python的一些语法
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={'a':1,'b':1.2,'c':1j};
for key,val in sorted(d.items()):
print('key: %s has value: %s' % (key,val))
o
e
u
(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∞4i24i2−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;
def addx(y):
return x+y
def setx(y):
x=y
print('x is %d' % x)
def setxx(y):
global x #访问全局变量x
x=y
print('x is %d' % x)
addx(10)
setx(10)
print(x)
setxx(10)
print(x)
x is 10
5
x 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 {'x': 1, 'y': 2}
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
os
os.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