python学习记录

变量和简单数据类型

message="Hello Python world!"
print(message)

message就是一个变量,绿色部分用双引号括起来的(也可以用单引号)就是一个字符串。
在这里插入图片描述

变量的命名和使用:

1.变量名只能包含字母、数字和下划线。字母下划线可以打头数字不可以。
2.变量名不能包含空格,但可以使用下划线来分割其中单词
3.不要将Python关键字和函数名用作变量名。
修改字符串大小写:
*title():*以首字母大写的方式显示单词。
*upper():*大写整个字符串。
*lower():*小写整个字符串。
在这里插入图片描述
合并字符串:

first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name

print(full_name)

在这里插入图片描述

first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name

print("hello,"+full_name.title()+"!")

也可以

first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name

message="hello,"+full_name.title()+"!"
print(message)

在这里插入图片描述
使用制表符或换行符来添加空白:
制表符:\t

print("\tPython")
print("Python")

在这里插入图片描述
使用制表符前面有空格,不使用制表符没有空格。

空格符:\n

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

在这里插入图片描述
可以发现python、C、JavaScript都换行了。

在一个字符串中同时包含\t,\n:

print("Language:\n\tPython\n\tC\n\tJavaScript")

在这里插入图片描述
可以发现python、C、JavaScript都换行了并且前面有空格。

删除空白:

favorite_language='python '
favorite_language.rstrip()

在这里插入图片描述
rstrip:删除右边的空格

favorite_language=' python'
favorite_language.lstrip()

在这里插入图片描述
lstrip:删除左边的空格

整数:
在这里插入图片描述
最后一个是乘方运算。

浮点数:
python中将带小数点的数字都称为浮点数
在这里插入图片描述
使用函数str()避免类型错误:
下面是错误的例子:因为都是字符串,但是age不是字符串。
在这里插入图片描述
改正:将age变成str(age),就变成字符串了

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

列表

列表是什么
列表由一系列按特定顺序排列的元素组成

bicyles=['trek','cannondale','redline','specialize']
print(bicyles)

在这里插入图片描述
这个列表包含了四种自行车,打印出来的结果也包含了双括号。

访问列表元素
要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。

bicyles=['trek','cannondale','redline','specialize']
print(bicyles[0])

在这里插入图片描述
大写首字母
在这里插入图片描述
注:索引是从0开始不是从1开始,就像数组一样。
使用索引-1可以得到最后一个元素。
在这里插入图片描述

使用列表中的各个值

bicyles=['trek','cannondale','redline','specialize']
message="My first bicyles was a "+bicyles[0].title()+"."
print(message)

在这里插入图片描述
修改列表元素

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

在这里插入图片描述
在列表末尾添加元素
使用append()将元素添加到列表末尾

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

在这里插入图片描述
亦可以建立一个空列表不断地在后面添加元素

motorcycles=[]
motorcycles.append('honda')
motorcycles.append('hyamaha')
motorcycles.append('suzuki')
print(motorcycles)

在这里插入图片描述
在列表中插入元素
使用insert()可在列表的任何位置添加新元素

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

在这里插入图片描述

从列表中删除元素.使用del语句删除元素

删除第一个元素

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

在这里插入图片描述
删除第二个元素

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

在这里插入图片描述
从列表中删除元素.使用方法pop删除元素

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

在这里插入图片描述
方法pop()可删除列表末尾的元素,并能够接着使用它,列表就像一个栈,而删除列表中的元素相当于弹出一个栈顶元素。
从列表中删除元素.弹出列表中任何位置处的元素

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

在这里插入图片描述

从列表中删除元素.根据值删除元素
如果不知道要从列表中删除的值所处位置,只知道要删除的元素的值,使用remove()。

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

在这里插入图片描述
组织列表
1.方法sort()对列表进行永久性排序
按字母排序,并且没有办法恢复。

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

在这里插入图片描述
按字母倒序,并且没有办法恢复。

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

