《编程小白的第一本Python入门书》笔记

用了两天时间读了一本Python的书,算是入门书吧。 确实写得很好。 这篇博客仅作为读书笔记。 PDF也已上传,下载地址:
http://download.csdn.net/detail/ch717828/9815193

版本为python 3.x

为什么选择Python

那些最好的程序员不是为了得到更高的薪水或者得到公众的仰慕而编程,它们只是觉得这是一件有趣的事 --Linux Torvalds

现在就开始

Mac上安装Python 3.x

Mac默认自带的Python版本为2.7 ,需要安装最新的Python 3.6

  1. 下载 : https://www.python.org/downloads/release/python-361/
  2. 直接打开安装包安装即可
  3. 检查 : 控制台输入python3

安装IDE

选择pycharm

  1. 下载 :
    https://www.jetbrains.com/pycharm/download/#section=mac
  2. 安装下载的安装包

变量与字符串

Python对大小写敏感,第一个helloword例子:

#!/usr/local/bin/python3
print("Hello, World!");

使用type()函数可以查看变量类型

#!/usr/local/bin/python3
#coding=utf-8

num = 1;
str = "2";

print(type(num)); #打印类型
print(type(str));

由于中文注释会导致报错,因此在文件开头加上一行 #coding=utf-8

字符串与数字的操作:

#!/usr/local/bin/python3
#coding=utf-8

num = 5;
str1 = "2";
str2 = "a";

print(str1*num);
print(str2*num);
print(int(str1)+num);

运行结果:

22222
aaaaa
7

字符串的分片与索引

字符串可以通过string[x]的方式进行索引、分片。字符串的分片(slice)实际上可以看作是从字符串中找出你要截取的东西,复制出来一小段你要的长度,存储在一个地方,而不会对字符串这个源文件改动。分片获得的每个字符串可以看作是原字符串的一个副本。

#!/usr/local/bin/python3
#coding=utf-8

name = "My Name is Mike";
print(name[0]); #M
print(name[-4]); #M
print(name[11:14]); #Mik
print(name[11:15]); #Mike
print(name[5:]); #me is Mike
print(name[:5]); #My Na

字符串方法

  • replace()
#!/usr/local/bin/python3
#coding=utf-8

phone_number = "86147-621-42214";
hiding_number = phone_number.replace(phone_number[:9],"*"*9);
print(hiding_number)
  • find()
#!/usr/local/bin/python3
#coding=utf-8

search = '168';
num_a = '1386-168-0006';
num_b = '1681-222-0006';
print(search+" is at "+str( num_a.find(search))+" to "+str(num_a.find(search)+len(search))+" of num_a");
print(search+" is at "+str( num_b.find(search))+" to "+str(num_b.find(search)+len(search))+" of num_b");
  • format()
#!/usr/local/bin/python3
#coding=utf-8


#With a word she can get what she come
print("{} a word she can get what she {} for.".format('With','came'));
print("{preposition} a word she can get what she {verb} for.".format(preposition='With',verb='came'));
print("{0} a word she can get what she {1} for.".format('With',"came"));

函数

  • 创建一个函数并调用
#!/usr/local/bin/python3
#coding=utf-8

def default_parameter(arg1,arg2,arg3=3):
    return arg1+arg2+arg3;

print(default_parameter(1,2)); #6
print(default_parameter(1,2,1)); #4
print(default_parameter(arg3=4,arg2=2,arg1=10)); #16
  • 创建一个文件
#!/usr/local/bin/python3
#coding=utf-8

def text_create(name,msg):
    desktop_path = '/Users/chenhong/Desktop/';
    full_path = desktop_path+name+".txt";
    file = open(full_path,'w');
    file.write(msg);
    file.close();
    print("Done");

text_create("text","text_create function");
  • 过滤敏感词
#!/usr/local/bin/python3
#coding=utf-8

def text_filter(str,cencored_word,changed_word):
    return str.replace(cencored_word,changed_word);
print( text_filter("My Love is Java","Java","Python") );

循环与判断

  • 不同类型的对象不能使用 ” < , > , <= , >=”进行比较,却可以使用 ” == ” 和 ” ! = ” ,例如字符串和数字。 需要注意的事, 浮点和整数虽然是不同的类型,但是不影响比较运算。

  • 布尔值的运算,True相当于1, False相当于0

True > False # 1>0
True + False > False + False # 1+0 > 0+0
  • 两个变量一致时,经过is对比(is是判断两个变量是否为同一个对象)后会返回True
#!/usr/local/bin/python3
#coding=utf8

