Python 命令汇总

兵种:Python程序员。 
等级:二级。 
攻击:较高。 
防御:普通。 
价格:低。 
天赋:胶水,我方有c程序员时,速度可达到c程序员的80%。 
天赋:成熟,难以升级到三级,即使成功也没什么好处 
—–刘鑫Mars


#Types


a = 2           # integer
b = 3.0         # float 
c = 5.3e5       #exponential
d = 6.5 + 0.5j  # complex
e = 7 > 5       # boolean
f = 'helloword'      # string

# Lists



a = ['red', 'blue', 'green']   
b = list(range(5)) 
c = [nu**2 for nu in b]
d = [nu**2 for nu in b if nu <3]
e = c[0]
f = c[1:2]
g = ['re', 'bl'] + ['gr']
h = ['re']*5
['re','bl'].index('re')         #returns index of 're'
're' in ['re', 'bl']            #true if 're' in list
sorted([3,4,1])                 #returns sorted list

----
列表中的元素可以是相同的类型,也可以是不同类型的。
a =[1, "b", 3, 6, "google", True]

-----列表中插入或者删除元素-----
a.insert(3, "fire") #插入到类别中第四个位置
a.append("ch")  # 插入到列表的最后面
del a[2]     #删除列表中的第三个元素


Tuple


元组是不能增加或删除元素,类似于常量。 
(2,) #一个元素的元组


# Dictionaries


字典是一种映射,从key 到value 的一种映射。


a = {'red': 'rouge', 'blue':'bleu', 'green': 'vertet'} 
b = a['red']  #字典取值
c = [value for key, value in a.items()]
d = a.get('yellow', 'no translation found')

#Strings


字符串其实是一个特殊的列表,列表中每个元素是一个字符。字符串本质上是一个常量,可以查询,不能修改。

a = 'red'
char = a[2]
'red' + 'blue'
'1, 2, three'.split(',')     # split string into list
'.'.join(['1', '2', 'three']) # concatenate list into string

%占位符 
a = “hello %s” % “wang” 
a =”%s %s” % (“hello”, “wang”) 
a =”%(verb)s %(name)s” % {“verb”: “hello”, “name” : “wang”} #占位符命名


# Operators



a  = 3
print(a)
a += 1   #(*=, /=)
print(a)
a *= 1
print(a)
a /= 1
print(a)
3 + 2
3/2
3//2    #integer division
3*2 
3**2    # exponent
3%2     # remainder
abs(a)  # absolute value
1 == 1  # equal
2 >1  
2 <1
1 != 2   #not equal
1 != 2 and 2 < 3  # logical AND
1 != 2 or 2 < 3 #logical OR
not  1 == 2     # logical NOT
'a' in b        # test if a is in b
a is b          # test if objects point to the same memory


----简写----
a = a +1 等价于 a +=1
a = a-1  等价于 a -=1

#Control Flow


控制流是能够改变代码执行顺序的。


# if/elif/else
a, b = 1, 2
if a + b == 3:
    print('True')
elif a + b == 1:
    print('False')
else:
    print('?')

# for 
a = ['red', 'blue', 'green']
for color in a:
    print(color)

#while
number = 1
while number < 10:
    print(number)
    number += 1

-----while -----
while 条件:
    do something

停止办法:
改变条件,使得条件变False
使用 break 强制退出。



#break
number = 1
while True:
    print(number)
    number += 1
    if number > 10:
        break

#Continue
for i in range(20):
    if i%2 == 0:
        continue
        print(i)



------breakcontinue   -------
row =[1, 2, 4, 6, 8]
for item in row:
    if item ==2:     
    continue        #跳过后面两句,只是跳出本次循环。
    if item == 4:
    break          #break使整个for 循环结束

# Functions, Classes, Generators, Decorators


所谓函数,就是多个命令的组合体。



# Function
def myfunc(a1, a2):
    return a1 + a2

x = myfunc(a1, a2)

# Class
class Point(object):
    def _init_(self, x):
        self.x = x
    def _call_(self):
        print(self.x)

x = Point(3)

---类与对象  ---
类与对象,类似于 概念与实体




# Generators
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

#Consume the generator wiht list comprehension
x = [i for i in firstn(10)]

# Decorators
class myDecorator(object):
    def _init_(self, f):
        self.f = f
    def _call_(self):
        print("call")
        self.f()

@myDecorator
def my_funct():
    print('func')

my_funct()

—函数中的参数—

