译文:
https://learnxinyminutes.com/docs/zh-cn/python3-cn/
昨天推文留言,看到好多公众号的读者想要多看点Python相关的文章,所以有了今天这篇Python基础推文!Python是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。
注意:这篇教程是基于 Python 3 写的。
""" 多行字符串用三个引号
包裹,也常被用来做多
行注释
"""
1. 原始数据类型和运算符
3
1 + 1
8 - 1
10 * 2
35 / 5
5 / 3
5 // 3
5.0 // 3.0
-5 // 3
-5.0 // 3.0
3 * 2.0
7 % 3
2**4
(1 + 3) * 2
True
False
not True
not False
True and False
False or True
0 and 2
-5 or 0
0 == False
2 == True
1 == True
1 == 1
2 == 1
1 != 1
2 != 1
1 < 10
1 > 10
2 <= 2
2 >= 2
1 < 2 < 3
2 < 3 < 2
"这是个字符串"
'这也是个字符串'
"Hello " + "world!"
"This is a string"[0]
"{} can be {}".format("strings", "interpolated")
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
"%s can be %s the %s way" % ("strings", "interpolated", "old")
None
"etc" is None
None is None
bool(0)
bool("")
bool([])
bool({})
2. 变量和集合
print("I'm Python. Nice to meet you!")
some_var = 5
some_var
some_unknown_var
li = []
other_li = [4, 5, 6]
li.append(1)
li.append(2)
li.append(4)
li.append(3
)
li.pop()
li.append(3)
li[0]
li[-1]
li[4]
li[1:3]
li[2:]
li[:3]
li[::2]
li[::-1]
del li[2]
li + other_li
li.extend(other_li)
1 in li
len(li)
tup = (1, 2, 3)
tup[0]
tup[0] = 3
len(tup)
tup + (4, 5, 6)
tup[:2]
2 in tup
a, b, c = (1, 2, 3)
d, e, f = 4, 5, 6
e, d = d, e
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"]
list(filled_dict.keys())
list(filled_dict.values())
"one" in filled_dict
1 in filled_dict
filled_dict["four"]
filled_dict.get("one")
filled_dict.get("four")
filled_dict.get("one", 4)
filled_dict.get("four", 4)
filled_dict.setdefault("five", 5)
filled_dict.setdefault("five", 6)
filled_dict.update({"four":4})
filled_dict["four"] = 4
del filled_dict["one"]
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4}
filled_set = some_set
filled_set.add(5)
other_set = {3, 4, 5, 6}
filled_set & other_set
filled_set | other_set
{1, 2, 3, 4} - {2, 3, 5}
2 in filled_set
10 in filled_set
3. 流程控制和迭代器
some_var = 5
if some_var > 10:
print("some_var比10大")
elif some_var < 10:
print("some_var比10小")
else:
print("some_var就是10")
"""
用for循环语句遍历列表
打印:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
print("{} is a mammal".format(animal))
"""
"range(number)"返回数字列表从0到给的数字
打印:
0
1
2
3
"""
for i in range(4):
print(i)
"""
while循环直到条件不满足
打印:
0
1
2
3
"""
x = 0
while x < 4:
print(x)
x += 1
try:
raise IndexError("This is an index error")
except IndexError as e:
pass
except (TypeError, NameError):
pass
else:
print("All good!")
filled_dict = {"one": 1
, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)
for i in our_iterable:
print(i)
our_iterable[1]
our_iterator = iter(our_iterable)
our_iterator.__next__()
our_iterator.__next__()
our_iterator.__next__()
our_iterator.__next__()
list(filled_dict.keys())
4. 函数
def add(x, y):
print("x is {} and y is {}".format(x, y))
return x + y
add(5, 6)
add(y=6, x=5)
def varargs(*args):
return args
varargs(1, 2, 3)
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness")
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)
all_the_args(**kwargs)
all_the_args(*args, **kwargs)
x = 5
def setX(num):
x = num
print (x)
def setGlobalX(num):
global x
print (x)
x = num
print (x)
setX(43)
setGlobalX(6)
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3)
(lambda x: x > 2)(3)
map(add_10, [1, 2, 3])
filter(lambda x: x > 5, [3, 4, 5, 6, 7])
[add_10(i) for i in [1, 2, 3]]
[x for x in [3, 4, 5, 6, 7] if x > 5]
5. 类
class Human(object):
species = "H. sapiens"
def __init__(self, name):
self.name = name
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def grunt():
return "*grunt*"
i = Human(name="Ian")
print(i.say("hi"))
j = Human("Joel")
print(j.say("hello"))
i.get_species()
Human.species = "H. neanderthalensis"
i.get_species()
j.get_species()
Human.grunt()
6. 模块
import math
print(math.sqrt(16))
from math import ceil, floor
print(ceil(3.7))
print(floor(3.7))
from math import *
import math as m
math.sqrt(16) == m.sqrt(16)
import math
dir(math)
7. 高级用法
def double_numbers(iterable):
for i in iterable:
yield i + i
range_ = range(1, 900000000)
for i in double_numbers(range_):
print(i)
if i >= 30:
break
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
print(say())
print(say(say_please=True))
本文代码获取链接:
https://pan.baidu.com/s/10MRXRgyz4CBOFeUaeL_tGg
提取码:eq3s
入门学习资料,仅供学习,请勿商用!

资料获取:公众号聊天框回复【Python】
(完)
打卡赠书:坚持30天打卡赠书新玩法!
送什么书?请点击左下角阅读原文
查看!
签到方式:长按以下二维码参与打卡↓↓↓↓↓

回馈公众号真爱粉的一次活动!
源码解析Java字符串比较
给你一份Spring Boot核心知识清单
推荐GitHub上100天学习Python的开源项目