首页 > 其他分享 >Datewhale学习笔记02

Datewhale学习笔记02

时间:2023-11-25 18:44:56浏览次数:21  
标签:02 False 0.1 type 笔记 Datewhale print crash True

Datewhale学习笔记2

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

聪明办法学 Python 2nd Edition

Chapter 2 数据类型和操作 Data Types and Operators

In [15]

import math
def f():
    return 42

常用内置类型 Builtin Types

我们提前导入了 math 库,并创建了一个函数 f() (内容并不重要)

在本节中,我们将要见到这些基本类型:

  • 整数 Integer(int)
  • 浮点数 Float
  • 布尔值 Boolean(bool)
  • 类型 Type(是的,“类型”也是种类型!)

严格的来说,Type 是一种 对象,Python 是一门“面向对象友好”的语言

In [22]

print(type(2))
<class 'int'>

In [23]

print(type(2.2))
<class 'float'>

In [24]

print(type(2 < 2.2))
<class 'bool'>

In [27]

print(type(type(42)))
<class 'type'>

Python 中的一些基本类型

In [28]

print(type(2))           # int
print(type(2.2))         # float
print(type(2 < 2.2))     # bool (boolean)
print(type(type(42)))    # type 
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'type'>

在今后的内容中,我们将会见到更多类型:

  • 字符串 String(str)
  • 列表 List
  • 元组 Tuple
  • 集合 Set
  • 字典 Dictionary(dict,或者你可以叫它 映射 map
  • 复数 Complex Number(complex)
  • 函数 Function
  • 模块 Module

strlisttuplesetdict 将尝试用 数组 Array 的方式讲授

后续课程中会见到的类型

In [29]

print(type("2.2"))       # str (string or text)
print(type([1,2,3]))     # list
print(type((1,2,3)))     # tuple
print(type({1,2}))       # set
print(type({1:42}))      # dict (dictionary or map)
print(type(2+3j))        # complex  (complex number)
print(type(f))           # function
print(type(math))        # module
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
<class 'complex'>
<class 'function'>
<class 'module'>

常用内置常数 Builtin Constants

常数区别于变量(将在下节课讲授),常数的值是固定的、不可改变的

Python 内置了一些常量

  • True,用于表示 布尔
  • False,用于表示 布尔
  • None,代表 ,用于空值

math 库中的一些数学常量

  • pi,数学常数 �π = 3.141592...,精确到可用精度
  • e,数学常数 ee = 2.718281...,精确到可用精度
  • tau,数学常数 �τ = 6.283185...,精确到可用精度(其实它不常用)
  • inf,浮点正无穷大,等价于 float('inf'),负无穷大使用 -math.inf

In [30]

print(True)
print(False)
print(None)
True
False
None

In [31]

print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)
print(-math.inf)
3.141592653589793
2.718281828459045
6.283185307179586
inf
-inf

常用内置运算符 Builtin Operators

  • 算术:+, -, *, @, /, //, **, %, - (一元算符), + (一元算符)
  • 关系:<, <=, >=, >, ==, !=
  • 赋值: +=, -=, *=, /=, //=, **=, %=
  • 逻辑:and, or, not

我们暂时跳过按位运算符

