1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python零基础速成班-第2讲-Python基础(上) 运算 变量 数据类型 输入输出

Python零基础速成班-第2讲-Python基础(上) 运算 变量 数据类型 输入输出

时间:2023-01-21 13:17:51

相关推荐

Python零基础速成班-第2讲-Python基础(上) 运算 变量 数据类型 输入输出

Python零基础速成班-第2讲-Python基础(上),运算、变量、数据类型、输入输出

学习目标

使用print输出结果运算及运算符变量数据类型(4种最常用的)输入输出课后作业(4必做+1挑战)

友情提示:

1、将下文中代码拷贝到JupyterNotebook中直接执行即可,部分代码需要连续执行。

2、JupyterNotebook安装教程及期初课程起初准备请参看上一讲。Python零基础速成班-第1讲-认识Python,课程目标,安装环境以及完成第一行代码“hello world”

1、输出:使用print输出字符串、数字

print("hello world")

hello world

print(222)

222

print("hello world")print("hello again")

hello worldhello again

print("This is the 3rd line,","this is the 4th line.")

This is the 3rd line, this is the 4th line.

特别注意\t和\n的用法

\t 表示四个空格(Space),也称缩进,相当于按一下Tab键

\n 表示换行,相当于按一下回车(Enter)

进阶提示1:在C、Java等语言的语法中规定,必须以分号作为语句结束的标识。Python也支持分号,同样用于一条语句的结束标识。但在Python中分号的作用已经不像C、Java中那么重要了,Python中的分号可以省略,主要通过换行来识别语句的结束。

进阶提示2:在循环语句和Function等代码块中,python是通过缩进来区分代码块的,缩进通常是一个Tab键(等同于4个空格)。

\t表示Tab缩进

print("This is the 3rd line,\tthis is the 4th line.")

This is the 3rd line,this is the 4th line.

print("This is the 3rd line,\this is the 4th line.")

This is the 3rd line,this is the 4th line.

\n表示换行

print("This is the 3rd line,\nthis is the 4th line.")

This is the 3rd line,this is the 4th line.

type用于求证数据的类型

字符串型

type("first")

str

整型

type(1111)

int

浮点型

type(111.111)

float

布尔型

type(False)

bool

2、运算

运算规则–> 数字1 运算符 数字2

运算符–> + - * /

数字–>1,2,3,4…

3 + 4

7

3 / 4

0.75

print(3 / 4)

0.75

刘翔能跑多快? 110米栏,13秒

print(110/12.97)

8.481110254433307

求余数

print(10 % 4)

2

求幂

print(4 ** 3)

64

求商

