Strawberry-Python

提示:版权归Strawberry所有(大数据2202Byj)
未经授权,禁止搬用。

Python

1.变量和简单数据类型

1.1.运行hello_worold.py时发生的情况

print("Hello Python world")

输出

Hello Python world

1.2.变量

例1.

message = "Hello Python world"
print(message)

输出

Hello Python world

例2.

message = "Hello Python world"
print(message)
message = "Hello Python Crash Course world"
print(message)

输出

Hello Python world
Hello Python Crash Course world
#总结:在程序中可随时修改变量的值,而python将始终记录变量的最新值

1.2.1变量的命名和使用

1.变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量名位message_1但是不能将其命名为1_message
2.变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但是变量名greeting message会报错
3.不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print
4.变量名应既简短又具有描述性。例如name比n好,student_name比s_n好。
5.慎用l和O,因为它们可能被人看成数字1或0

1.2.2使用变量时避免命名错误

message = "Hello Python Crash Course reader!"
print(mesage)

结果

Traceback (most recent call last):
  File "H:\Python_study_first\1.2-hello_worold_two.py", line 2, in <module>
    print(mesage)
NameError: name 'mesage' is not defined

动手一试

Python尝试代码

print("随便一条消息") #这是2-1
Strawberry = "一条消息" #这是2-2
print(Strawberry)
Strawberry = "另一条消息"
print(Strawberry)

结果运行

随便一条消息
一条消息
另一条消息

1.3字符串

1.字符串可以是双引号,也可以是单引号括起来的信息。

1.3.1使用方法修改字符串大小写

例1.

name = "ada lovelace"
print(name.title())

运行结果

Ada Lovelace

例2.

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

运行结果

ADA LOVELACE
ada lovelace

总结:
1.titile()的意义是以首字母大写的方式显示每个单词
2.upper()的意义是将每个单词都改成大写
3.lower()的意义是将每个单词都改成小写

1.3.2合并(拼接)字符串

例1.

first_name = "ada"
last_name = "lovelace"
full_name = first_name + "" + last_name
print(full_name)

结果

adalovelace

例2.

first_name = "ada"
last_name = "lovelace"
full_name = first_name + "" + last_name
print("hello,"+full_name.title()+""+"!")

结果

hello,Adalovelace!

总结:
1.Python使用+来合并字符串。

1.3.3使用制表符或换行符来添加空白

例1.

print("\tPython")

结果

	Python

例2.

print("Languages:\nPython\nC\nJavaScript")

结果

Languages:
Python
C
JavaScript

总结:
1.\t是制表符也就是键盘上的Tab键
2.\n是换行符也就是键盘上的回车键

1.3.4删除空白

例1.

favorite_language = "python "
print(favorite_language)

结果

python #注意这里有空格

例2.暂时消除末尾空白

favorite_language="python "
print(favorite_language.rstrip())

结果

python#这里空格消失,但是不是永久消失再次调用变量空格还是会出现。

例3.永久删除末尾空白

favorite_language="python "
favorite_language=favorite_language.rstrip()
print(favorite_language)

例4.

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

结果

python
python

总结:
1.rstrip(),lstrip(),strip()可以将变量删除多余的空白,但是这种是暂时的,接下来访问还是有空白的
2.如果永久删除,见例3
3.
删除末尾空白:rstrip()
删除开头空白:lstrip()
删除两端空白:strip()

例1.

message = 'One of Python's strengths is its diverse community'
print(message)

结果

  File "H:\Python_study_first\1.3.5-apostrophe.py", line 1
    message = 'One of Python's strengths is its diverse community'
                             ^
SyntaxError: invalid syntax

总结:双引号和单引号两个两个成对,不能单独出现。

1.3动手一试
在这里插入图片描述
在这里插入图片描述
结果:

1.4数字

介绍:在编程中,经常使用数字来记录游戏得分、表示可视化数据、存储Web应用信息。Python根据数字的用法以不同的方式处理它们。鉴于整数使用起来最简单,下面就先来看看Python是如何管理他们的

1.4.1整数

Python中可以
执行+ - * /运算
**幂运算

1.4.2浮点数

a=0.1+0.1
b=0.2+0.1
print(a)
print(b)

结果:

0.2
0.30000000000000004

注意:所有语言都存在这种问题,没有什么可担心的,Python会尽力找到一种方式,以尽可能准确地表示结果,但鉴于计算机内部表示数字的方式,这在有些情况下很难,就现在而言,可以暂时忽略小数位数即可;在第二部分的项目中,你将学习在需要时处理多余小数位的方式。

1.4.3使用函数str()避免类型错误

例1

age=23
message = "Happy" + age + "rd Birthday"
print(message)

结果:

Traceback (most recent call last):
  File "H:\Python_study_first\1.4.3-str().py", line 2, in <module>
    message = "Happy" + age + "rd Birthday"
TypeError: can only concatenate str (not "int") to str

例2

age=23
message="Happy" + str(age) + "rd Birthday!"
print(message)

