Python编程:从入门到实战

变量和简单数据类型

name = "ada lovelace" 
print(name.title())  # title()以首字母大写的方式显示每个单词
print(name.upper()) 
print(name.lower())

# 剔除字符串开头的空白
favorite_language.rstrip()
favorite_language.lstrip() 
favorite_language.strip()

"""在Python 2代码中,有些print语句包含括号,有些不包含"""

#在Python中,可对整数执行加(+)减(-)乘(*)除(/)(**)乘方运算


列表简介

# 在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles) 
print(bicycles[0]) 
"""Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,可让Python返 回最后一个列表元素"""
print(bicycles[-1]) 
# 在列表末尾添加元素 
motorcycles.append('ducati') 
# 在列表中插入元素 
motorcycles.insert(0, 'ducati')
# 使用del语句删除元素 
del motorcycles[0]
# 使用方法pop()删除元素 
"""方法pop()可删除列表末尾的元素,并让你能够接着使用它。术语弹出(pop)源自这样的类 比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。 """
# 弹出列表中任何位置处的元素 
first_owned = motorcycles.pop(0)
# 根据值删除元素 
motorcycles.remove('ducati')
"""方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要 使用循环来判断是否删除了所有这样的值"""  

# 使用方法 sort()对列表进行永久性排序
# 相反的顺序排列列表元素,为此,只需向sort()方法传递参数 reverse=True
"""临时排序:
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数sorted()。函数 sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。 """
# 要反转列表元素的排列顺序,可使用方法reverse()。
cars.reverse()
# 使用函数len()可快速获悉列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru'] 
len(cars)   

操作列表

# 遍历列表
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
	print(magician) 
# Python函数range()让你能够轻松地生成一系列的数字。
for value in range(1,5):
    print(value)
# 使用range()创建数字列表 
numbers=list(range(1,6))
print(numbers)
# 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3])
print(players[:4]) 
print(players[2:]) 
print(players[-3:])  #输出名单上的最后三名队员
# 遍历切片 
 for player in players[:3]:
     print(player.title())
# 复制列表 
friend_foods = my_foods[:] 
# 元组
"""列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网 站的用户列表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修改的元素, 元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组。 """
# 元组看起来犹如列表,但使用圆括号而不是方括号来标识。
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# 遍历
dimensions = (200, 50)  
for dimension in dimensions:
    print(dimension)

if语句

for car in cars: 
    if car == 'bmw':          
        print(car.upper())     
     else:         
        print(car.title()) 
# 要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一; 使用or检查多个条件 

 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.")
# 有时候必须检查你关心的所有条件,连续使用多个if

字典

# 在Python中,字典是一系列键—值对。
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color']) 
# 添加键—值对 
alien_0 = {'color': 'green', 'points': 5}
alien_0['x_position'] = 0 
# 先使用一对 空的花括号定义一个字典,再分行添加各个键—值对。
alien_0 = {} 
alien_0['color'] = 'green' 
alien_0['points'] = 5
# 修改字典中的值
alien_0['color'] = 'yellow' 
# 删除键—值对 
del alien_0['points'] 
# 遍历字典
user_0 = {     
    'username': 'efermi',
    'first': 'enrico', 
    'last': 'fermi',     
} 
for key, value in user_0.items(): 
    print("\nKey: " + key) 
    print("Value: " + value) 
# 遍历字典中的所有键,方法keys()很有用。
for name in favorite_languages.keys():
    print(name.title()) 
# 遍历字典中的所有值,可使用方法values().
for language in favorite_languages.values():     				
    print(language.title())
"""为剔除重复项,可使用集合(set)。 集合类似于列表,但每个元素都必须是独一无二的: """
for language in set(favorite_languages.values()):     			
    print(language.title()) 
# 字典列表
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) 
# 在字典中存储列表 
 pizza = {     
     'crust': 'thick',     
     'toppings': ['mushrooms', 'extra cheese'],     
 }
 # 在字典中存储字典 
users = {     
    'aeinstein': {         
        'first': 'albert',        
        'last': 'einstein',       
        'location': 'princeton',      
    }, 
 
    'mcurie': {       
        'first': 'marie',  
        'last': 'curie',    
        'location': 'paris',    
    },  
}

用户输入和while循环

message = input("Tell me something, and I will repeat it back to you: ") 
# 类型转换:
int()    str()   float()
# 如果你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。
# 使用while 循环 
while message != 'quit':  
    message = input(prompt)  
    print(message) 
# 使用break 退出循环 ,在循环中使用 continue 
# 删除包含特定值的所有列表元素 
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 
print(pets)  
while 'cat' in pets:  
    pets.remove('cat') 

函 数

