新建保存一个HelloWorld.py文件
print('Hello World !!!')
区别:和C比较 可以不用定义基本类型
message = "Hello Python world!"
print(message)
引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
C语言中方式其实就是函数
message = "hello Python world!"
print(message.title())
Python使用加号(+ )来合并字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
如空格、制表符和换行符。可使用字符组合\t
print("\tPython")
空白很重要,因为你经常需要比较两个字符串是否相同。例如,一个重要的示例是,在用户登录网站时检查其用户名。但在一些简单得多的情形下,额外的空格也可能令人迷 惑。
Python能够找出字符串开头和末尾多余的空白。
要确保字符串末尾没有空白,可使用方法rstrip() 。
注意!!!:这种删除只是暂时的,要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中
favorite_language = 'python '
favorite_language = favorite_language.rstrip()
print(favorite_language)
lstrip() 开头
strip()两端
favorite_language = ' python '
favorite_language = favorite_language.strip()
print(favorite_language)
在Python中,可对整数执行加(+ )减(- )乘(* )除(/ )运算、乘方** 运算 。
数字和字符串一起使用时 需要将数字用str 进行转换
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
# 向大家问好
print("Hello Python people!")
列表列 由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有 任何关系
在Python中,用方括号([] )来表示列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
需要指定新元素的索引和值
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
del motorcycles[1]
print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
有时候,你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
字母顺序排列,列表中的所有值都是小写
再也无法恢复到原来的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
按与字母顺序相反的顺序排列列表元素
只需向sort() 方法传递参数reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
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)
reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
这行代码让Python从列表magicians 中取出一个名字,并将其存储在变 量magician 中。最后,我们让Python打印前面存储到变量magician 中的名字
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
print(magician)
print('end')
每个缩进的代码行都是循环的一部分
建议:临时变量这样写和列表名称相似
for cat in cats:
for dog in dogs:
for item in list_of_items:
函数range() 让Python从你指定的第一个值开始数,并在到达你指定的第二个值 后停止,因此输出不包含第二个值(这里为5)。
for value in range(1,5):
print(value)
要创建数字列表,可使用函数list() 将range() 的结果直接转换为列表。如果将range() 作为list() 的参数,输出将为一个数字列表
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
min
max
sum
arange = list(range(1,10))
print(arange)
print(min(arange))
print(max(arange))
print(sum(arange))
列表解析 列 将for 循环和创建新元素的代码合并成一行,并自动 附加新元素
在这个示例中,for 循环为for value in range(1,11) ,它将值 1~10提供给表达式value2 。请注意,这里的for 语句末尾没有冒号。**
squares = [value**2 for value in range(1,11)]
print(squares)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
没有指定第一个索引,Python将自动从列表开头开始
让切片终止于列表末尾,也可使用类似的语法
print(players[:4])
print(players[2:])
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's 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's favorite foods are:")
print(friend_foods)
元组看起来犹如列表,但使用圆括号而不是方括号来标识
类似于const
dimensions = [200, 50]
dimensions[0] = 30
print(dimensions)
dimensions = (200, 50)
dimensions[0] = 30
print(dimensions)
# 向大家问好
print("Hello Python people!")
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
answer = 17
if answer < 42 and answer < 31:
print("run !!!")
if answer < 42 or answer < 15:
print("run !!!")
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings )
print('pepperoni' in requested_toppings )
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' not in requested_toppings )
print('pepperoni' not in requested_toppings )
在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式
# 向大家问好
print("Hello Python people!")
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!")
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.")
在Python中,字典字 是一系列键—值对值 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将 任何Python对象用作字典中的值。
类似于C语言中 一个标识符对应一个值
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐。另外一种不错的做法是在最后一个键—值对后面也加上逗号,为以 后在下一行添加键—值对做好准备。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +".")
for 语句的第二部分包含字典名和方法items() ,它返回一个键—值对列表。接下来,for 循环依次将每个键—值对存储到指定的两个变量中,下面是key、value。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key, value in favorite_languages.items():
print("key = "+key+"value = "+value)
在不需要使用字典中的值时,方法keys() 很有用,处的代码行让Python提取字典favorite_languages 中的所有键,并依次将它们存储到变量key 中
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key in favorite_languages.keys():
print("key = "+ key)
下面也可以省略
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for key in favorite_languages:
print("key = "+ key)
,但对方法dictionary.keys() 的结果调用了函数sorted() 。这让Python列出字典中的所有键,并在遍历前对这个列表进行排序。输出 表明,按顺序显示了所有被调查者的名字:
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in sorted(favorite_languages.values()):
print(name.title() + ", thank you for taking the poll.")
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
for name in set(favorite_languages.values()):
print(name.title() + ", thank you for taking the poll.")
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
pizza = { 'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用
函数input() 接受一个参数:即要向用户显示的提示提 或说明,让用户知道该如何做
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
message = input("Tell me something, and I will repeat it back to you: ")
message = int(message)
print(message)
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止 # 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
❶处的代码行使用关键字def 来告诉Python你要定义一个函数。这是函数定义
函数调用 函 让Python执行函数的代码。要调用调 函数,可依次指定函数名以及用括号括起的必要信息
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user()
def greet_user(username):
"""显示简单的问候语"""
print("Hello!"+ username.title() + "!")
greet_user('dada')
其实就是传入参数赋值
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
Python将非空字符串解读为True
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: " + current_design)
completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
相当于可变数组 都集中在一个数组当中
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')