Python入门
本专题的目标
- 掌握基本的Python语法,编写简单的py程序
- 编写简单的爬虫
- 基本的数据分析
Python的特性
- 语法简单,容易理解
- 跨平台
- 有强大、丰富的第三方库
- 作用:网站、爬虫、大数据处理、机器学习……
- 动态类型语言
Hello World
import this
print("Hello")
print("World")
# 输出:
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.
# Special cases aren't special enough to break the rules.
# Although practicality beats purity.
# Errors should never pass silently.
# Unless explicitly silenced.
# In the face of ambiguity, refuse the temptation to guess.
# There should be one-- and preferably only one --obvious way to do it.
# Although that way may not be obvious at first unless you're Dutch.
# Now is better than never.
# Although never is often better than *right* now.
# If the implementation is hard to explain, it's a bad idea.
# If the implementation is easy to explain, it may be a good idea.
# Namespaces are one honking great idea -- let's do more of those!
# Hello
# World
Python初体验
计算器:
- ±*/
- **:乘方
- import math
import math
print(3 ** 2)
print(math.pi)
print('---------')
price = 5
count = 10
cost = price * count
print("count: {}".format(count))
# 输出:
# 9
# 3.141592653589793
# ---------
# count: 10
规范和变量
命名规范
-
与Java(驼峰命名)不同,使用_分割
-
第一个字符必须是字母或者_
值的交换:
import math
a = 10
b = 20
# 交换a, b的值
a, b = b, a
print("a = {}, b = {}".format(a, b))
print("-----")
a = 10
b = 20
c = 30
# 交换a, b, c的值
a, b, c = b, c, a
print("a = {}, b = {}, c = {}".format(a, b, c))
print("-----")
# 取两位小数
print(round(math.pi, 2))
# 输出:
# a = 20, b = 10
# -----
# a = 20, b = 30, c = 10
# -----
# 3.14
代码规范
- 不用单个字母取变量名
- 不用拼音首字母取变量名!!!
- 清晰表达变量的含义
- 必要时加注释