the_Eddie = 'Eddie';
Eddie = 'Eddie';
input = input(""); #输入 Eddie
print(the_Eddie==Eddie); #true
print(the_Eddie is Eddie); #true
print(input == Eddie); #true
print(input is Eddie); #false

  • Python中任何对象都可以判断其布尔值。除了0、None、空字符串、所有空的序列与集合(列表,字典,集合)和布尔值为Fasle的之外,其他都为True。 可以使用函数 bool()进行判断。

  • if/else用法

#!/usr/local/bin/python3
#coding=utf-8

def account_login():
    password = input("Password:");
    password_is_correct = (password == "12345");
    if(password_is_correct):
        print("Login success");
    else:
        print("Paswword is wrong:");
        account_login();
account_login();
  • elif 用法
#!/usr/local/bin/python3
#coding=utf-8

password_list = ['***','12345'];
def account_login():
    password = input("Password:");
    password_is_correct = password == password_list[-1];
    password_need_reset = password == password_list[0];
    if(password_is_correct):
        print("Login success");
    elif(password_need_reset):
        new_password=input("Enter a new password:");
        password_list.append(new_password);
        print("Password has changed");
        account_login();
    else:
        print("Password is wrong");
        account_login();

account_login();
  • for 用法(省略文件前两行)
for letter in "Hello Word":
    print(letter);
  • range()用法
#!/usr/local/bin/python3
#coding=utf-8

for num in range(1,11):
    print(str(num)+" + 1 = ",num+1);
  • while用法
#!/usr/local/bin/python3
#coding=utf-8

password_list=["***","12345"];

def account_login():
    tries = 3;
    while(tries>0):
        password = input("Password:");
        password_is_correct = password ==password_list[-1];
        password_need_reset = password ==password_list[0];
        if(password_is_correct):
            print("Login success");
            break;
        elif(password_need_reset):
            new_password = input("Enter new password:");
            password_list.append(new_password);
            print("password has changed");
        else:
            print("wrong password");
            tries = tries -1;
    else:
        print("The account has been suspended");
account_login();        

数据结构

Python有4种数据结构

  1. 列表 list = [val1,val2,val3,val4]
  2. 字典 dict = {key1:val1,key2:val2}
  3. 元组 tuple = (val1,val2,val3,val4)
  4. 集合 set = {val1,val2,val3,val4}

列表

  • insert()

fruit = ['pineapple','pear'];
fruit.insert(1,'grape');
print(fruit); #pineapple,grape,pear
fruit[0:0] = ['apple'];
print(fruit); #apple,pineapple,grap,pear
fruit[0:-1]=['apple'];
print(fruit); #apple,pear
  • remove()
fruit = ['pineapple','pear'];
fruit.remove('pear');
print(fruit); #pineapple
fruit[0] = 'apple' ;
print(fruit); #apple
del fruit[0:1];
print(fruit); # 

字典

NASDAQ_code = {"BIDU":"Baidu","SINA":"Sina"};
NASDAQ_code['YOKU'] = 'Youku';
print(NASDAQ_code);#{'BIDU': 'Baidu', 'SINA': 'Sina', 'YOKU': 'Youku'}
  • update
NASDAQ_code = {"BIDU":"Baidu","SINA":"Sina"};
NASDAQ_code.update({'FB':'Facebook','TSLA':'Tesla'});
print(NASDAQ_code); #{'BIDU': 'Baidu', 'SINA': 'Sina', 'FB': 'Facebook', 'TSLA': 'Tesla'}
  • del
NASDAQ_code = {"BIDU":"Baidu","SINA":"Sina"};
del NASDAQ_code['SINA'];
print(NASDAQ_code); #{'BIDU': 'Baidu'}

元组

元组可以理解成一个稳固版本的列表,因为元组时不可修改的。

集合

a_set ={'a','b','c','d'};
a_set.add('e');  #{'c', 'e', 'd', 'b', 'a'}
a_set.discard('b'); #{'c', 'e', 'd', 'a'}

常用技巧

  • sorted()
num_list = [6,2,7,4,1,3,5];
print(sorted(num_list)) #[1, 2, 3, 4, 5, 6, 7]
print(sorted(num_list,reverse=True)); #[7, 6, 5, 4, 3, 2, 1]
  • zip()
num_list = [6,2,7,4,1,3,5];
str_list = "abcdefg";

for num,word in zip(num_list,str_list):
        print(str(num)+" : "+word);
  • 推导式

执行效率

import time;

list1 = [];
start_time = time.clock();
for i in range(1,200000):
        list1.append(i);