在这里插入图片描述

2.函数sorted()对列表进行临时排序
调用函数sorted()后,列表元素的排列顺序没有变。如果要按与字母顺序相反的顺序显示列表,也可以向sorted()传递参数reverse=True

cars=['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

在这里插入图片描述
3.方法reverse()倒着打印列表

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

这是永久性的修改,多使用一次reverse()又反转过来了
在这里插入图片描述
4.函数len()确定列表长度

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

在这里插入图片描述

操作列表

遍历整个列表
定义一个for循环这行代码让python从列表magicians中取出一个名字并将其存放在magician中。记住这个print是在for循环中缩进的。

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

在这里插入图片描述
在for循环中执行更多的操作

magicians=['alice','david','carolina']
for magician in magicians:
    print(magician.title()+',that was a great trick')
    print("I can't wait to see your next trick,"+magician.title()+".\n")

在这里插入图片描述
在for循环结束后执行一些操作
不缩进print就只执行了一次也就是说结束了for循环以后的操作

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

在这里插入图片描述
创建数值列表
使用函数range()
range()能够轻松地生成一系列数字
range()只是打印1-4,这是编程语言中经常看到的差一行为。如果要打印1-5,那么就需要输入range(1,6)

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

在这里插入图片描述
使用range()创建数字列表
使用list(range())

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

在这里插入图片描述

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

在这里插入图片描述
从2-10,不断的增加2

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

在这里插入图片描述
或者

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

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

digits=[1,2,3,4,5,6,7,8,9,0]
print(sum(digits))
print(max(digits))
print(min(digits))

在这里插入图片描述

列表解析

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

在这里插入图片描述
这里的for循环语句没有冒号。

切片
其中索引就是开始的位置这里就是0

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

在这里插入图片描述

得到第二个到第四个,索引变成了1就是从1开始

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

在这里插入图片描述
没有索引,只有结尾

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

在这里插入图片描述
有索引,没有结尾

players=['charles','martina','michael','florence','eli']
print(players[2:])

在这里插入图片描述
使用-3输出最后三名成员

players=['charles','martina','michael','florence','eli']
print(players[-3:])

在这里插入图片描述
遍历切片

players=['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

在这里插入图片描述
复制列表
同时省略起始索引和终止索引

my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend favorite foods are:")
print(friend_foods)

在这里插入图片描述
更直观

my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend favorite foods are:")
print(friend_foods)

在这里插入图片描述
如果使用friend_foods=my_foods两个列表将会变得一模一样
不管修改了谁都会跟着改变
在这里插入图片描述
定义元组
不可变的列表叫做元组,使用圆括号而不是方括号来标识

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

在这里插入图片描述
如果dimensions[0]=255,不能被修改会出错

遍历元组中的所有值

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

在这里插入图片描述

修改元组变量

dimensions=(200,50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)
dimensions=(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)

在这里插入图片描述

if语句

条件测试

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

在这里插入图片描述
检查是否相等
car=‘bmw’
car==‘bmw’
返回true
检查是否相等不考虑大小写
car=‘Audi’
car=‘audi’
False
#两个大小写不同的值会被视为不相等
car=‘Audi’
car.lower=‘audi’
True
这里car的值没有改变

检查是否不相等

requested_topping='mushrooms'
if requested_topping!='anchovies':
    print("hold the anchovies")

在这里插入图片描述
注意:一定要记住if语句后面的冒号,还有print缩进

比较数字
在这里插入图片描述

answer=18
if answer!=42:
    print('That is not correct answer.Please try again!')

在这里插入图片描述
使用and检查多个条件
要检查是否两个条件是否同时为true
在这里插入图片描述
在这里插入图片描述
使用or检查多个条件
在这里插入图片描述检查特定值是否包含在列表中
在这里插入图片描述
在这里插入图片描述
检查特定值是否不包含在列表中

banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users:
    print(user.title()+",you can post a response if you wish")
    

在这里插入图片描述
布尔表达式
布尔表达式的结果要么为True,要么为False

简单的if语句

age=19
if age>=18:
    print("You are old enough to vote!")

在这里插入图片描述if_else语句

age=19
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 soons as you turn 18!')

if_else_else结构

#根据年龄段收费的游乐场
#4岁以下免费
#4-18岁收费5
#18岁(含)以上收费10
age=12
if age<4:
    print("You admission cost is 0.")
elif age<18:
    print('You admission cost is 5.')
else:
    print('You admission cost is 10.')

在这里插入图片描述
使用多个elif代码块

age=12
if age<4:
    price=0
elif age<18:
    price=5
elif age<65:
     price=10
else:
    price=5
print("You admission cost is "+str(price)+'.')

在这里插入图片描述
省略else代码块

age=12
if age<4:
    price=0
elif age<18:
    price=5
elif age<65:
     price=10
elif age>=65:
    price=5
print("You admission cost is "+str(price)+'.')
 

在这里插入图片描述测试多个条件

#如果顾客点了2种配料,就需要确保在其比萨中包含这些配料
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'peperoni' in requested_toppings:
    print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese")
print("\nFinished making your pizza")

在这里插入图片描述
检查特殊元素

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

在这里插入图片描述

requested_toppings=['mushrooms','green peppers','extra cheese']
#假设青椒用完了
for requested_topping in requested_toppings:
    if requested_topping=='green peppers':
        print('Sorry,we are out of green peppers right now.')
    else:
         print("Adding "+requested_topping+'.')
print("\nFinished making your pizza!")

在这里插入图片描述
确定列表不是空的

requested_toppings=[]
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding"+requested_topping+'.')
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

在这里插入图片描述
使用多个列表

available_toppings=['mushrooms','olives','green peppers','pineapple','extra cheese']
requested_toppings=['mushroom','french fries','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding"+requested_topping+'.')
    else:
        print("Sorry,we don't have "+requested_topping+'.')
print("\nFinished making your pizza!")

在这里插入图片描述
字典
列表car=[‘bmw’,‘suzuki’]
元组car=(200,250)
字典alien_0={‘color’:‘green’,‘points’:5}

alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])

在这里插入图片描述
键—值对是两个相关联的值。指定键时,python将会返回与其相关联的值。
键和值之间用冒号分隔,而键—值对之间用逗号分隔。

使用字典
访问字典中的值

alien_0={'color':'green','points':5}
new_points=alien_0['points']
print("You just earnned"+str(new_points)+"points!")

在这里插入图片描述
添加键—值对

alien_0={'color':'green','points':5}
print(alien_0)
#外星人的x坐标和y坐标
alien_0['x_postion']=0
alien_0['y_postion']=25
print(alien_0)

在这里插入图片描述
先创建一个空字典

alien_0={}
#分行添加各个键队的值
alien_0['color']='green'
alien_0['point']=5
print(alien_0)

在这里插入图片描述
修改字典中的值

alien_0={'color':'green'}
#现在外星人的颜色是
print("The alien is now "+alien_0['color']+".")
alien_0['color']='yellow'
#修改外星人的颜色为黄色
print("The alien is now"+alien_0['color']+".")

在这里插入图片描述

#对一个能以不同速度移动的外星人的位置进行跟踪
#存储外星人当前的速度,并确定外星人将向右移动多远
alien_0={'x_position':0,'y_position':25,'speed':'medium'}
print("original x_position:"+str(alien_0'[x_position']))
#向右移动机器人
#据外星人当前速度决定将其移动多远
if alien_0['speed']=='slow':
    x_increment=1
elif alien_0['speed']=='medium':
    x_increment=2
else:
    #这个外星人的速度一定很快
    x_increment=3
#新位置等于 老位置加上增量
alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position: "+str(alien_0['x_position']))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值