首页 > 编程语言 >聪明办法学Python task03 & task04

聪明办法学Python task03 & task04

时间:2023-11-25 22:33:24浏览次数:32  
标签:return Python 20% print False task03 True task04 def

聪明办法学Python 学习笔记

chapter 2 数据类型和操作 Data Types and operator

常用内置类型 Builtin Types

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

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

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

[22]:

print(type(2))

<class 'int'>

[23]:

print(type(2.2))

<class 'float'>

[24]:

print(type(2 < 2.2))

<class 'bool'>

[27]:

print(type(type(42)))

<class 'type'>

Python 中的一些基本类型

[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 的方式讲授

后续课程中会见到的类型

[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,数学常数 e = 2.718281...,精确到可用精度
  • tau,数学常数 � = 6.283185...,精确到可用精度(其实它不常用)
  • inf,浮点正无穷大,等价于 float('inf'),负无穷大使用 -math.inf

[30]:

print(True)

print(False)

print(None)

True
False
None

[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

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

/浮点数 除法操作符

[34]:

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

 5/3  = 1.6666666666666667

// 代表 整除

[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

[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

�mod�⟺�−(�∣�)×�

[38]:

def mod(a, b):

return a - (a//b)*****b

[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

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

[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

[42]:

from IPython.display import IFrame

IFrame('https://docs.python.org/zh-cn/3.9/reference/expressions.html#operator-precedence', width=1300, height=600)

[42]:

优先顺序 Precedence

[43]:

print(2+3*****4) # 14(不是 20)

print(5+4%3) # 6(不是 0)

print(2*3****4) # 32(不是 4096)

14
6
32

结合律 Associativity

[ ]:

print(5-4-3) # -2(不是 4)

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

浮点数误差

[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

我们先来定义一些函数

[45]:

def yes():

return True

def no():

return False

def crash():

return 1/0 # 会崩溃!

[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,再来试试

[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

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

[51]:

def isPositive(n):

​ result = (n > 0)

​ print(n, "是不是正数?", result)

return result

def isEven(n):

​ result = (n % 2 == 0)

​ print(n, "是不是偶数?", result)

return result

[64]:

print(isEven(-4) and isPositive(-4)) # 调用了两个函数

-4 是不是偶数? True
-4 是不是正数? False
False

[55]:

print(isEven(-3) and isPositive(-3)) # 只调用了一个函数

-3 是不是偶数? False
False

type() vs isinstance()

[57]:

print(type("p2s") == str)

print(isinstance("p2s", str))

True
True

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

[58]:

def isNumber(x):

return ((type(x) == int) or

​ (type(x) == float))

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

[59]:

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

True True False False
  • isinstance()type() 更具有 稳健性(Robustness)
  • 这种做法更加符合 面向对象编程继承(inheritance) 的思想

[60]:

import numbers

def isNumber(x):

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

[61]:

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

True True True False

总结

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

Chapter 3 变量与函数 Variables and Functions

变量 Variables

A variable is a named value that references or stores a piece of data.

  • 变量是一个名字,它所指代的是一段数据
  • 使用 = 来对这段数据的区域进行赋值

[7]:

x = 5

[8]:

print(x)

5

[9]:

print(x*****2)

10
  • 新的值会覆盖掉旧的值
  • 新值的数据类型不必与旧值相同

[10]:

y = 10

print(y - 2)

8

[11]:

y = True

print(y)

True

变量命名规则:

  • 必须以字母或下划线(_)开头
  • 命名可由字母、数字和下划线组成
  • 大小写敏感
  • 尽量避免使用保留字命名

[12]:

numberOfRabbits = 40

courseIs15112 = True

[13]:

99problems = 0 # 会崩溃!因为变量名以数字开头

  Cell In [13], line 1
    99problems = 0 # 会崩溃!因为变量名以数字开头
      ^
SyntaxError: invalid syntax

保留字

[14]:

import keyword

keyword.kwlist

[14]:

['False',
 'None',
 'True',
 '__peg_parser__',
 'and',
 'as',
 'assert',
 'async',
 'await',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']

更新变量

[15]:

x = 5

x += 2 # 等价于 x = x + 2

print(x) # 7

7

[16]:

# 换成其他运算符也是同理

y = 350

y //= 10

print(y) # 35

35

多变量赋值

[17]:

a = b = c = 2

print(f"a={a}, b={b}, c={c}")

a=2, b=2, c=2

[18]:

a, b, c = 1, 2, 6

print(f"a={a}, b={b}, c={c}")

a=1, b=2, c=6

函数 Functions

A function is a procedure (a sequence of statements) stored under a name that can be used repeatedly by calling the name.

  • 函数是一个名字,代表一串代码序列(流程、过程)

  • 函数由两个部分组成:

    header

    body

    • header 用于定义函数接口(函数 名称参数
    • body 包含函数所需要执行的操作

header 用于定义函数的名称参数

  • 当函数被调用时,参数将会作为变量被提供给函数的 body 部分
  • 可以提供多个参数(用逗号 , 分隔),也可以不提供参数(0 个)
  • header 以冒号(:)结尾,代表后面会跟着 body 部分

函数的 header 的写法:

[19]:

def functionName(parameters):

pass # 函数的 body 部分,这里使用 pass 代替

body

body 包含函数执行的语句(statement

  • 语句需要缩进(由 Code Style Guide 决定)
  • 当语句不再缩进,函数部分结束
  • 一般会使用 return 语句,来让函数返回其结果,但不是必须的

类似于用一个 = 来对多个变量赋值,函数的返回结果也可以不止一个(用逗号 , 分隔)

下面我们用一个例子来解释函数的细节

[21]:

def double(x):

​ print("我在一个名叫 “double” 函数里!")

return 2 ***** x

  • 我们使用函数名来调用函数
  • 函数名后紧跟一对括号
  • 括号中是我们设定的参数的,一个不多,一个不少(这很重要)
  • 函数会返回设定的 return 语句的值

调用示例函数 double() 会返回一个值(2 * x

[23]:

print(double(2)) # 会输出 4

我在一个名叫 “double” 函数里!
4

[25]:

print(double(5)) # 会输出 10

我在一个名叫 “double” 函数里!
10

[26]:

print(double(1) + 3) # 会输出 5

我在一个名叫 “double” 函数里!
5

函数可以有任意多个参数,也可以一个都没有

[27]:

# 三个参数

def f(x, y, z):

return x + y + z

print(f(1, 3, 2)) # 返回 6

6

[28]:

# 无参数

def g():

return 42

print(g()) # 返回 42

42

可是如果参数数目没有匹配的话……Oops!

[29]:

print(g(2)) # 崩溃!

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [29], line 1
----> 1 print(g(2))

TypeError: g() takes 0 positional arguments but 1 was given

[30]:

print(f(1, 2)) # 也会崩溃

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [30], line 1
----> 1 print(f(1, 2))

TypeError: f() missing 1 required positional argument: 'z'

多返回值

[31]:

def Multi_Return_Values():

return 9, 2, 8

[32]:

a, b, c = Multi_Return_Values()

print(f"a={a}, b={b}, c={c}")

a=9, b=2, c=8

语句与表达式 Statements and Expressions

An expression is a data value or an operation that evaluates to a value.

对于表达式

  • 它本身是
  • 它的计算结果是值

Statements, by contrast, do not evaluate to a value, and we can't print them. Usually they perform some action, though.

对于语句

  • 它不是值
  • 它不能打印
  • 但它能执行一些操作

表达式的一些例子

[33]:

4

[33]:

4

[34]:

"Hello World"

[34]:

'Hello World'

[35]:

7 + 2

[35]:

9

[36]:

True or False

[36]:

True

[37]:

(2 < 3) and (9 > 0)

[37]:

True

Python 只能 print 值和表达式,如果你能用 print() 输出它,那它就是表达式

[38]:

print((2 < 3) and (9 > 0))

True

语句的一些例子

[39]:

def f(x):

return 5*****x

[40]:

x = 5 + 4

[42]:

if 10 > 5:

​ y = 5 + 3

内置函数 Builtin Functions

就是 Python 自己带的函数啦

标签:return,Python,20%,print,False,task03,True,task04,def
From: https://www.cnblogs.com/blog4my/p/17856248.html

相关文章

  • 聪明方法学python task2,task3
    数据类型类型Type本身也是类型Float默认双精度Moudle内置常数None表示空值tau(2*pi)inf,浮点正无穷大,等价于float(‘inf’),负无穷大使用-math.inf逻辑运算符not类比c语言‘!’and,or类比&&和||浮点数误差`print(0.1+0.1==0.2)#True``print(0......
  • 聪明办法学Python任务笔记
    数据类型和操作Python中数据类型与C语言相似,常见的有整数型(Integer)int,浮点数Float,布尔值型Boolean(bool),类型type,字符串string等。Python中比较特殊的是列表LIst,元组Tuple,集合Set,字典Dictionary这几种数据类型。下面是几种数据类型的用途:内置常数:Boolean:True用于表示......
  • python 设置镜像
    清华镜像源pipconfigsetglobal.index-urlhttps://pypi.tuna.tsinghua.edu.cn/simple>WritingtoC:\Users\Administrator\AppData\Roaming\pip\pip.ini临时包设置pipconfigsetindex-urlhttps://pypi.tuna.tsinghua.edu.cn/simple 中科大镜像https://mirrors.ustc.......
  • 聪明办法学python第二次任务笔记
    笔记数据类型int整型float浮点型bool布尔型True和False表示and运算是与运算,只有所有都为True,and运算结果才是Trueor运算是或运算,只要其中有一个为True,or运算结果就是Truenot运算是非运算,它是一个单目运算符,把True变成False,False变成Truestr字符串空值用None......
  • 聪明办法学python-11.23——11.26笔记打卡
      python的数据类型和操作1.数据类型和运算符:基本类型是:整形int  如1、34、-12浮点型float  如 1.23、-2.44布尔值bool  有真“True”假“False”  类型type 如:print(type(2))输出为:<class......
  • pythonDay17
    叠加多个装饰器的加载、运行分析 分析图 f......
  • 聪明办法学Python_task2_11.22-11.26
    数据类型int(整型,即整数)str(字符串,单个长度使长度为1的字符串)float(浮点型,即小数,默认为双精度)bool(TrueorFalse)可通过type()函数输出数据类型强制转换,int(“1”)将字符串转化为整型1###整型,浮点型(数字型数据类型):可以对数字数据进行数学处理。int类型将省去小数部分。这意味......
  • python变量和简单类型
    数据类型整型python的整型数值有4种表示形式:十进制形式二进制形式:以0b或0B开头的整数就是二进制形式的整数八进制形式:以0o或0O开头的整数就是八进制形式的整数十六进制形式:以0x或0X开头的整数就是十六进制形式的整数,其中10-15分别以a-f(a-f不区分大小写)来表......
  • python3使用libpcap给ESL命令添加日志记录
    操作系统:CentOS7.6_x64FreeSWITCH版本:1.10.9python版本:3.9.12libpcap版本:1.11.0b7 FreeSWITCH的ESL模块用起来很方便,可以控制FreeSWITCH实现具体业务需求,但该模块没有提供ESL命令执行日志,不便于排查问题,本文展示一种使用python3基于libpcap实现ESL命令执行日志的方法,并......
  • Java开发者的Python快速进修指南:面向对象基础
    当我深入学习了面向对象编程之后,我首先感受到的是代码编写的自由度大幅提升。不同于Java中严格的结构和约束,Python在面向对象的实现中展现出更加灵活和自由的特性。它使用了一些独特的关键字,如self和cls,这些不仅增强了代码的可读性,还提供了对类和实例的明确引用。正如Java,Python也......