print(time.clock()-start_time," seconds process time"); #0.03

start_time = time.clock();
list2 = [i for i in range(1,200000)];
print(time.clock()-start_time," seconds process time"); #0.009

list

a = [i**2 for i in range(1,10)]; 
print(a); #[1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [j+1 for j in range(1,10)];
print(b);#[2, 3, 4, 5, 6, 7, 8, 9, 10]
c = [n for n in range(1,10) if n % 2 ==0]; 
print(c);#[2, 4, 6, 8]
d = [letter.lower() for letter in "ABCDEFG"];
print(d); ##['a', 'b', 'c', 'd', 'e', 'f', 'g']

dict

d = {i:i+1 for i in range(1,4)}
print(d);#{1: 2, 2: 3, 3: 4}
e = {i:j for i,j in zip(range(1,6),"abcde")}
print(e);#{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
f = {i:j.upper()  for i,j in zip(range(1,6),"abcde")};
print(f); #{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}
  • 遍历时获得元素的索引
letters = ['a','b','c','d','e','f','g'];
for num,letter in enumerate(letters):
        print(letter," is",num+1);

word count 例子

import string;

path = "./Walden.txt";
with open(path,'r') as text:
    words = [ raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()];
    words_index = set(words); #去重
    counts_dict = {index:words.count(index) for index in words_index};
    for word in sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True):
        print("{} - {} times".format(word,counts_dict[word]));

class Cocacola():
    it_taste = 'So good!';
    formula = ['caffeine','sugar','water','soda'];
    def drink(self):
        print("Energy!");



coke_for_bum = Cocacola();
coke_for_president = Cocacola();
coke_for_president.local_name = "可口可乐";
print(coke_for_bum.it_taste);  #So good!
print(coke_for_president.it_taste); #So good!

print(Cocacola.formula);  #['caffeine', 'sugar', 'water', 'soda']
print(coke_for_bum.formula);  #['caffeine', 'sugar', 'water', 'soda']
print(coke_for_president.formula);  #['caffeine', 'sugar', 'water', 'soda']

print(coke_for_president.local_name); #可口可乐

Cocacola.drink(coke_for_bum); #Energy!
coke_for_bum.drink(); #Energy!
coke_for_president.drink(); #Energy!
  • _init_()方法会在实例创建时自动调用
class Cocacola:
    def __init__(self):
        self.local_logo = "可口可乐";


coke = Cocacola();
print(coke.local_logo); #可口可乐

继承

class Cocacola:
    calories = 140;
    sodium = 45;
    total_carb = 39;
    caffeine = 34;
    ingredients = ['High Fructose Corn Syrup',
                   'Carbonated Water',
                   'Phosphoric Acid',
                   'Natural Flavors'];

    def __init__(self,logo_name):
        self.logo_name = logo_name;

    def drink(self):
        print("You got {}  caffeine!".format(self.caffeine));

class CaffeineFree(Cocacola):
    caffeine = 0;
    ingredients = ['Caramel Color'];

coke = CaffeineFree("无咖啡因咖啡");
coke.drink();

属性引用

Python中属性的引用机制是自外而内的,当创建了一个实例之后,准备开始引用属性,这时候编译器会先搜索该实例是否拥有该属性,如果有,则引用;如果没有,将搜索这个实例所属的类是否有这个属性,如果有,则引用,没有就报错。

  • 类属性如果被重新赋值,是否会影响到类属性的引用? 会
class TestA:
    attr = 1;

obj = TestA();
TestA.attr=43;
print(obj.attr); #43

 ```
  • 实例属性如果被重新复制,是否会影响到类属性的引用? 会
class TestA:
    attr = 1;

obj_a = TestA();
obj_b = TestA();

print(obj_a.attr); #1
obj_a.attr = 43;
print(obj_b.attr); #1
print(obj_a.attr); #43

- 类属性实例属性具有相同的名称

class TestA:
    attr = 1;
    def __init__(self):
        self.attr=43

obj_a = TestA();

print(obj_a.attr); #43
print(TestA.attr); #1 

第三方库

  • 使用PyCharm安装

    1. File > Default Settings
    2. Project Interpreter > 点 +
  • 终端安装

    1. 安装 pip

      sudo easy_install pip3

      如果要安装到python2中 ,选择使用

      sudo easy_install pip

    2. 查看版本 pip3 -V

    3. 安装库flask
      pip3 install flask

    4. 升级库pip
      pip3 install --upgrade pip
    5. 卸载库flask
      pip3 uninstall flask

你可能感兴趣的:(python)