# 向函数传递信息 
def greet_user(username): 
    """显示简单的问候语"""   
    print("Hello, " + username.title() + "!") 
# 关键字实参 
"""关键字实参让你无需考虑函 数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。 """
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 greet_users(names): 
    """向列表中的每位用户都发出简单的问候"""  
    for name in names:       
        msg = "Hello, " + name.title() + "!"         			    
        print(msg)
"""将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永 久性的,这让你能够高效地处理大量的数据"""
 def print_models(unprinted_designs, completed_models):  
        """     模拟打印每个设计,直到没有未打印的设计为止   
 		打印每个设计后,都将其移到列表completed_models中     """   
        while unprinted_designs:     
            current_design = unprinted_designs.pop()      
            # 模拟根据设计制作3D打印模型的过程      
            print("Printing model: " + current_design)
            completed_models.append(current_design)
# 传递任意数量的实参 
# 函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们 统统收入囊中
def make_pizza(*toppings):   
    """打印顾客点的所有配料"""     
    print(toppings) 
# 使用任意数量的关键字实参 
"""有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种 情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。
形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所 有名称—值对都封装到这个字典中"""
def build_profile(first, last, **user_info): 
    """创建一个字典,其中包含我们知道的有关用户的一切"""    
    profile = {}  
    profile['first_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'
) 
# 使用as 给函数指定别名 
from pizza import make_pizza as mp
# 导入模块中的所有函数 
# 使用星号(*)运算符可让Python导入模块中的所有函数
from pizza import * 

# 根据约定,在Python中,首字母大写的名称指的是类
class Dog(): 
    """一次模拟小狗的简单尝试"""      
    def __init__(self, name, age):  """self必不可少,还必须位于其他形参的前面。"""
        """初始化属性name和age""" 
        self.name = name        
        self.age = age          
    def sit(self):        
        """模拟小狗被命令时蹲下"""     
        print(self.name.title() + " is now sitting.") 
    def roll_over(self):       
        """模拟小狗被命令时打滚"""  
        print(self.name.title() + " rolled over!") 
# 在Python 2.7中创建类时,需要做细微的修改——在括号内包含单词object:  
class ClassName (object):
# 调用方法 
my_dog = Dog('willie', 6) # 实例化 
my_dog.sit() # 调用sit()方法
#-------------继承----------------------
# 子类的方法__init__() 
class ElectricCar(Car):   
    """电动汽车的独特之处"""      
    def __init__(self, make, model, year):    
        """初始化父类的属性""" 
        super().__init__(make, model, year) 
"""的super()是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让Python调用 ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。父类也称为超 类(superclass),名称super因此而得名"""
# 在Python 2.7中,继承语法稍有不同,ElectricCar类的定义类似于下面这样: 
class Car(object):     
    def __init__(self, make, model, year):      
        -snip -- 
 
class ElectricCar(Car):     
    def __init__(self, make, model, year):   
        super(ElectricCar, self).__init__(make, model, year)
# Python标准库 
# OrderedDict实例的行为 几乎与字典相同,区别只在于记录了键—值对的添加顺序。 
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python' 
favorite_languages['sarah'] = 'c' 
favorite_languages['edward'] = 'ruby' 
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + ".") 
 

文件和异常

# -----------从文件中读取数据 --------------
with open('pi_digits.txt') as file_object:    
    contents = file_object.read()
    print(contents)
 """相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢?因 为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删 除多出来的空行,可在print语句中使用rstrip()"""
with open('pi_digits.txt') as file_object:  
    contents = file_object.read()     
    print(contents.rstrip())
 """文件路径:Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/): """
# 逐行读取:要以每次一行的方式检查文件,可对文件对象使用for循环
filename = 'pi_digits.txt' 
with open(filename) as file_object:    
    for line in file_object:     
        print(line.rstrip())
# -------------写入文件------------------------
filename = 'programming.txt' 
  with open(filename, 'w') as file_object: 
        file_object.write("I love programming.") 
 """打开文件时,可指定读取模 式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如果 你省略了模式实参,Python将以默认的只读模式打开文件"""
# ---------------异常----------------------------
 try:   
     answer = int(first_number) / int(second_number)   
 except ZeroDivisionError:       
    print("You can't divide by 0!") 
 else:       
    print(answer) 
 # ---------------存储数据---------------------
# 函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。
import json  
numbers = [2, 3, 5, 7, 11, 13] 
filename = 'numbers.json' 
with open(filename, 'w') as f_obj: 
    json.dump(numbers, f_obj)
    
    
import json 
filename = 'numbers.json' 
with open(filename) as f_obj: 
    numbers = json.load(f_obj)   
    print(numbers) 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值