0
点赞
收藏
分享

微信扫一扫

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

谷中百合517 2022-04-17 阅读 20
python

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

学习目标

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

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

print("hello world")
hello world
print(222)
222
print("hello world")
print("hello again")
hello world
hello 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)

# \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设置一个执行单元多个输出,只需要执行一次下方代码即可

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。

first_number = 22
first_number
22
a = "this is a string"
a
'this is a string'

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

x = 9
if x < 8:
    print("x is lower than 8")
else:
    print("x is bigger than 8")
x is bigger than 8
speed = 100 / 15
distance = 1000
time = distance / speed
print(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 = -2
print(a)
-2
b = 5
b += 5   #等同于b = b + 5
print(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.141592653589793
2.718281828459045
#向下求整
print(math.floor(98.77))
#向上求整
print(math.ceil(98.77))
98
99
#求幂的两种方法
print(math.pow(2,4))
print(2**4)

#两种方法求出来的结果数据类型不一样
print(type(math.pow(2,4)))#数学包计算出来是浮点型
print(type(2**4))#直接计算是整型
16.0
16
<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
a = (2 == 1)#先计算括号内为False再赋值给a
print(a)
False
a = (2 != 1)
print(a)
True

4.4 String 字符串型

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

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  test
lalala
''')
this is 
a  test
lalala
#将字符串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 字符串提取和切片

letters = "abcdefghijklmn"
letters[1]#[n] n为下标,取第几个字符,字符串下标从0开始,即a的下标是0,b的下标是1,c的下标是2...以此类推
'b'
letters[13]
'n'
letters[14]#超出下标范围会报错
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_192/2629420110.py in <module>
----> 1 letters[14]#超出下标范围会报错


IndexError: string index out of range
letters[-1]#反向取值,从后往前倒序取值
'n'

4.4.3 切片:提取子字符串

格式: arr[start🔚step]

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🔚step]从开始到(结束-1),根据步长跳过字符取值

letters = "0123456789"
letters[0:9:3]#此时步长为3,即跳过2个字符取值
'036'
letters[::2]#全部取值,步长为2,即跳过1个字符取值
'02468'
letters[::-2]#全部逆向取值,步长为2
'97531'

4.4.4 求字符串长度

letters = "abcdefghijklmn"
len(letters)
14
len("Python description:Python is a programming ")

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']
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'
test.replace("cloudy","sunny",1)#替换次数,1表示只替换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 SMITH
harry smith
#方法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.  '
favorite_language = "##python##"
print(favorite_language.rstrip("#"))#去掉尾部固定字符
print(favorite_language.lstrip("#"))#去掉头部边固定字符
print(favorite_language.strip("#"))#去掉头尾固定字符
##python
python##
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" + 10


TypeError: 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输出(从显示器)

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?lulugege
how old are you?38
how tall are you?181
so,your name is lulugege,your are 38 years old, 181 meters tall
so,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?
lulugege
how old are you?
38
how tall are you?
181
so,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、目的:在https://pvp.qq.com/web201605/herolist.shtml 中提取三个英雄头像图片、英雄名称并换行输出

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

3、输出结果参考样式:

输出结果参考样式

HTML素材如下:

  • 女娲女娲
  • 梦奇梦奇
  • 百里守约百里守约
您的代码:
举报

相关推荐

0 条评论