聪明办法学 Python 2nd Edition
Chapter 1 启航 Getting Started
注释 Comment
分类:
- 单行注释,使用
#
开头 - 多行注释,使用
'''
或"""
包裹起来
作用:
- 注释主要是用于对代码进行解释和说明,可以提升代码的可读性
- 注释并不会被当做代码处理 # magic comment 除外
程序员最讨厌的 10 件事:0. 别人的代码不写注释。 1. 给自己的代码写注释
当初写这段代码的时候只有上帝和我知道它是干嘛的,现在只有上帝知道
单行注释
使用 #
开头,#
后面的内容不会被当做代码,只能写在一行中
例1:
print("Datawhale") # for the learner,和学习者一起成长
#output 输出, print 打印
输出为:Datawhale
例2:
#learn python the smart way v2
print("p2s")
#print("prepare to be smart")
输出为:p2s
多行注释
使用 '''
或 """
包裹起来(头和尾都是 3 个),单引号(')与双引号(")在 Python 中并无太大区别
例:
print("人生苦短,我用 Python")
'''
Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.
'''
基础的控制台输出 Basic Console Output
#f(x) print -> f; (x) -> ("Datawhale"); x -> "Datawhale" 字符串 String
print("Datawhale") # for the learner,和学习者一起成长
输出为:Datawhale
print()
的作用是将填入的内容显示在 Console 中,默认每次输入后会换行(等价于按了一次回车,或者 \n
)
控制结尾的参数是 end
print("Data")
print("whale")
输出为:
Data
whale
print("Data", end="*")
print("whale")
输出为:Data*whale
print()
一次也可以输出多个内容,默认以空格分隔
控制分隔的参数是 sep
print("Data","whale") # f(x, y)
输出为:Data whale
print("Data", "whale", sep="*")
输出为:Data*whale
你甚至可以做加法和乘法!
print("p2s"*2,"data"*3, sep="/"*4)
输出为:p2sp2s////datadatadata
print("Data"+"whale"+"P2S")
输出为:DatawhaleP2S
一些更好玩的做法
我们假设,
x = 1
y = 2
print(f"一个简单的数学问题:\"{x} + {y} = ?\",答案是 {x+y}!") # f-strings
输出为:一个简单的数学问题:"1 + 2 = ?",答案是 3!
为了课程演示,我们编写了下面这些代码,你并不需要弄清楚它具体内容是什么,享受游戏的过程就好了 ?
from ipywidgets import interact
import ipywidgets as widgets
def f(x, y):
print(f"A simple math question: \"{x} + {y} = ?\", the answer is {x + y}!")
interact(f,x=10, y=20)
输出为:
interactive(children=(IntSlider(value=10, description='x', max=30, min=-10), IntSlider(value=20, description='…
<function main.f(x, y)>
如果我想一次性输出很多行?
print("""
Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.
""")
输出为:
Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.
如何秒杀马里奥题
from IPython.display import IFrame
IFrame('https://www.luogu.com.cn/problem/P1000', width=1300, height=600)
<iframe
width="1300"
height="600"
src="https://www.luogu.com.cn/problem/P1000"
frameborder="0"
allowfullscreen
></iframe>
错误 Error
- 语法错误 Syntax Errors,不符合语法规范,代码根本没有开始运行
- “运行时”错误 Runtime Errors,代码在运行过程中出错,也就是常说的“崩溃”(Crash)
- 逻辑错误 Logical Errors,代码能够运行,且运行过程中没有出错,但是不是想要的结果
#语法错误(在编译时出错,Python 并没有开始运行代码)
print("哦不!) # Error! 缺少结尾引号
输出为:
{
"name": "SyntaxError",
"message": "EOL while scanning string literal (3098959924.py, line 2)",
"stack": " Cell In [27], line 2
print("哦不!) # Error! 缺少结尾引号
^
SyntaxError: EOL while scanning string literal
"
}
“运行时”错误(Python 开始运行代码,但是遇到了些问题)
print(1/0) # Error! 0 被作为除数
输出为:
{
"name": "ZeroDivisionError",
"message": "division by zero",
"stack": "---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In [28], line 2
1 # “运行时”错误(Python 开始运行代码,但是遇到了些问题)
----> 2 print(1/0)
ZeroDivisionError: division by zero"
}# Logical Errors (Compiles and runs, but is wrong!)
#逻辑错误(能编译,能运行,但不是想要的结果)
print("2+2=5") # Error! 算错了!!!
#我们想要:4!
输出为:
2+2=5
基础的控制台输入 Basic Console Input
input()
可以接收 Console 的输入,并以字符串的形式返回,你可以给定个字符串参数,它会先输出到 Console,再接收输入
name = input("输入你的名字:")
print("あなたの名前は", name, "です")
输出为:
输入你的名字:龙的传人
あなたの名前は 龙的传人 です
注意!返回的格式是字符串
name = input("输入你的名字:")
print("あなたの名前は", name, "です")
输出为:
输入你的名字:龙的传人
あなたの名前は 龙的传人 です
x = input("输入一个数字")
print(x, "的一半等于", x/2) # Error!
输出为:
输入一个数字10
{
"name": "TypeError",
"message": "unsupported operand type(s) for /: 'str' and 'int'",
"stack": "---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [33], line 2
1 x = input("输入一个数字")
----> 2 print(x, "的一半等于", x/2)
TypeError: unsupported operand type(s) for /: 'str' and 'int'"
}
x = input("输入一个数字")
x = int(x) # 类型转换 float(x)
x = int(input("输入一个数字:")) # f(g(x))
print(x, "的一半等于", x/2) # 对味啦
输出为:
输入一个数字10
10 的一半等于 5.0
一行多个输入值
1 -> a,2 -> b
可以在结尾加上 split()
,默认分隔参数是空格,可以更改,如:split(",")
a, b = input().split("*")
print(f"a = {a}, b = {b}")
输出为:
1*2
a = 1, b = 2
导入模块
Python 中有许多强大的工具箱,我们把它们叫做“库”(Library),课程后期会介绍更多强大的工具
库需要使用 import
来导入,并且使用 xx.yy
的方式来调用,我们今天只作粗略介绍
以 Python 内置数学库 math
为例:
#阶乘 factorial
print(math.factorial(20))
输出为:
{
"name": "NameError",
"message": "name 'math' is not defined",
"stack": "---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [39], line 2
1 # 阶乘 factorial
----> 2 print(math.factorial(20))
NameError: name 'math' is not defined"
}
import math # 使用库前要先导入!
print(math.factorial(20000))
输出为:
{
"name": "ValueError",
"message": "Exceeds the limit (4300) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit",
"stack": "---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [43], line 2
1 import math # 使用库前要先导入!
----> 2 print(math.factorial(20000))
ValueError: Exceeds the limit (4300) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit"
}
#Euler 常数
print(math.e)sh
输出为:
2.718281828459045
#gcd 最大公约数
math.gcd(12, 36)
输出为:
12
def f(x):
a = x*(math.pi/180)
print(math.sin(a))
interact(f,x=30)
输出为:
interactive(children=(IntSlider(value=30, description='x', max=90, min=-30), Output()), _dom_classes=('widget-…
<function main.f(x)>
补充资料
0.1+0.2≠0.3?? 无可避免的浮点误差:https://www.bilibili.com/video/BV1xq4y1D7Ep
总结
- 写注释是个好习惯
- 调整输入输出的参数来控制其呈现效果
- 大部分错误类型可以归为:语法错误、运行时错误和逻辑错误
- Python 的库能让很多操作变方便