2 Star 37 Fork 12

Epsilon Luoo/仅同步_learn-python-the-smart-way-v2

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.github
docs
homework
resources
slides
chapter_0-Installation.ipynb
chapter_1-Getting_Started.ipynb
chapter_10-Object_Oriented_Programming_Part_1.ipynb
chapter_11-Object_Oriented_Programming_Part_2.ipynb
chapter_2-Data_Types_and_Operators.ipynb
chapter_3-Variables_and_Functions.ipynb
chapter_4-Conditionals.ipynb
chapter_5-Loop.ipynb
chapter_6-Strings.ipynb
chapter_7-Lists_and_Tuples.ipynb
chapter_8-Sets.ipynb
chapter_9-Dictionaries.ipynb
datawhale_logo.png
rise.css
talks
utils/bilibili_live
.gitignore
.gitmodules
LICENSE
README.md
mkdocs.yml
克隆/下载
chapter_1-Getting_Started.ipynb 30.90 KB
一键复制 编辑 原始数据 按行查看 历史
Epsilon Luoo 提交于 2年前 . 更新邮件信息

聪明办法学 Python 2nd Edition

Chapter 1 启航 Getting Started


聪明办法学 Python 教学团队

learn.python.the.smart.way@gmail.com

欢迎大家来到 P2S!

迈出成为 AI 训练大师的第一步!

AI Master

第一行代码

Language C

#include<stdio.h> 
int main(){
    printf("Hello, World");
    return 0;
}
print("聪明办法学Python") 
聪明办法学Python

Hello World 的由来

Brian Kernighan
main( ) {
    printf("hello, word");
}

Brian Wilson Kernighan, 1972

A Tutorial Introduction to the Language B

Language B Version:

main( ) {
    extern a, b, c;
    putchar(a); putchar(b); putchar(c); putchar('!*n');
}
 
a 'hell';
b 'o, w';
c 'orld';

注释 Comment

分类:

  • 单行注释,使用 # 开头
  • 多行注释,使用 '''""" 包裹起来

作用:

  • 注释主要是用于对代码进行解释和说明,可以提升代码的可读性
  • 注释并不会被当做代码处理 # magic comment 除外

程序员最讨厌的 10 件事:0. 别人的代码不写注释。 1. 给自己的代码写注释

当初写这段代码的时候只有上帝和我知道它是干嘛的,现在只有上帝知道

单行注释

使用 # 开头,# 后面的内容不会被当做代码,只能写在一行中

print("Datawhale") # for the learner,和学习者一起成长 
# output 输出, print 打印
Datawhale
# 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

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")
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.

如何秒杀马里奥题

洛谷 P1000 超级玛丽游戏

from IPython.display import IFrame
IFrame('https://www.luogu.com.cn/problem/P1000', width=1300, height=600)

错误 Error

  • 语法错误 Syntax Errors,不符合语法规范,代码根本没有开始运行
  • “运行时”错误 Runtime Errors,代码在运行过程中出错,也就是常说的“崩溃”(Crash)
  • 逻辑错误 Logical Errors,代码能够运行,且运行过程中没有出错,但是不是想要的结果
# 语法错误(在编译时出错,Python 并没有开始运行代码)
print("哦不!) # Error! 缺少结尾引号
  Cell In[1], line 2
    print("哦不!) # Error! 缺少结尾引号
          ^
SyntaxError: unterminated string literal (detected at line 2)
# “运行时”错误(Python 开始运行代码,但是遇到了些问题)
print(1/0) # Error! 0 被作为除数
---------------------------------------------------------------------------
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, "です")
输入你的名字:龙的传人
あなたの名前は 龙的传人 です

注意!返回的格式是字符串

x = input("输入一个数字")
print(x, "的一半等于", x/2) # Error!
输入一个数字10
---------------------------------------------------------------------------
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))
---------------------------------------------------------------------------
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))
---------------------------------------------------------------------------
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)
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 的库能让很多操作变方便

Thank You ;-)

Datawhale 聪明办法学 Python 教学团队出品

关注我们

Datawhale 是一个专注 AI 领域的开源组织,以“for the learner,和学习者一起成长”为愿景,构建对学习者最有价值的开源学习社区。关注我们,一起学习成长。

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/anine09/learn-python-the-smart-way-v2.git
git@gitee.com:anine09/learn-python-the-smart-way-v2.git
anine09
learn-python-the-smart-way-v2
仅同步_learn-python-the-smart-way-v2
main

搜索帮助