形参:  
def clean_room(room_name): 
clean_table(room_name) 
clean_floor(room_name) 
clear_trash(room_name)

clean_room(“主卧”)

位置参数: 依据位置赋值。 
def clean_room(room_name, level): 
# clear code

clean_room(“主卧”, 2)

关键字参数: 明确指出传入给某个参数。 
def clean_room(room_name, level): 
#clean code

clean_room(level = 2, room_name =”主卧”) 
关键字参数不局限位置信息。

默认参数:  
def clean_room(room_name, level =2): 
#clean code

clean_room(“主卧”)

返回值:  
def clean_room(room_name, level =2): 
#clean code 
finished = True 
return finished

success = clean_room(room_name =”主卧”) 
无return 语句,默认返回 None.

多返回值:  
def clean_room(room_name, level =2): 
#clean code 
finished = True 
error_msg = “清洁剂没有了” 
return finished, error_msg

success, msg = clean_room(room_name =”主卧”) 
无return 语句,默认返回 None.

文档字符串:  
def clean_room(room_name, level =2): 
”’ 
这个函数用来清理房间  #文档字符串 
”’ 
#clean code 
finished = True 
error_msg = “清洁剂没有了” 
return finished, error_msg

success, msg = clean_room(room_name =”主卧”) 
无return 语句,默认返回 None.


# IPython



# Python console

<object>? # Information about the object
<object>.<TAB>  # tab completion

# measure runtime of a function:
%timeit range(1000)
100000 loops, best of 3: 7.76 us per loop

# run scripts and debug
%run 
%run -d  # run in debug mode
%run -t  # measures execution time 
%run -p # ruans a profiler
%debug # jumps to debugger after an exception

%pdb  # run debugger automatically on exception 

# examine history
%history
%history ~1/1-5  # lines 1-5 of last session

# run shell commands
!make # prefix command with "!"

#clean namespace
%rese

查看python软件包信息


可以查看已经安装的python软件包和版本

pip freeze  
pip list 

查看软件包源代码所在位置

python
import xgboost
xgboost.__file__  #查看xgboost包的__init__.py文档所在位置

查看软件包的版本

import xgboost
xgboost.__version__

不同软件包的属性不一样,有的查询版本可使用

import django
django.VERSION

查看模块的属性 
本质上是一个变量。

import xgboost
dir(xgboost)
['Booster', 'DMatrix', 'VERSION_FILE', 'XGBClassifier', 'XGBModel', 'XGBRegressor', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'absolute_import', 'callback', 'compat', 'core', 'cv', 'libpath', 'os', 'plot_importance', 'plot_tree', 'plotting', 'rabit', 'sklearn', 'to_graphviz', 'train', 'training']

查看模块的属性类型

import xgboost
dir(xgboost)
type(xgboost.plotting)

模块导入


模块被导入时,代码会运行一次。再次导入,不会再次运行。


规则1.模块导入


跟入口文件在同一个目录下。


规则2.模块导入


. 表示当前模块所在的包下。 
.. 表示当前模块的所在包的外层目录下。


python命名规则


命名只能是数字、字母和下划线。数字不能开头,区分大小写。


写入文件


poem = '''\
Programming is fun
When the work is done
If you want to make your work also fun:
use Python!
'''
f = open('poem.txt','w') # 模式:'w'写入 write,'r'读取read,'a'追加 append
#open 返回的是文件夹表示符
f.write(poem) # write text to file
f.close() #close the file  不关闭会占用系统。

读取文件


f = open('poem.txt')  #默认为'r'模式
while True:
     line = f.readline()
     if len(line) ==0:#空行表示读取结束
     break
     print(line, end="")
     #print 内容后面默认会增加一个\n
     #这里end禁止结尾增加\n,改为增加""
f.close() #close the file  

with语句


写入文件

with open('poem.txt','w') as f:
    f.write(poem)

读取文件

with open('poem.txt') as f:
    while True:
    line = f.readline()
    if len(line) == 0:
       break
    print(line, end="")

异常处理


try:
   一段可能出错的代码
expect ValueError as e:
   print(e) # 处理这个异常
except Exception:
   处理其余所有的异常
else:
没有异常的处理代码
try:
     一段可能出错的代码
finally:
     最后一定会执行的代码,例如
     f.close()
try:
    int("a")
except ValueError as e:
    print(e)
    raise e   # 抛出异常

References


1小时入门Python 
Python学习教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值