python3笔记

提示:
1.python对空格和缩进要求比较严格(4个空格)
2.方法、判断等结尾注意加冒号
3.不需要end等结尾
 
1.输出
print("Hello, World!")
python hello.py
 
2.判断
if 条件1:
    print("1")
elif 条件2:
    print("2")
else:
    print("3")
 
3.计算
import math
print(math.floor(32.9))
 
from math import sqrt
print(sqrt(9))
 
4.循坏输出1~5
(1)while
count = 1
while count < 6:
    print (count)
    count = count + 1
 
(2)for
for i in range(1,6):
    print(i)
 
words = ['this', 'is', 'a', 'sentence']
for word in words:
    print(word)
 
5.日期
import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
 
6.读取文件
f = open(r'e:/temp/1.txt')
print(f.read())
f.close()
 
readline读取1行
readlines读取所有行,返回结果为数组
write写入文件
 
7.类
class Person:
    def setName(self, name):
        self.name = name
        
    def getName(self):
        return self.name
    
    def greet(self):
        print("hello, %s." % self.name)
        
foo = Person()
foo.setName("Luke")
foo.greet()
 
8.页面简单抓取
import urllib.request
res = urllib.request.urlopen(url)
html = res.read().decode('utf-8')
print(html)
 
python3之前版本
import urllib
res = urllib.urlopen(url)
html = res.read().decode('utf-8')
print(html)
 
9.注释
单行注释
#print(1)
#print(2)
 
多行注释''' 或 """
'''
print(1)
print(2)
'''

 

10.字符串和数字之间转换
x = int("6")
y = str(6)
#查看类型
print(type(x))
#判断类型,返回true或false
isinstance(6, int)
 
11.字符串长度
len()
 
12.数组
#追加
data = []
data.append({"address":"beijing", "price":"100"})
data.append({"address":"shanghai", "price":"200"})
#del 根据下标删除
 
13.lambda 排序
data.sort(key=lambda z:(z["address"], z["price"]) ,reverse=True)
#reverse=True为倒叙
for d in data:
print(d)
   
14.集合反转
list = [11, 'abc', 22, 'xyz']    
print(list[::-1])
#::-2 隔一个反转    
 
15.1~100随机数
randint(1, 100)
 
16.in 操作,返回true或false
print('bc' in 'abcd')
print('nm' not in 'abcd')
 
17.string模块
import string
#首字母大写
print(string.capitalize("hello"))
#小写
string.lowercase    
"HELLO".lower()
#切割
string.split("abcdefg")
#去空格
string.lstrip(" xx")
string.rstrip("xx ")
string.rstrip(" xx ")
 
18.异常
#raise抛异常
#异常捕获
try
...
except Exception, e:
print e
finally
...
   
19.自定义高阶函数
def convert(func, seq):
return [func(eachNum) for eachNum in seq]
 
myseq = [123, 45.67, -6.263, 9999L]
#数组中每个值转为int
print(convert(int, myseq))
#数组中每个值转为long
print(convert(long, myseq))
 
20.多个参数
#默认值 rate=0.085
#多参数 *theRest
#键值对参数 **theRest
 
def taxMe(cost, rate=0.085, *theRest):
    for eachRest in theRest:
        ...
    return ...
 
def taxMe(cost, rate=0.085, **theRest):
    for eachRest in theRest,keys():
        #value = theRest[eachRest]
        ...
    return ...
原文地址:https://www.cnblogs.com/songfei90/p/10185595.html