Python编程:从入门到实践(1-4)

1. 起步
print("Hello Python interpreter")
2. 变量和简单数据类型
添加一个名为message的变量,每个变量都存储了一个值--与变量相关联的信息。
message = "Hello Python world"
print(message)

message = "Hello Python Crash Course world"
print(message)
字符串就是一系列字符。在Python中,用引号括起来的都是字符串,其中引号可以是双引号,也可以是单引号。
"This is a string"
'This is also a string'
使用方法修改字符串的大小写
name = "ada lovelace"
print(name.title())

#输出
Ada Lovelace
name = "ada lovelace"
print(name.upper())
print(name.lower())

#输出
ADA LOVELACE
ada lovelace
合并字符串
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() + "!")

#输出
Hello, Ada Lovelace!
first_name = "ada"
last_name = "lovelace"
full_name = first_name + last_name
message = "Hello " + full_name.title() + "!"
print(message)
使用制表符或换行符来添加空白
print("\tPython")
输出
    Python
print("Languages: \n\tPython\n\tC\n\tJavaScript")
输出
Languages:
    Python
    C
    JavaScript
删除空白
>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '
>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python'
>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'
使用函数str(), 避免类型错误
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
python之禅

 Beautiful is better than ugly.
 Simple is better than complex.
 Complex is better than complicated.
 Readability counts.
 There should be one-- and preferably only one --obvious way to do it.
  Now is better than never.

3. 列表简介
列表 由一系列按特定顺序排列的元素组成。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
索引从0而不是1开始
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])
print(bicycles[3])

输出:
cannondale
specialized
通过将索引指定为-1 ,可让Python返回最后一个列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])

输出:
specialized
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)

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

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

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

输出:
['ducati', 'honda', 'yamaha', 'suzuki']
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)

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

输出:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
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.
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

输出:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
使用方法sort()对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

输出:
['audi', 'bmw', 'subaru', 'toyota']
使用方法sorted()对列表进行临时排序
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)

输出:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)

输出:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
确定列表的长度
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4
4. 操作列表
遍历整个列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)

输出:
alice
david
carolina
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")

输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
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!")

输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!
忘记缩进
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

输出:
File "magicians.py", line 3
print(magician)
^
IndentationError: expected an indented block
创建数值列表
for value in range(1,5):
    print(value)

输出:
1
2
3
4
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 value in range(1,11):
    square = value**2
    squares.append(square)
print(squares)

输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares = []
for value in range(1,11):
    squares.append(value**2)
print(squares)
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits) 
0 
>>> max(digits)
9 
>>> sum(digits)
45
列表解析 将for 循环和创建新元素的代码合并成一行,并自动附加新元素。
squares = [value**2 for value in range(1,11)]
print(squares)
你还可以处理列表的部分元素——Python称之为切片 。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
输出:
['charles', 'martina', 'michael']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
输出:
['martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
输出:
['charles', 'martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
输出:
['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
输出:
Here are the first three players on my team:
Charles
Martina
Michael
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
输出:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
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's favorite foods are:")
print(friend_foods)
输出:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
倘若我们只是简单地将my_foods 赋给friend_foods ,就不能得到两个列表。这里将my_foods 赋给friend_foods ,而不是将my_foods 的副本存储到friend_foods 。这种语法实际上是让Python将新变量friend_foods 关联到包含在my_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's favorite foods are:")
print(friend_foods)
输出:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站的用户列表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组 。元组看起来犹如列表,但使用圆括号而不是方括号来标识。
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
输出:
200
50
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
输出:
200
50
虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定义整个元组:
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
输出:
Original dimensions:
200
50
Modified dimensions:
400
100
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值