Python3基础学习

最近因为论文需要应用Python做一些事情,虽然之前对Python已经有所了解并且做了一些小东西,但为了能更加全面一点,就对Python再做一个全面的学习。(参考书籍《Python编程 从入门到实战》)

第一章 起步

1 hello world程序

print("Hello World!")

第二章 变量和简单数据类型

1 变量命名和使用

  • 变量名只能包含数字、字母和下划线。变量名可以用字母或下划线打头,但不能以数字打头。
  • 变量名不能包含空格,但可以使用下划线来分隔其中的单词。
  • 不要将Python关键字和函数名用作变量名。
  • 变量名应既简短又具有描述性。
  • 慎用小写字母l和大写字母O,因为它们可能被人错看成数据1和0。

2 字符串

字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。

"This is a string."
'This is also a string.'

使用制表符  \t 或换行符 \n 来添加空白。

3 数字

3.1 整数

3.2 浮点数

3.3 使用函数str()避免类型错误

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

message = "Happy " + age + "rd Birthday!"
TypeError: can only concatenate str (not "int") to str

类型错误,无法识别使用的信息。变量age可能是数值23,也可能是字符2和3。

为此,可以调用函数str(),它让Python将非字符串值表示为字符串。

message = "Happy " + str(age) + "rd Birthday!"

 这样,将数值23转换为字符串。

4 注释

在大多数编程语言中,注释都是一项很有用的功能。

在Python中,注释用井号(#)标识。井号后面的内容都会被Python解释器忽略。

5 Python之禅

import this

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

第三章 列表简介

1 列表是什么

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

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)

['trek', 'cannondale', 'redline', 'specialized']

1.1 访问列表元素

列表是有序集合。因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。

print(bicycles[0])

trek

2 修改、添加和删除元素

2.1 修改列表元素

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

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

2.2 在列表中添加元素

在列表末尾添加元素

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

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

在列表中插入元素

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

['ducati', 'honda', 'yamaha', 'suzuki']

2.3 从列表中删除元素

使用del语句删除元素

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

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

使用方法pop()删除元素

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

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

弹出列表任何位置处的元素

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

The first motocycle I owned was a Honda.

根据值删除元素

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

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

3 组织列表

3.1 使用sort()方法对列表进行永久性排序

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

['audi', 'bmw', 'subaru', 'toyota']

向sort()方法传递参数reverse=True,按与字母顺序相反的顺序排列列表元素。

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

['toyota', 'subaru', 'bmw', 'audi']

 3.2 使用函数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']

3.3 倒着打印列表

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

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

第四章 操作列表

1 创建数值列表

1.1 使用函数range()

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

1
2
3
4

1.2 使用range()创建数字列表

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

[1, 2, 3, 4, 5]

2 元组

不可变的列表被称为元组。

第六章 字典

字典就是一系列键值对

1 嵌套

有时候,需要将一系列字典存储在列白哦中,或将列表作为值存储在字典中,这称为嵌套。

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell']
}
for name,languages in favorite_languages.items():
    print('\n' + name.title() + "'s favorite languages are:")
    for languages in languages:

Jen's favorite languages are:
    Python
    Ruby

Sarah's favorite languages are:
    C

Edward's favorite languages are:
    Ruby
    Go

Phil's favorite languages are:
    Python
    Haskell

在字典中存储字典

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())

Username:aeinstein
    Full name:Albert Einstein
    Location:Princeton

Username:mcurie
    Full name:Marie Curie
    Location:Paris

第七章 用户输入和while循环

1 函数input()的工作原理

height = input("How tall are you, in inches?")
height = int(height)
if height >= 36:
    print("\nYou're tall enough to ride")
else :
    print("\nYou'll be able to ride when you're a little older.")

How tall are you, in inches?35

You'll be able to ride when you're a little older.

2 删除包含特定值的所有列表元素

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

3 使用用户输入来填充字典

responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("\nWhat's your name?")
    response = input("\nWhich mountain would you like to climb someday?")
    # 将答卷存储在字典中
    responses[name] = response
    # 看看是否还有人要参与调查
    repeat = input("Would you like to let another person reponse?(yes/no)")
    if repeat == 'no':
        polling_active = False
