学习python:语法(一)

来源:互联网 发布:虚拟按键软件代码 编辑:程序博客网 时间:2024/05/18 23:28

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))
oeu(0, 'cool')(1, 'powerful')(2, 'readable')key: a has value: 1key: b has value: 1.2key: c has value: 1j

2 . 通过公式 π=2i=14i24i21π

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+ydef 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 105x is 1010

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    passfuncname?

6 .import
可以通过 import,import … as…, from … import … 加载模块或模块中的函数、变量

import ososos.listdir('../')#不要使用 from os import *,这使得代码不易阅读,#不知道函数来自哪里,且可能导致变量覆盖import numpy as npnp.linspace(0,10,6)
array([  0.,   2.,   4.,   6.,   8.,  10.])
import scipyprint(scipy.__file__)print(scipy.__version__)
F:\Anaconda3\lib\site-packages\scipy\__init__.py0.19.1

参考
scipy-lectures

原创粉丝点击