整除 Integer Division (//)

这个知识点可能会在作业中发挥很大的作用,所以请多花些时间来理解它的运作方式

/` 指的是**浮点数**除法,它的结果是一个浮点数,例如 `2/1` 的结果是 `2.0

// 指的是整除除法,它的计算结果是整数,舍弃余数

/浮点数 除法操作符

In [34]

print(" 5/3  =", (5/3))
 5/3  = 1.6666666666666667

// 代表 整除

In [1]

print(" 5//3 =", ( 5//3))
print(" 2//3 =", ( 2//3))
print("-1//3 =", (-1//3))
print("-4//3 =", (-4//3))
 5//3 = 1
 2//3 = 0
-1//3 = -1
-4//3 = -2

模运算或余数运算符 (%)

这个知识点可能会在作业中发挥很大的作用,所以请多花些时间来理解它的运作方式

% 代表模运算(取余),结果为商的余数

例如:5 整除 2 的结果是 2余数1,则 5 % 2 的结果为 1

In [40]

print(" 6%3 =", ( 6%3))
print(" 5%3 =", ( 5%3))
print(" 2%3 =", ( 2%3))
print(" 0%3 =", ( 0%3))
print("-4%3 =", (-4%3))
print(" 3%0 =", ( 3%0))
 6%3 = 0
 5%3 = 2
 2%3 = 2
 0%3 = 0
-4%3 = 2

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [40], line 6 4 print(" 0%3 =", ( 0%3)) 5 print("-4%3 =", (-4%3)) ----> 6 print(" 3%0 =", ( 3%0)) ZeroDivisionError: integer division or modulo by zero

$ a \mod b \iff a - (a \mid b) \times b $

In [38]

def mod(a, b):
  return a - (a//b)*b

In [39]

print(41%14 == mod(41,14))
print(14%41 == mod(14,41))
print(-32%9 == mod(-32,9))
print(32%-9 == mod(32,-9))
True
True
True
True

补充资料:注意 %math.fmod() 的区别,详见:Modulo operation

类型影响语义 Types Affect Semantics

运算符的运作方式会受到运算数据的类型的影响

In [41]

print(3 * 2)
print(3 * "p2s")
print(3 + 2)
print("Data" + "whale")
print(3 + "p2s")
6
p2sp2sp2s
5
Datawhale

---------------------------------------------------------------------------****TypeError Traceback (most recent call last)Cell In [41], line 5 3 print(3 + 2) 4 print("Data" + "whale") ----> 5 print(3 + "p2s") TypeError: unsupported operand type(s) for +: 'int' and 'str'

运算符优先级 Operator Order

优先顺序与结合律 Precedence and Associativity

In [1]

from IPython.display import IFrame
IFrame('https://docs.python.org/zh-cn/3.9/reference/expressions.html#operator-precedence', width=1300, height=600)
<IPython.lib.display.IFrame at 0x7fe502621360>

优先顺序 Precedence

In [43]

print(2+3*4)  # 14(不是 20)
print(5+4%3)  # 6(不是 0)
print(2**3*4) # 32(不是 4096)
14
6
32

结合律 Associativity

In [ ]

print(5-4-3)   # -2(不是 4)
print(4**3**2) # 262144(不是 4096)

浮点数误差

In [2]

print(0.1 + 0.1 == 0.2)        # True
print(0.1 + 0.1 + 0.1 == 0.3)  # False!
print(0.1 + 0.1 + 0.1)         # Why?
print((0.1 + 0.1 + 0.1) - 0.3) # 特别小,但不是 0
True
False
0.30000000000000004
5.551115123125783e-17

短路求值 Short-Circuit Evaluation

逻辑运算参照表

X Y X and Y X or Y not X not Y
True True True True False False
True False False True False True
False False False False True True
False True False True True False

我们先来定义一些函数

In [45]

def yes():
    return True

def no():
    return False

def crash():
    return 1/0 # 会崩溃!

In [47]

print(no() and crash()) # 成功运行!
print(crash() and no()) # 崩溃了!
print (yes() and crash()) # 因为上一行崩溃了,所以这行不会被运行,就是运行也会因为短路求值崩溃
False

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [47], line 3 1 print(no() and crash()) # 成功运行! ----> 3 print (yes() and crash()) Cell In [45], line 8, in crash() 7 def crash(): ----> 8 return 1/0 ZeroDivisionError: division by zero

我们换成 or,再来试试

In [50]

print(yes() or crash()) # 成功运行
# print(crash() or yes()) # 崩溃了
print(no() or crash())  # 因为上一行崩溃了,所以这行不会被运行,就是运行也会因为短路求值崩溃
True

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [50], line 3 1 print(yes() or crash()) # 成功运行 2 # print(crash() or yes()) # 崩溃了 ----> 3 print(no() or crash()) Cell In [45], line 8, in crash() 7 def crash(): ----> 8 return 1/0 ZeroDivisionError: division by zero

再来个例子,我们也先定义些函数

In [51]

def isPositive(n):
    result = (n > 0)
    print(n, "是不是正数?", result)
    return result

def isEven(n):
    result = (n % 2 == 0)
    print(n, "是不是偶数?", result)
    return result

In [64]

print(isEven(-4) and isPositive(-4)) # 调用了两个函数
-4 是不是偶数? True
-4 是不是正数? False
False

In [55]

print(isEven(-3) and isPositive(-3)) # 只调用了一个函数
-3 是不是偶数? False
False

type() vs isinstance()

In [57]

print(type("p2s") == str)
print(isinstance("p2s", str))
True
True

任务:编写代码,判断 x 是不是数字

In [58]

def isNumber(x):
    return ((type(x) == int) or
            (type(x) == float)) 

你能确保它能够判断所有数字吗?

In [59]

print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
True True False False
  • isinstance()type() 更具有 稳健性(Robustness)
  • 这种做法更加符合 面向对象编程继承(inheritance) 的思想

In [60]

import numbers
def isNumber(x):
    return isinstance(x, numbers.Number) # 可以应对任何类型的数字

In [61]

print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
True True True False

总结

  • Python 的类型系统很丰富,可以使用 type() 查看对应的类型
  • 常数类型的值是不可修改的
  • 除法操作默认是浮点数除法,整除操作需要使用 //
  • 运算符之间有运算优先级,运算符作用于不同对象之间的效果是不同的
  • 在进行逻辑判断时,会使用短路求值

原文链接

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

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

课程ppt链接

标签:02,False,0.1,type,笔记,Datewhale,print,crash,True
From: https://www.cnblogs.com/liuyunhan/p/17855860.html

相关文章

  • 2023-2024-1 20232311 《网络空间安全导论》第3周学习总结
    2023-2024-120232311《网络空间安全导论》第3周学习教材内容学习总结网络空间安全导论第三章思维导图教材学习中的问题和解决过程问题1:不理解IP数据包结构问题1解决方案:询问chatgpt,令chatgpt举出了具体的示例以辅助理解问题2:不理解防火墙的具体原理问题2解决方案:查找了......
  • NOIP 2023比赛报告
    第一题比赛情况$100$分,耗时$1$小时。题解对于$1\lei\len$,比较$w_i$字典序最小的字符$a_i$与每个$w_j(i\nej)$字典序最大的字符$b_j$。如果有$b_j\lea_i$,则$w_i$不能成为字典序最小的单词,反之可以。代码第二题比赛情况$100$分,耗时$2$小时。题解......
  • 笔记·数据类型与类型转换
    笔记·数据类型与类型转换数据类型Number(数字)python中的数字分为以下四种类型int(整数):python中的int对应C语言中的长整型float(浮点数):小数bool(布尔类型):int的子类型,其中False==0True==1complex(复数):由实数部分与虚数部分构成,可表示为complex(a,b),其中a代表实部,b代表虚部......
  • 2023-11-25:用go语言,给定一个数组arr,长度为n,表示n个格子的分数,并且这些格子首尾相连, 孩
    2023-11-25:用go语言,给定一个数组arr,长度为n,表示n个格子的分数,并且这些格子首尾相连,孩子不能选相邻的格子,不能回头选,不能选超过一圈,但是孩子可以决定从任何位置开始选,也可以什么都不选。返回孩子能获得的最大分值。1<=n<=10^6,0<=arr[i]<=10^6。来自华为od。来自左程......
  • 《信息安全系统设计与实现》第十二周学习笔记
    《信息安全系统设计与实现》第十二周学习笔记第13章TCP/IP和网络编程TCP/IP协议TCP/IP协议是利用IP进行通信时所必须用到的协议群的统称。具体来说,IP或ICMP、TCP或UDP、TELNET或FTP、以及HTTP等都属于TCP/IP协议。他们与TCP或IP的关系紧密,是互联网必不可少的......
  • 2023版Web前端架构师:引领前端开发的创新与变革
    2023版Web前端架构师:引领前端开发的创新与变革一、前言随着互联网技术的飞速发展,Web前端领域也在不断演进。作为一名2023版的Web前端架构师,你需要具备广博的技术知识、卓越的架构能力以及敏锐的市场洞察力,从而引领前端开发的创新与变革。本文将为你揭示如何在这个充满挑战与机遇的......
  • 学习笔记11
    网络编程是一种涉及计算机网络的软件开发技术,它允许不同计算机之间的通信和数据交换。在网络编程中,TCP/IP协议是基础,它定义了数据如何在网络上进行传输。TCP/IP协议TCP/IP(TransmissionControlProtocol/InternetProtocol)是一组通信协议,它是互联网通信的基础。主要包括TCP和IP......
  • 第十二周学习笔记(学习笔记11)
    〇、思维导图一、知识点总结论述TCP/IP协议及其应用,具体包括TCP/IP栈、IP地址、主机名、DNS、IP数据包和路由器;2.介绍TCP/IP网络中的UDP和TCP协议、端口号和数据流;3.阐述服务器—客户机计算模型和套接字编程接口;4.介绍Web和CGI编程,解释HTTP编程模型、Web页面和Web浏览器......
  • CSharp: vs 2022
    package.json {"name":"healthcheck","version":"0.0.0","scripts":{"ng":"ng","start":"echoStarting...&&ngserve","build&......
  • Linux—终端常用指令20218573
     导言:Linux操作系统的终端是用户与系统进行交互的重要界面,通过终端可以执行各种任务和操作。本文将详细介绍Linux终端中的常用指令,为初学者提供一个全面的指南,帮助他们更好地理解和利用Linux系统。1.认识Linux终端:Linux终端是用户通过命令行方式与操作系统进行交互的工具。了......