print(9 // 2)

4

被除数为负值求商

print(-9 // 2)

-5

小提示:jupyter notebook设置一个执行单元多个输出,只需要执行一次下方代码即可

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = “all”

3、变量

Python变量命名规则:

1、变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。

2、变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名send_message可行,但变量名send message会引发错误。

3、不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print

4、变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。

5、慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。

进阶提示:应尽量使用小写的Python变量名。在变量名中使用大写字母虽然不会导致错误,但避免使用大写字母是个不错的主意。

first_number = 22first_number

22

a = "this is a string"a

'this is a string'

和其它程序设计语言(如 Java、C 语言)采用大括号“{ }”分隔代码块不同,Python采用代码缩进和冒号( : )来区分代码块之间的层次。

x = 9if x < 8:print("x is lower than 8")else:print("x is bigger than 8")

x is bigger than 8

speed = 100 / 15distance = 1000time = distance / speedprint(time)

150.0

4、数据类型

Python常用的数据类型包括以下4种:

1.Integer(int) 整型

2.Float(float) 浮点型

3.Boolean(bool) 布尔型(True or False)

4.String(str) 字符串型

4.1 Int 整型

包含所有的整数,例如 0、5、42、100000 …,在python3中理论上整数长度是无限的(只要内存足够大)

a = -2print(a)

-2

b += 5等同于b = b + 5

b = 5b += 5print(b)

10

+= 加法赋值运算符 c += a 等效于 c = c + a

-= 减法赋值运算符 c -= a 等效于 c = c - a

*= 乘法赋值运算符 c *= a 等效于 c = c * a

/= 除法赋值运算符 c /= a 等效于 c = c / a

%= 取模赋值运算符 c %= a 等效于 c = c % a

**= 幂赋值运算符 c **= a 等效于 c = c ** a

//= 取整除赋值运算符 c //= a 等效于 c = c // a

求商,整数

99 // 2

49

求余,整数

99 % 2

1

type(99 // 2)

int

4.2 Float 浮点型

有小数点的数字,例如 3.14159、1.0e8、10000.00 …

type(100.01)

float

9.8235e2

982.35

4.2.1 Math Functions 引入数学包

import math

print(math.pi)print(math.e)

3.1415926535897932.718281828459045

floor向下求整

ceil向上求整

print(math.floor(98.77))print(math.ceil(98.77))

9899

求幂的两种方法

两种方法求出来的结果数据类型不一样

math数学包计算出来结果是浮点型,而直接计算结果是整型

print(math.pow(2,4))print(2**4)print(type(math.pow(2,4)))print(type(2**4))

16.016<class 'float'><class 'int'>

开方

print(math.sqrt(16))

4.0

4.3 Boolean 布尔型

包含两种类型 True or False

type(1 < 2)

bool

(1 < 3) or (3 < 1)

True

(1 < 3) and (3 < 1)

False

not (1 < 2)

False

先计算括号内为False再赋值给a

a = (2 == 1)print(a)

False

a = (2 != 1)print(a)

True

4.4 String 字符串型

字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。

进阶提示:您可以使用 “string” 或者 'string’来表示字符串,一般情况下单引号等同于双引号。

双引号

print("this is a test")

this is a test

单引号

print('this is a test')

this is a test

双引号内嵌套单引号效果

print("it's a test")

it's a test

混合效果

print("aaaa'a\"aa'a'a\"a'a")

aaaa'a"aa'a'a"a'a

单引号内嵌套双引号效果

print('I like "中国李宁"')

I like "中国李宁"

使用3个引号表示多行字符串文本

print('''this is a testlalala''')

this is a testlalala

将字符串10转化为整型10,即可以进行运算

1089 + int("10")

1099

将整型10转化为字符串10,即可以进行字符串拼接

"1098"+ str(10)

'109810'

True和False可以进行运算,True为1,False为0

True + 3

4

3 - False

3

4.4.1 字符串拼接和复制

template = "my name is"name = "Lily"greeting = template + " " + name + "."print(greeting)

my name is Lily.

用"*"对字符串快速进行赋值

laugh = 3 * "ha "print(laugh)

ha ha ha

4.4.2 字符串提取和切片

[n] 为下标,取第几个字符,字符串下标从0开始,即a的下标是0,b的下标是1,c的下标是2…以此类推

letters = "abcdefghijklmn"letters[1]

'b'

letters[13]

'n'

超出下标范围会报错

letters[14]

---------------------------------------------------------------------------IndexError Traceback (most recent call last)~\AppData\Local\Temp/ipykernel_192/262940.py in <module>----> 1 letters[14]#超出下标范围会报错IndexError: string index out of range

反向取值,从后往前倒序取值

letters[-1]

'n'

4.4.3 切片:提取子字符串

格式: arr[start:end:step]

语法:切取 [ start,end) 的元素,注意是 左闭 右开,步长为 step(当步长为负数表示逆序)。即左边取到 start,右边取不到 end

start 缺省表示从最左边 index = 0 开始

end 缺省表示取到最右边 index = len(arr) - 1

step 缺省表示步长为1

letters = "abcdefghijklmn"letters[0:3]

'abc'

[start:]从start开始到结束所有字符

letters[3:]

'defghijklmn'

letters[-3:]

'lmn'

[:end]从开始到end-1逆序偏移

letters[:4]

'abcd'

letters[:-4]

'abcdefghij'

letters[:100]

'abcdefghijklmn'

[start:end] 从开始到(结束-1),即不包括end

letters[1:3]

'bc'

letters[-6:-2]

'ijkl'

letters[-2:-6]

''

[start:end:step]从开始到(结束-1),根据步长跳过字符取值

此时步长为3,即跳过2个字符取值

letters = "0123456789"letters[0:9:3]

'036'

全部取值,步长为2,即跳过1个字符取值

letters[::2]

'02468'

全部逆向取值,步长为2

letters[::-2]

'97531'

4.4.4 求字符串长度

letters = "abcdefghijklmn"len(letters)

14

len("Python description:Python is a programming ")

43

4.4.5 字符串拆分和拼接

拆分为数组格式

默认根据空格拆分

lan = "today is a cloudy day"lan.split()

['today', 'is', 'a', 'cloudy', 'day']

根据","来拆分字符

tan = "today,is,a, cloudy,day"tan.split(',')

['today', 'is', 'a', ' cloudy', 'day']

默认根据空格拆分,这里就拆分为2个元素

print(tan)tan.split()

today,is,a, cloudy,day['today,is,a,', 'cloudy,day']

join拼接字符串,语法:“n”.join,即根据引号内n的内容来分隔并拼接字符串

例如 “”.join表示直接拼接字符串," “.join表示空格为分隔拼接字符串,”-".join表示-为分隔拼接字符串

根据","分隔拼接字符串

t = ","t.join("today")

't,o,d,a,y'

"|".join("today is a cloudy day")

't|o|d|a|y| |i|s| |a| |c|l|o|u|d|y| |d|a|y'

如拼接的内容为数组,则根据分隔符和数组里面的每个元素来拼接成字符串

"|".join(["today"," is" , " a" ," cloudy"," day" ])

'today| is| a| cloudy| day'

4.4.6 字符串替换

默认全部替换

test = "today is a cloudy day,a cloudy day,a cloudy day,a cloudy day"test.replace("cloudy","sunny")

'today is a sunny day,a sunny day,a sunny day,a sunny day'

替换次数,1表示只替换1次

test.replace("cloudy","sunny",1)

'today is a sunny day,a cloudy day,a cloudy day,a cloudy day'

4.4.7 字符串布局

center居中对齐,空格填充

align = 'learn how to align'align.center(30)

'learn how to align'

左对齐,空格填充剩余

align.ljust(30)

'learn how to align '

右对齐,空格填充剩余

align.rjust(30)

' learn how to align'

strip()方法去掉首尾空格

ralign = align.rjust(30)ralign.strip()

'learn how to align'

4.4.8其他常用方法

方法title() 将每个单词首字母改为大写

name = "harry smith"print(name.title())

Harry Smith

方法upper() 将单词所有字母改为大写

方法lower() 将单词所有字母改为小写

name = "harry smith"print(name.upper()) print(name.lower())

HARRY SMITHharry smith

进阶提示:存储数据时,方法lower() 很有用。很多时候,你无法依靠用户来提供正确的大小写,因此需要将字符串先转换为小写,再存储它们。以后需要显示这些信息时,再将其转换为最合适的大小写方式。

方法startwith() 表示是否以某些字符开头,返回bool

py_desc = "Python description:Python is a programming language that let you work quickly and effictively."py_desc.startswith("Python description:")

True

方法endwith() 表示是否以某些字符结尾,返回bool

py_desc.endswith("work quickly and effictively.")

True

方法find() 表示查询某些字符,返回最开始找到的位置,未找到则返回-1

py_desc = "Python description:Python is a programming language that let you work quickly and effictively."py_desc.find('language')

43

方法count() 表示寻找某些字符出现的次数

py_desc = "Python description:Python is a programming language that let you work quickly and effictively."py_desc.count("Python")

2

去掉头尾固定字符,默认位空格,可以自定义并传入参数

py_desc = "*Python description .Python is a programming language that let you work quickly and effictively. "py_desc.strip('*')

'Python description .Python is a programming language that let you work quickly and effictively. '

rstrip去掉尾部固定字符

lstrip去掉头部边固定字符

strip去掉头尾固定字符

favorite_language = "##python##"print(favorite_language.rstrip("#"))print(favorite_language.lstrip("#"))print(favorite_language.strip("#"))

##pythonpython##python

4.5 数据类型转换

int + float = float

10 + 10.1

20.1

类型不一致,不能相加,报错

"10" + 10

---------------------------------------------------------------------------TypeError Traceback (most recent call last)~\AppData\Local\Temp/ipykernel_192/1141157989.py in <module>1 #类型不一致,不能相加,报错----> 2 "10" + 10TypeError: can only concatenate str (not "int") to str

字符串拼接

"10" + "110"

'10110'

整型转字符串,再拼接

str(10) + "110"

'10110'

字符串转整型,再相加

10 + int("110")

120

字符串相加

str(True) + "3"

'True3'

数值相加,True=1,False=0

True + 3.0

4.0

5、输入输出

input输入(从键盘),print输出(从显示器)

进阶提示:python中的%s %d即格式化字符串,使用后,在需要输出的长字符串中占位置。输出字符串时,可以依据变量的值,自动更新字符串的内容。

常用的格式化字符串如下:

%s 字符串 (采用str()的显示)

%d 十进制整数

%f 浮点数

%c 单个字符

%r 字符串 (采用repr()的显示)

name = input("what's your name?")age = input("how old are you?")height = input("how tall are you?")print("so,your name is %s,your are %s years old, %s meters tall" % (name,age,height))print("so,your name is" +" " + name)

what's your name?lulugegehow old are you?38how tall are you?181so,your name is lulugege,your are 38 years old, 181 meters tallso,your name is lulugege

加入\n实现输入换行效果

name = input("what's your name?\n")age = input("how old are you?\n")height = input("how tall are you?\n")print("so,your name is %s,your are %s years old, %s meters tall" % (age,name,height))

what's your name?lulugegehow old are you?38how tall are you?181so,your name is 38,your are lulugege years old, 181 meters tall

6、课后作业,答案在下一讲

1、写一个程序读取输入的两个数字,并把数字加起来输出

您的代码:

2、动手编程 利用Python计算一下公式

21980 + 987345

4950782 - 2340985

3456 * 4390

9285 / 5

57的21次方

98434 / 456 的余数

您的代码:

3、输入一个数,这个数代表从凌晨0点,过去的分钟数,请计算并输出当前时间

本程序需要输出两个小数:小时(0到23):分钟(0到59)

例如,如果你输入是150,那么应该是2:30了,所以你程序应该输出2:30

您的代码:

4、利用Python表达以下公式

b ∗ ( 1 + r 100 ) n b*(1+\frac{r}{100})^n b∗(1+100r​)n

a 2 + b 2 b \sqrt \frac{a^2+b^2}{b} ba2+b2​ ​

您的代码:

*(挑战)5、编程实践项目

小项目:王者荣耀英雄信息提取

1、目的:在/web05/herolist.shtml 中提取三个英雄头像图片、英雄名称并换行输出

2、方法:截取王者荣耀英雄列表HTML文本,采用字符串相关操作提取需要的信息

3、输出结果参考样式:

HTML素材如下:

女娲梦奇百里守约

您的代码:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。