Datewhale学习笔记1

发布时间 2023-11-21 12:56:08作者: 瑟兰迪尔·绿叶

$\textcolor{blue}{Datewhale学习笔记}$$\textcolor{red}{chap1}$

第一行代码

Language C

#include<stdio.h> 
int main(){
    printf("Hello, World");
    return 0;
}

In [3]

print("聪明办法学Python") 
聪明办法学Python

Hello World 的由来

img

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. 给自己的代码写注释

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

单行注释

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

In [4]

print("Datawhale") # for the learner,和学习者一起成长 
# output 输出, print 打印
Datawhale

In [7]

# learn python the smart way v2
print("p2s")
# print("prepare to be smart")
p2s

多行注释

使用 '''""" 包裹起来(头和尾都是 3 个),单引号(')与双引号(")在 Python 中并无太大区别

In [ ]

print("人生苦短,我用 Python")
'''
Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.
'''

基础的控制台输出 Basic Console Output

In [9]

# f(x) print -> f; (x) -> ("Datawhale"); x -> "Datawhale" 字符串 String
print("Datawhale") # for the learner,和学习者一起成长
Datawhale

print() 的作用是将填入的内容显示在 Console 中,默认每次输入后会换行(等价于按了一次回车,或者 \n

控制结尾的参数是 end

In [10]

print("Data")
print("whale")
Data
whale

In [14]

print("Data", end="\t")
print("whale")
Data*whale

print() 一次也可以输出多个内容,默认以空格分隔

控制分隔的参数是 sep

In [16]

print("Data","whale") # f(x, y)
Data whale

In [17]

print("Data", "whale", sep="*")
输出:Data*whale

你甚至可以做加法乘法

In [18]

print("p2s"*2,"data"*3, sep="/"*4)
p2sp2s////datadatadata

In [19]

注:(加法前后的数据类型必须相等)

print("Data"+"whale"+"P2S")
DatawhaleP2S

一些更好玩的做法

我们假设,

In [21]

x = 1
y = 2

In [24]

注:(进行格式化处理)将x,y的内容输入文本

print(f"一个简单的数学问题:\"{x} + {y} = ?\",答案是 {x+y}!") # f-strings
一个简单的数学问题:"1 + 2 = ?",答案是 3!

In [2]

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)
A simple math question: "10 + 20 = ?", the answer is 30!
interactive(children=(IntSlider(value=10, description='x', max=30, min=-10), IntSlider(value=20, description='…
<function __main__.f(x, y)>

如果我想一次性输出很多行

In [26]

注:(跟多行注释相似)

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 超级玛丽游戏

In [1]

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

错误 Error

注:(可以使用异常处理机制try--except--else--finally来进行程序异常处理)

  • 语法错误 Syntax Errors,不符合语法规范,代码根本没有开始运行
  • “运行时”错误 Runtime Errors,代码在运行过程中出错,也就是常说的“崩溃”(Crash)
  • 逻辑错误 Logical Errors,代码能够运行,且运行过程中没有出错,但是不是想要的结果

In [27]

# 语法错误(在编译时出错,Python 并没有开始运行代码)
print("哦不!) # Error! 缺少结尾引号

Cell In [27], line 2 print("哦不!) # Error! 缺少结尾引号 ^ SyntaxError****: EOL while scanning string literal

In [28]

# “运行时”错误(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

In [29]

# Logical Errors (Compiles and runs, but is wrong!)
# 逻辑错误(能编译,能运行,但不是想要的结果)
print("2+2=5") # Error! 算错了!!!
# 我们想要:4!
2+2=5

基础的控制台输入 Basic Console Input

input() 可以接收 Console 的输入,并以字符串的形式返回,你可以给定个字符串参数,它会先输出到 Console,再接收输入

In [31]

name = input("输入你的名字:")
print("あなたの名前は", name, "です")
输入你的名字:龙的传人
あなたの名前は 龙的传人 です

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

In [33]

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'


In [34]

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(",")

In [38]

a, b = input().split("*")
print(f"a = {a}, b = {b}")
1*2
a = 1, b = 2

导入模块

Python 中有许多强大的工具箱,我们把它们叫做“库”(Library),课程后期会介绍更多强大的工具

库需要使用 import 来导入,并且使用 xx.yy的方式来调用,我们今天只作粗略介绍

以 Python 内置数学库 math 为例:

In [39]

# 阶乘 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

In [3]

import math # 使用库前要先导入!
print(math.factorial(3))
6

In [48]

# Euler 常数
print(math.e)
2.718281828459045

In [49]

# gcd 最大公约数
math.gcd(12, 36)
12

In [4]

def f(x):
    a = x*(math.pi/180)
    print(math.sin(a))
interact(f,x=30)
0.49999999999999994
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

可引用Decimal函数中的decimal来缩小误差

from decimal import Decimal

print(Decimal("1.1") + Decimal("2.2"))

总结

  • 写注释是个好习惯
  • 调整输入输出的参数来控制其呈现效果
  • 大部分错误类型可以归为:语法错误、运行时错误和逻辑错误
  • Python 的库能让很多操作变方便

$\textcolor{red}{本文部分引用自网络}$

$\textcolor{red}{文章架构来源于课程ppt(免责声明)}$

课程ppt链接