提交 8f9acbd6 编写于 作者: 逆流者blog's avatar 逆流者blog 🇨🇳

Python3 基础用法

上级 2d0674a5
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
print(alien_0['color'])
print(alien_0['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 = {}
alien_0['color'] = 'grenn'
alien_0['points'] = 5
print(alien_0)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['color'] = 'yellow'
print(alien_0)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['color']
print(alien_0)
\ No newline at end of file
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'red', 'points': 10}
alien_2 = {'color': 'yellow', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
message = "Python's"
print(message)
message = 'Python's'
\ No newline at end of file
message = 'Python'
\ No newline at end of file
......@@ -7,54 +7,84 @@ print(bicycles[0].title())
print(bicycles[-1])
# 修改列表中的元素
print("修改之前:")
print(bicycles)
bicycles[1] = 'jerry2'
print("修改之后:")
print(bicycles)
# 添加元素
# 末尾添加
bicycles = ['tom', 'jerry', 'jerry5', 'xiaohong', 'jerry5', 'xiaoming']
print("末尾添加之前:")
print(bicycles)
bicycles.append('xiaoqiang')
print("末尾添加之后:")
print(bicycles)
# 插入元素
bicycles.insert(0, 'tiger')
print("插入添加之后:")
print(bicycles)
# 删除元素
# del 语句
bicycles = ['tom', 'jerry', 'jerry5', 'xiaohong', 'jerry5', 'xiaoming']
print("末尾添加之前:")
print(bicycles)
del bicycles[0]
print("删除元素之后:")
print(bicycles)
# pop() 弹出列表最后的元素
pop_val = bicycles.pop()
print("弹出元素之后:")
print(bicycles)
print(pop_val)
print("pop的元素:" + pop_val)
# pop(0) 弹出指导位置元素
pop_val2 = bicycles.pop(0)
print("弹出指定位置元素之后:")
print(bicycles)
print(pop_val2)
print("pop的指位置的元素:" + pop_val2)
# remove() 根据元素的值删除元素, 只会删除列表中的第一个
bicycles.remove('jerry5')
print(bicycles)
print("-----------------")
# 组织列表
# 按照字典顺序
# sort() 永久排序, 默认正序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print('原始列表:')
print(cars)
cars.sort()
print('顺序:')
print(cars)
# 逆序
cars.sort(reverse=True)
print('逆序:')
print(cars)
print('---------')
# sorted() 临时排序, 也可以使用reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
print('原始列表:')
print(cars)
print('临时排序后列表: ')
print(sorted(cars))
print("再次查看列表: ")
print(cars)
print('---------')
# 倒着打印
cars = ['bmw', 'audi', 'toyota', 'subaru']
print('原始列表:')
print(cars)
cars.reverse()
print('倒着打印列表:')
print(cars)
# len() 长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
print('原始列表:')
print(cars)
print(len(cars))
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars[4])
# continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
\ No newline at end of file
print(current_number)
even_numbers = list(range(2, 11, 2))
print(even_numbers)
......@@ -8,4 +8,5 @@ favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, languages in favorite_languages.items():
print(name.title() + "'s favorite languages is " + languages.title() + '.')
\ No newline at end of file
print(name.title() + "'s favorite languages is " + languages.title() + '.')
favorite_languages = {'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
for name, languages in favorite_languages.items():
print(name.title() + "'s favorite languages is " + languages.title() + '.')
favorite_languages = {'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
for name in favorite_languages.keys():
print(name.title())
print('------')
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 languages in favorite_languages.values():
print(languages.title())
favorite_languages = {'jen': ['python', 'java'],
'sarah': 'c',
'edward': ['ruby', 'go'],
'phil': ['python', 'c++']
}
for name, languages in favorite_languages.items():
print('\n' + name.title() + "'s favorite languages are: ")
for language in languages:
print('\t' + language.title())
......@@ -3,43 +3,41 @@ names = ['name1', 'name3', 'name2']
for name in names:
print(name)
# 数值列表
# 函数 range() 范围左闭右开
for value in range(1,10):
for value in range(1, 10):
print(value)
# 使用range() 创建数字列表
numbers = list(range(1,6))
numbers = list(range(1, 6))
print(numbers)
# 创建一个数值列表, 包含1-10 的平方
squares = []
for value in range(1,11):
square = value**2
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
# 统计计算
digits = [1,2,3,4,5,6,7,8,9,0]
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
# 列表解析
# 前面 生成列表squares需要好几行代码, 这里用下列表解析
squares = [value**2 for value in range(1,11)]
squares = [value ** 2 for value in range(1, 11)]
print(squares)
# 使用列表的一部分- 切片
players = ['a','b','c','d','e','f','g']
players = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(players[0:3])
print(players[1:4])
print(players[:4]) # 不指定, 从列头开始
print(players[2:]) # 不指定, 到列尾
print(players[-3:]) # 返回最后3个
print(players[:4]) # 不指定, 从列头开始
print(players[2:]) # 不指定, 到列尾
print(players[-3:]) # 返回最后3个
# 遍历切片
for player in players[:3]:
......@@ -61,7 +59,7 @@ dimensions = (200, 500)
print(dimensions)
print(dimensions[0])
print(dimensions[1])
# dimensions[0] = 300 不能修改, 会报错
# dimensions[0] = 300 # 不能修改, 会报错
# 遍历元祖
for dimension in dimensions:
print(dimension)
......@@ -74,4 +72,4 @@ for dimension in dimensions:
print('modified: ')
dimensions = (100, 200)
for dimension in dimensions:
print(dimension)
\ No newline at end of file
print(dimension)
print('hello world')
......@@ -2,4 +2,4 @@ message = "hello python world!"
print(message)
message = "python 改变世界"
print(message)
\ No newline at end of file
print(message)
cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
if car == 'bmw':
print(car.upper())
else:
print(car.title())
print('--------------')
# 检查是否相等 (区分大小写)
......@@ -27,7 +27,7 @@ print('--------------')
# and 同时成立; or 至少一个满足
print(age > 10 and age < 19)
print(age > 10 or age < 19)
print('--------------')
print('--------------达到')
# 是否包含
# in 包含; not in 不包含
......@@ -42,7 +42,7 @@ status2 = False
# 确定列表不是空的
cars = []
if cars:
print("cars is not null")
print("cars is not null")
else:
print("cars is null")
print("cars is null")
# del 语句
names = ['tom', 'jerry', 'tiger', 'Davis']
print("删除元素之前:")
print(names)
del names[0]
print("删除元素之后:")
print(names)
# pop() 弹出列表最后的元素
names = ['tom', 'jerry', 'tiger', 'Davis']
print("弹出元素之前:")
print(names)
name1 = names.pop()
print("弹出元素之后:")
print(names)
print("pop的元素:" + name1)
# pop(0) 弹出指定位置元素
names = ['tom', 'jerry', 'tiger', 'Davis']
print("弹出指定位置元素之前:")
print(names)
name2 = names.pop(0)
print("弹出指定位置元素之后:")
print(names)
print("pop的指位置的元素:" + name2)
# remove(指定的元素) 根据元素的值删除元素, 只会删除列表中的第一个
names = ['tom', 'jerry', 'tiger', 'Davis']
print("删除指定元素之前:")
print(names)
names.remove('tiger')
print("删除指定元素之后:")
print(names)
\ No newline at end of file
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
users = {
'user1': {
'first': 'xiao',
'last': 'ming',
'location': 'shanghai'
},
'user2': {
'first': 'hong',
'last': 'hong',
'location': 'beijing'
},
}
for username, user_info in users.items():
print('\nUsername: ' + username)
full_name = user_info['first'] + ' ' + user_info['last']
location = user_info['location']
print('\t Full name: ' + full_name.title())
print('\tLocation: ' + location.title())
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
favorite_language = ' python java '
print(favorite_language.rstrip())
age = 27
print("年龄:" + str(age))
\ No newline at end of file
for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
squares = [value**2 for value in range(1, 11)]
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
user_0 = {
'username': 'wsh',
'first': 'wh',
'last': 'shanghui'
}
for key, value in user_0.items():
print('\nkey: ' + key)
print('value: ' + value)
current_number = 1
while current_number <=5:
print(current_number)
current_number += 1
# current_number = 1
# while current_number <= 5:
# print(current_number)
# current_number += 1
# break
prompt = '\n请输入你喜欢的城市名称:'
prompt += '\n输入 "quit" 退出 '
while True:
city = input(prompt)
if city == 'quit':
break
else:
print('我喜欢去 ' + city + '!')
prompt = '\n请输入你喜欢的城市名称(输入 "quit" 退出): '
active = True
while active:
city = input(prompt)
if city == 'quit':
active = False
else:
print('我喜欢去 ' + city + '!')
......@@ -3,4 +3,4 @@ message = input("请输入你的名称: ")
print('hello ' + message)
age = input("请输入你的年龄: ")
age = int(age)
print(age)
\ No newline at end of file
print(age)
# 定义函数
def greet_user():
"""文档注释, 描述此函数的功能"""
print("hello")
"""文档注释, 描述此函数的功能"""
print("hello")
greet_user()
# 向函数传递信息
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('tom')
# 位置实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("我的 " + animal_type + ' 的名字是 ' + pet_name)
"""显示宠物的信息"""
print("我的 " + animal_type + ' 的名字是 ' + pet_name)
describe_pet('狗', '小黄')
describe_pet('猫', '小黑')
......@@ -26,8 +26,8 @@ describe_pet(pet_name='小红', animal_type='鸡')
# 默认值 默认值放在后面
def describe_pet2(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("我的 " + animal_type + ' 的名字是 ' + pet_name)
"""显示宠物的信息"""
print("我的 " + animal_type + ' 的名字是 ' + pet_name)
describe_pet2(pet_name='小黄')
describe_pet2('大黄')
......@@ -35,14 +35,14 @@ describe_pet2('大黄2', '狗')
# 默认值 默认值放在前面 SyntaxError: non-default argument follows default argument 会报错
# def describe_pet3(animal_type='dog', pet_name):
# """显示宠物的信息"""
# print("我的 " + animal_type + ' 的名字是 ' + pet_name)
# """显示宠物的信息"""
# print("我的 " + animal_type + ' 的名字是 ' + pet_name)
# 返回值
def get_formatted_name(frist_name, last_name):
"""返回整洁的姓名"""
full_name = frist_name + ' ' + last_name
return full_name.title()
"""返回整洁的姓名"""
full_name = frist_name + ' ' + last_name
return full_name.title()
# 函数调用
musician = get_formatted_name('jimi', 'hendrix')
......@@ -50,32 +50,32 @@ print(musician)
# 返回字典
def build_person(frist_name, last_name):
"""返回一个字典, 其中包含一个人的信息"""
person = {'first': frist_name, 'last': last_name}
return person
"""返回一个字典, 其中包含一个人的信息"""
person = {'first': frist_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
# 在函数中修改列表
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计, 直到没有末打印的设计为止
打印每个设计后, 都将其移到列表completed_models中
"""
"""
模拟打印每个设计, 直到没有末打印的设计为止
打印每个设计后, 都将其移到列表completed_models中
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
print('打印 模型: ' + current_design)
completed_models.append(current_design)
# 模拟根据设计制作3D打印模型的过程
print('打印 模型: ' + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print('\n')
for completed_model in completed_models:
print(completed_model)
"""显示打印好的所有模型"""
print('\n')
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
......@@ -91,7 +91,7 @@ print(unprinted_designs)
# 传递任意参数的实参 *toppings
def make_pizza(*toppings):
print(toppings)
print(toppings)
# 看到打印结果 看打印的结果实际上是 使用元祖来存储 任意数量的实参的
make_pizza('peperoni')
......@@ -99,21 +99,21 @@ make_pizza('mushrooms', 'green peppers', 5)
# 使用位置实参和任意数量实参
def make_pizza(size, *toppings):
print(size)
print(toppings)
print(size)
print(toppings)
make_pizza(16, 'green peppers', 'mushrooms')
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典,包含我们知道的有关用户的一切"""
profile = {}
profile['frist_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
"""创建一个字典,包含我们知道的有关用户的一切"""
profile = {}
profile['frist_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
\ No newline at end of file
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册