结果:

Happy23rd Birthday!

总结:
1.注意基本数据类型,不能混用提供给一个变量。

1.4动手一试

1.5注释

1.5.1如何编写注释

利用#来编写注释

2.列表简介

2.1列表是什么

例1.

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)

结果

['trek', 'cannondale', 'redline', 'specialized']

2.1.1访问列表元素

例1

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0])

结果

trek

例2.

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0].title())

结果

Trek

2.1.2索引从0而不是1开始

例1

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[1])
print(bicycles[3])

结果

cannondale
specialized

例2

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[-1])

结果

specialized

总结:
1.列表中第一个元素是0开始并不是1
2.列表中最后一个元素可以用-1表示

2.1.3使用列表中的各个值

例1

bicycles = ['trek','cannondale','redline','specialized']
message = ("my first bicycle was a " + bicycles[0].title() + ".")
print(message)

结果

bicycles = ['trek','cannondale','redline','specialized']
message = ("my first bicycle was a " + bicycles[0].title() + ".")
print(message)

2.2修改、添加和删除元素

2.2.1修改列表元素

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

总结:
1.修改单个元素可以使用:列表[元素位置] = ‘修改的内容’

2.2.2在列表中添加元素

1.在列表末尾添加元素

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

2.在列表中插入元素

motorcycles = ['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)

结果

['ducati', 'honda', 'yamaha', 'suzuki']

总结:
1.append()能够在文章末尾添加一个元素
2.insert(位置,‘插入内容’)在特定位置插入内容

2.2.3从列表中删除元素

1.利用del删除列表中元素

motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)

结果

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

2.利用pop()删除列表元素

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

总结:
1.del 变量[位置]:删除变量中位置中的元素
2.pop()可以从原列表中弹出一个值(suzuki)然后赋值给popped_motorcycle然后原motorcycle少了一个元素(suzuki)

3.弹出任意位置处的元素

motorcycles = ['honda','yamaha','suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')

结果

The first motorcycle I owned was a Honda.

总结:del和pop的判断方法:如果你以后不再以任何方式使用他,就是用del语句,如果你要在删除元素后还能继续使用,那么就用pop()

4.根据值删除元素

motorcycles = ['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

结果

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

总结:
1.在不知道元素的位置的时候,可以使用remove(元素名称)移除元素
注意:
方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要用循环来判断是否删除了所有这样的值,你将在第六章中学习如何这样做。

2.3组织列表

2.3.1使用sort()对列表进行永久性排序

cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)

结果

['audi', 'bmw', 'subaru', 'toyota']

如果想要相反排序呢?

cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)

结果

['toyota', 'subaru', 'bmw', 'audi']

总结:
1.sort()是按照首字母排序
2.sort(reverse=True)是按照首字母倒序
3.对列表的修改是永久性的

2.3.2使用函数sorted()对列表进行临时排序

cars = ['bmw','audi','toyota','subaru']
print(cars)
print(sorted(cars))
print(cars)

结果

['bmw', 'audi', 'toyota', 'subaru']
['audi', 'bmw', 'subaru', 'toyota']
['bmw', 'audi', 'toyota', 'subaru']

总结:
1.sorted可以对列表进行暂时性排序并不是永久性的,原列表并不会改变。
2.sorted也可以进行倒序sort(reverse=True)

2.3.3 倒着打印列表

cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

总结:
1.reverse()是永久性的改变列表的排列顺序,如果想恢复原来的排列顺序,再次调用reverse()即可

2.3.4确认列表的长度

cars = ['bmw','audi','toyota','subaru']
a=len(cars)
print(a)
4

总结
1.利用len()可以获悉列表的长度

3.操作列表

3.1遍历整个列表

magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician)

结果

alice
david
carolina

解释:
让Python在magicians中取出一个名字存储到magician中然后print打印出来

3.1.1在for循环中执行更多的操作

