python快速基础

转载[个人学习使用]:https://www.voidking.com/dev-python-start/

hello world

1、IDLE中,输入print(‘hello world’)。语句末尾加不加分号;都可以
2、使用sublime新建文件hello.py

#!/usr/bin/env python
print('hello world')

运行脚本。首先添加执行权限chmod a+x hello.py,然后执行./hello.py。或python hello.py

引入模块

Python每一个 .py 文件都是一个模块。包含 .py 文件的目录叫做包。
模块的引入方法:

import module_name
from package_name import module_name

下面是一个例子:
1、新建name.py,内容如下:
name=‘voidking’
2、执行python name.py。
3、进入python shell模式,执行import name,print(name.name),则打印出voidking。


  • 在一个py脚本script中自定义函数func
    调用
from script import func
  • pip install python pkg
pip install script
from script import func
  • conda install python pkg
conda install script
from script import func
# cigar_shell.py
import sys
from cigar import Cigar
cigar_string = sys.argv[1]
c = Cigar(cigar_string)
c_len=len(c)
print(c_len)
python cigar_shell.py $i >> txt

基础语法

常用函数(print)、数据类型、表达式、变量、条件和循环、函数。和其他语言类似,下面选择一部分展开。

list链表数组

1、定义数组
myList = [‘Hello’, 100, True]
2、输出数组
print(myList)
3、输出数组元素
print(myList[0]),print(myList[-1])
4、追加元素到末尾
myList.append(‘voidking’)
5、追加元素到头部
myList.insert(0,‘voidking’)
6、删除元素
myList.pop(),myList.pop(0)
7、元素赋值
myList[0]=‘hello666’

tuple固定数组

1、定义数组
myTuple = (‘Hello’, 100, True)
错误定义:myTuple1=(1),正确定义:myTuple=(1,)
2、输出数组
print(myTuple)
3、输出数组元素
print(myTuple[0])
4、tuple和list结合
t = (‘a’, ‘b’, [‘A’, ‘B’]),t[2][0]=‘X’

if语句

score = 75
if score>=60:
    print 'passed'

两次回车,即可执行代码。

if score>=90:
    print('excellent')
elif score>=80:
    print('good')
elif score>=60:
    print('passed')
else:
    print('failed')

循环

for循环

L = [75, 92, 59, 68]
sum = 0.0
for score in L:
       sum += score
print(sum / 4)

while循环

sum = 0
x = 1
while x<100:
    sum += x
    x = x + 1
print(sum)

break

sum = 0
x = 1
while True:
    sum = sum + x
    x = x + 1
    if x > 100:
        break
print(sum)

continue

L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
    if x < 60:
        continue
    sum = sum + x
    n = n + 1
print(sum/n)

多重循环

for x in ['A', 'B', 'C']:
    for y in ['1', '2', '3']:
        print(x + y)

dict

dict的作用是建立一组 key和一组value的映射关系。

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
print(d)
print(d['Adam'])
print(d.get('Lisa'))
d['voidking']=100
print(d)
for key in d:
    print(key+':',d.get(key))

set

set持有一系列元素,这一点和list很像,但是set的元素没有重复,而且是无序的,这点和dict的key很像。

s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
print(s)
s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul'])
print(s)
len(s)
print('Adam' in s)
print('adam' in s)
for name in s:
    print(name)
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
for x in s:
    print(x[0]+':',x[1])
s.add(100)
print(s)
s.remove(('Adam',95))
print(s)

函数

自带函数

L = [x*x for x in range(1,101)]
print(sum(L))

自定义函数

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
print(my_abs(-100))

引入函数库

import math

def quadratic_equation(a, b, c):
    x = b * b - 4 * a * c
    if x < 0:
        return none
    elif x == 0:
        return -b / (2 *a)
    else:
        return ((math.sqrt(x) - b ) / (2 * a)) , ((-math.sqrt(x) - b ) / (2 * a))
print(quadratic_equation(2, 3, 0))
print(quadratic_equation(1, -6, 5))

可变参数

def average(*args):
    if args:
        return sum(args)*1.0/len(args)
    else:
        return 0.0

print(average())
print(average(1, 2))
print(average(1, 2, 2, 3, 4))

切片

list切片

L = ['Adam', 'Lisa', 'Bart', 'Paul']
print(L[0:3])
print(L[:3])
print(L[1:3])
print(L[:])
print(L[::2])

倒序切片

print(L[-2:])
print(L[-3:-1])
print(L[-4:-1:2])
L = range(1, 101)
print(L[-10:])
print(L[4::5][-10:])

print(L[-2:])
print(L[-3:-1])
print(L[-4👎2])
L = range(1, 101)
print(L[-10:])
print(L[4::5][-10:])
PS:range是有序的list,默认以函数形式表示,执行range函数,即可以list形式表示。

字符串切片

def firstCharUpper(s):
    return s[0:1].upper() + s[1:]

print(firstCharUpper('hello'))

迭代

Python的for循环不仅可以用在list或tuple上,还可以作用在其他任何可迭代对象上。
迭代操作就是对于一个集合,无论该集合是有序还是无序,我们用for循环总是可以依次取出集合的每一个元素。
集合是指包含一组元素的数据结构,包括:

  • 有序集合:list,tuple,str和unicode;
  • 无序集合:set
  • 无序集合并且具有key-value对:dict
for i in range(1,101):
    if i%7 == 0:
        print(i)

索引迭代

对于有序集合,元素是有索引的,如果我们想在for循环中拿到索引,怎么办?方法是使用enumerate()函数。

L = ['Adam', 'Lisa', 'Bart', 'Paul']
for index, name in enumerate(L):
    print(index+1, '-', name)

myList = zip([100,20,30,40],L);
for index, name in myList:
    print(index, '-', name)

迭代dict的value

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
print(d.values())
for v in d.values():
    print(v)

PS:Python3.x中,dict的方法dict.keys(),dict.items(),dict.values()不会再返回列表,而是返回一个易读的“views”。这样一来,k = d.keys();k.sort()不再有用,可以使用k = sorted(d)来代替。
同时,dict.iterkeys(),dict.iteritems(),dict.itervalues()方法不再支持。

迭代dict的key和value

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
for key, value in d.items():
    print(key, ':', value)

列表生成

一般表达式

L = [x*(x+1) for x in range(1,100)]
print(L)

复杂表达式

d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
def generate_tr(name, score):
    if score >=60:
        return '<tr><td>%s</td><td>%s</td></tr>' % (name, score)
    else:
        return '<tr><td>%s</td><td style="color:red">%s</td></tr>' % (name, score)

tds = [generate_tr(name,score) for name, score in d.items()]
print('<table border="1">')
print('<tr><th>Name</th><th>Score</th><tr>')
print('\n'.join(tds))
print('</table>')

条件表达式

L = [x * x for x in range(1, 11) if x % 2 == 0]
print(L)
def toUppers(L):
    return [x.upper() for x in L if isinstance(x,str)]

print(toUppers(['Hello', 'world', 101]))

多层表达式

L = [m + n for m in 'ABC' for n in '123']
print(L)
L = [a*100+b*10+c for a in range(1,10) for b in range(0,10) for c in range(1,10) if a==c]
print(L)

书签

Python入门 http://www.imooc.com/learn/177
如何学习Python爬虫? https://zhuanlan.zhihu.com/p/21479334?refer=passer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值