# 调查结束,显示结果
print("\n---Poll Results---")
for name,response in responses.items():
    print(name + " would like to climb " + response + ".")

第八章 函数

函数是带名字的代码块,用于完场具体的工作。

第九章 类

第十章 文件和异常

1 从文件中读取数据

with open("pi_digits") as file_object:
    contents = file_object.read()
    print(contents)

3.1415926535
89456496895
45646546844

2 写入文件

filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love programming")

3 异常

使用try-except代码块

try:
    print(5/0)
except ZeroDivisionError:
    print("Jack, you can't divide by zero!")

Jack, you can't divide by zero!

4 存储数据

import json
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename,'w') as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back," + username + "!")
else:
    print("Wecome back, " + username + "!")

 第十一章 测试代码

1 测试函数

name_function.py

def get_formatted_name(first, last):
    full_name = first + " " + last
    return full_name.title()

names.py

from name_founction import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me a first name:")

    if first == 'q':
        break
    last = input("Please give me a last name:")
    if last == 'q':
        break
    formatted_name = get_formatted_name(first, last)
    print("\tNeatly formatted name:" + formatted_name + ".")

1.1 单元测试和测试用例

要为函数编写测试用例,可先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。

import unittest
from name_founction import get_formatted_name
class NamesTestCase(unittest.TestCase):
    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis Joplin')

unittest.main()

Ran 0 tests in 0.000s

OK

2 测试类

survey.py

class AnonymousSurvey():
    '''收集匿名问卷的答案'''
    def __init__(self,question):
        '''存储一个问题,并为存储答案做准备'''
        self.question = question
        self.responses = []
    def show_question(self):
        '''显示调查问卷'''
        print(self.question)
    def store_response(self,new_response):
        '''存储单份调查问卷'''
        self.responses.append(new_response)
    def show_results(self):
        '''显示收集到的所有答卷'''
        print('Survey results:')
        for response in self.responses:
            print('-' + response)

language_survey.py

from survey import AnonymousSurvey
#定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
#显示问题并存储答案
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)
#显示调查结果
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

测试AnonymousSurvey类

import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
    def test_store_single_response(self):
        question = 'What language did you first learn to speak?'
        my_survey = AnonymousSurvey(question)
        my_survey.store_response(('English'))
        self.assertIn('English',my_survey.responses)

unittest.main()

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

第十五章 生成数据

1 绘制简单的折线图

import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values, squares, linewidth = 5)
plt.title("Square Numbers",fontsize = 24)
plt.xlabel("Value",fontsize = 14)
plt.ylabel("Square of Value", fontsize = 14)
plt.tick_params(axis='both',labelsize=14)
plt.show()

使用scatter()绘制散点图并设置其样式

import matplotlib.pyplot as plt
plt.scatter(2,4,s=200)
# 设置图表标题并给坐标轴加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Value",fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()

使用scatter()绘制一系列点

import matplotlib.pyplot as plt
x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]
plt.scatter(x_values,y_values,s=100)
# 设置图表标题并给坐标轴加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Value",fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()

import matplotlib.pyplot as plt
x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values,y_values,s=40)
# 设置图表标题并给坐标轴加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Value",fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both',which='major',labelsize=14)
# 设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
plt.show()

2 随机漫步

random_walk.py

from random import choice
class RandomWalk():
    '''生成一个随机漫步数据的类'''
    def __init__(self,num_points=5000):
        '''初始化随机漫步的属性'''
        self.num_points = num_points
        '''所有随机漫步都始于(0,0)'''
        self.x_values=[0]
        self.y_values=[0]
    def fill_walk(self):
        '''计算随机漫步包含的所有点'''
        # 不断漫步,直到列表达到指定的长度
        while len(self.x_values) < self.num_points:
            # 决定前进方向以及沿着这个方向前进的距离
            x_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance
            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance
            # 拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue
            # 计算下一个点的x和y值
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)

rw_visual.py

import matplotlib.pyplot as plt
from random_walk import RandomWalk
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()

import matplotlib.pyplot as plt
from random_walk import RandomWalk
# 只要程序处于活动状态,就不断地模拟随机漫步
while True:
    # 创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
    # 突出起点和终点
    plt.scatter(0,0,c='green',edgecolors='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)
    plt.show()
    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值