magicians = ['alice','david','carolina']
for magican in magicians:
    print(magican.title()+", that was a great trick!

结果

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!

3.1.2在for循环结束后执行一些操作

magicians = ['alice','david','carolina']
for magican in magicians:
    print(magican.title()+", that was a great trick!")
    print("I cant wait to see your next trick, " + magican.title() + ".\n")
print("Thank you,everyone. That was a great show!")
Alice, that was a great trick!
I cant wait to see your next trick, Alice.

David, that was a great trick!
I cant wait to see your next trick, David.

Carolina, that was a great trick!
I cant wait to see your next trick, Carolina.

Thank you,everyone. That was a great show!

3.2避免缩进错误

1.忘记缩进
2.忘记缩进额外的代码行
3.不必要的缩进
4.缩进后不必要的缩进
5.遗漏了冒号

3.3创建数值列表

3.3.1使用函数range()

for value in range(1,5):
    print(value)

结果

1
2
3
4

1.range(n,m)是从n到m-1的范围

3.3.2使用range()创建数字列表

numbers = list(range(1,6))
print(numbers)

结果

[1, 2, 3, 4, 5]

even_numbers=list(range(2,11,2))
print(even_numbers)

结果

[2, 4, 6, 8, 10]

squares = []
for values in range(1,11):
    square=values**2
    squares.append(square)

print(squares)

结果

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

总结:
1.**是乘方运算
2.range(x,y,z)是从x到y-1每隔z个的数字

3.3.3对数字列表执行简单的统计运算

digits = [1,2,3,4,5,6,7,8,9,10]
a=min(digits)
b=max(digits)
c=sum(digits)
print(a,b,c)
1 10 55

总结
1.min()最小值
2.max()最大值
3.sum()求和

3.3.4列表解析

squares = [value**2 for value in range(1,11)]
print(squares)

结果

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

格式
变量名 = [公式 for循环]

3.4使用列表的一部分

3.4.1切片

player = ['charles','martina','michael','florence','eli']
print(player[0:3])

结果

['charles', 'martina', 'michael']

player = ['charles','martina','michael','florence','eli']
print(player[:4])

结果

['charles', 'martina', 'michael', 'florence']
player = ['charles','martina','michael','florence','eli']
print(player[0:3])
print(player[:4])
print(player[2:])

结果

['michael', 'florence', 'eli']

总结:
1.切片格式:变量名[n:m]
把原列表从n元素到m-1元素切出来
2.如果不加n则是从索引为0开始切片
3.如果不加m则是从n到末尾所有元素切片
4.n和m都可以为负数

3.4.2遍历切片

players = ['charles','martina','michael','florence','eli']
for player in players[:3]:
    print(player.title())

结果

Charles
Martina
Michael

3.4.3复制列表

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)

结果

['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake']

总结:
1.利用切片可以复制列表 :列表1 = 列表2[:]

3.5元组

3.5.1定义元组

介绍:不可以改变列表的列表称为元组

dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])

结果

200
50

总结:
1.元组用小括号包含
2.元组中的数值不能更改

3.5.2遍历元组中的所有值

dimensions = (200,50)
for dimension in dimensions:
    print(dimension)

结果

200
50

3.5.3修改元组的变量

dimensions = (200,50)
print(dimensions)
dimensions = (400,100)
print(dimensions)

结果

(200, 50)
(400, 100)

4.if语句

4.1一个简单实例

cars = ['bmw','audi','toyota','subaru']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

结果

BMW
Audi
Toyota
Subaru

4.2条件测试

1.检查是否相等
2.检查是否相等时考虑大小写
3.检查是否不相等
4.比较数字
5.检查多个条件
(1)利用and检查多个条件
and是两边都为True则为True
(2)利用or检查多个条件
or是两边为一个True则为True
6.检查特定值是否包含在列表中(利用in可以检查列表中是否含有这个特定值,包含为True不包含为False)
7.检查特定值是否不包含在列表中(利用not in可以检查列表中是否含有这个特定值,不包含为True包含为False)
8.布尔表达式True和False

4.3if语句

4.3.1 简单的if语句

1个测试和一个操作

4.3.2 if-else语句

age = 17
if age >=18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry,You are too young to vote.")
    print("Please register to vote as soon as you turn 18")

结果

Sorry,You are too young to vote.
Please register to vote as soon as you turn 18

总结:
1.如果if语句通过了则执行后续操作,如果判断不正确,则执行else操作

4.3.3if-elif-else结构

例子
1.4岁以下免费
2.4~18岁收费5美元
3.18岁收费10美元

age = 12
if age < 4:
    print("Your admission cost is $0")
elif age < 18:
    print("Your admission cost is $5")
else:
    print("Your admission cost is $10")

结果

Your admission cost is $5

4.3.4使用多个elif代码块

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5

print("Your admission cost is $" + str(price) + ".")

结果

Your admission cost is $5.

4.3.5省略else代码块

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
elif age <= 65:
    price = 5

print("Your admission cost is $" + str(price) + ".")

结果

Your admission cost is $5.

4.3.6测试多个条件

requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
print("\nFinished making your pizza!")

结果

Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

注意:
1.如果使用if-elif-else结构代码将不能正确运行,因为有一个测试通过了,就会跳过余下的测试。
总结
1.如果只想运行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句。

4.4使用if语句处理列表

4.4.1检查特殊元素

requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\nFinished making your pizza")

结果

Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza

4.4.2确定列表不是空的

requester_toppings = []
if requester_toppings:
    for requester_topping in requester_toppings:
        print("Adding "+ requester_topping)
    print("\nFinished making your pizza")
else:
    print("Are you sure you want a plain pizza")

结果

Are you sure you want a plain pizza

总结:
1.如果列表为空则返回False,如果列表不为空,就进行for循环。

4.4.3使用多个列表

available_toppings = ['mushrooms','olives','green peppers',
                     'pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fries','extra cheese']

for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + ".")
    else:
        print("Sorry we dont have " + requested_topping + ".")    

结果

Adding mushrooms.
Sorry we dont have french fries.
Adding extra cheese.

5.字典

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值