Fork me on GitHub

Python学习笔记之语言基础与流程控制

Python简介

 python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承。

 

Python的特点

 Python 优点
    1.简单、优雅、明确
    2.强大的模块第三方库
    3.易移植
    4.纯面向对象语言
    5.可扩展性良好(c\java\c#。。。)

  Python缺点
    1.代码不能加密
    2.执行速度慢

  Python能做什么
    1.软件开发
      1.游戏后台、搜索、图形界面
      2.网站
      3.C\S软件
      4.科学运算  
    2.系统管理
      1.脚本
      2.IT自动化工具

 

Python的编码风格

 1 1.分号
 2   不要在行尾加分号,也不要用分号将两条命令放在一行
 3 
 4 2.行长度
 5   每行不超过80个字符
 6 
 7 3.括号
 8   除非是用于实现行连接,否则不要在返回语句或条件语句中使用括号,不过在元祖两边使用括号还是可以的
 9 
10 4.缩进
11   用4个空格来缩进代码
12 
13 5.空行
14   顶级定义之间空两行,方法定义之间空一行[类2行,函数1行]
15 
16 6.空格
17   按照标准的排版规范来使用标点两边的空格
18 
19 7.SheBang
20   大部分.py文件不必以#!作为文件的开始。根据PEF-394,程序的main文件应该以
21 #!/usr/bin/python2或#!/usr/bin/python3开始
22 
23 8.注释
24   确保对模块、函数、方法和行内注释使用正确的风格
25 
26 9.类
27   如果一个类不继承自其它类,就显示的从object继承,嵌套类也一样
28 
29 10.字符串
30   即使参数都是字符串,使用%操作符或者格式化方法格式化字符串,不过也不能一概而论,你需要在+和%之间好好判定
31 
32 11.文件和sockets
33   在文件和sockets结束时,显式的关闭它
34 
35 12.TODO注释
36   为临时代码使用TODO注释,它是一种短期解决方案,不算完美,但够用就好
37 
38 13.导入格式
39   每个导入应该独占一行
40 
41 14.语句
42   通常每个语句应该独占一行
43 
44 15.访问控制
45    在Python中,对于琐碎又不太重要的访问函数,你应该直接使用公有变量来取代它们,
46 这样可以避免额外的函数调用开销,当添加更多功能时,你可以用属性(prorerty)来保持语法的一致性
47 
48 16.命名
49    1.所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
50    2.用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含).
51    3.用双下划线(__)开头的实例变量或方法表示类内私有.
52    4.将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.
53    5.对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py). 
54 尽管已经有很多现存的模块使用类似于CapWords.py这样的命名, 但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致, 这会让人困扰.
55 
56 17.Main
57    即使是一个打算被用作脚本的文件,也应该是可以导入的。并且简单的导入不应该导致
58 这个脚本的主功能(main functionality)被执行,这是一种副作用。主功能应该放在一个mian()函数中

 

Python指定解释器

这是脚本语言共同遵守的规则:当第一行为 #!/path/to/script/interpreter时,指定了用来执行本脚本的解释器。
注意:
1、必须是文件的第一行
2、必须以#!开头,你丢了一个惊叹号
3、/path/to/script/interpreter是脚本解释器的全路径名。

例如:
#!/bin/sh           shell脚本
#!/usr/bin/perl     perl脚本
#!/usr/bin/python   python脚本
#!/usr/bin/python3  python3脚本
#!/usr/bin/python2  python2脚本

而有时不太清楚脚本解释器的具体全路径名;或者开发环境与运行环境的安装路径不同。为了保证兼容性,也可以写作:
#!/usr/bin/env python3
这样运行时会自动搜索脚本解释器的绝对路径。
/usr/bin是一个系统目录,里面存储一些系统命令,可执行程序。
类似windows操作系统的C:\Windows\System32目录

 

Python注释

#单行注释

eg: #这是个单行注释

#多行注释

eg:
'''多行注释
多行注释
多行注释
'''

#单引号与多引号,没区别

 

 

Python变量运算

#变量→可变的量
例如:
x = 2
y = 3

#常量→不可变的量、默认不变
PAI = 3.141592654

写代码的时候,一般小写的表示变量,大写表示常量

>>> x = 2
>>> z = x
>>> print('z:',z)
z: 2
>>> x = 5
>>> print('x:',x)
x: 5
>>> print('z:',z)
z: 2
>>>

当创建x = 2时,解释器干了两件事
1.在内存中,创建了一个名为2的数字
2.在内存中创建了一个名为x的变量,并把它指向2

z = x
1.把z指向x所指向的2

x = 5
1.把x重新指向了5,(又重新开辟了一块内存)

>>> a = 1
>>> id(a)
491282656
>>> a = 2
>>> id(a)
491282688
>>>


语法要求:
   1.缩进统一
   2.变量:
      1.标识符的第一个自反目必须是字母表中的字母(大写或小写)或者一个下划线(‘_’)
      2.标识符名称的其他部分可以是由字母(大写或小写)、下划线(“_”)或数字(0-9)组成
      3.标识符名称是对大小写敏感的,例如,myname和myName不是一个标识符。注意前者中的小写n和后者中的大写N
      4.有效标识符名称例子i,_my_name,name_123和a1b1
        无效标识符名称列子2thing、 this is 和my-name

#----------------------------------------数据类型[特征划分]-------------------------------------------
1.数字类型
   1.整型
     1.布尔型:True False
     2.长整型(L) 存的数据大
     3.标准整型    存的数据小   [当存的数据长的时候,Python自动转换]
   2.非整型
     1.双精度浮点型(float)
     2.复数
     3.decimal(不是内建类型)

2.序列类型[数组]
   1.字符串(str)
   2.元祖(tuple)
   3.列表(list)

3.映像类型
   1.字典(dict)

4.集合类型
   1.可变集合(set)
   2.不可变集合(frozenset)

#----------------------------------------数据类型[可变性划分]-------------------------------------------
1.不可变数据类型
  1.数字类型
  2.不可变集合(frozenset)
  3.字符串(str)
  4.元祖(tuple)

2可变数据类型
  1.字典(dict)
  2.列表(list)
  3.可变集合(set)


#----------------------------------------算术运算-------------------------------------------
+ 相加
- 相减
* 相乘
/ 相除
% 取余
**  a**b a的b次方
// 取整除

#----------------------------------------比较运算-------------------------------------------
== 等于
!= 不等于
<> 不等于
>  大于
<  小于
>= 大于等于
<= 小于等于

#----------------------------------------赋值运算-------------------------------------------
= 简单的赋值运算符
+= 加法赋值运算符, c += a 等效于c = c+a
-= 减法赋值运算符, c -= a 等效于c = c-a
*= 乘法赋值运算符, c *= a 等效于c = c*a
/= 除法赋值运算符, c /= a 等效于c = c/a
%= 取模赋值运算符, c %= a 等效于c = c%a
**= 幂赋值运算符,  c **= a 等效于c = c**a
//= 取整除赋值运算符, c //= a 等效于c = c//a

#----------------------------------------位运算-------------------------------------------
128 64 32 16 8 4 2 1
 
 0  0  0  0  1 0 1 0  = 10 

 0  0  0  1  0 1 0 0  = 20 

& 按位与[两个都为真]:  10 % 20 = 0
| 按位或[一个为真则为真]:10 | 20 = 1 1 1 1 0 = 30
^ 按位异或[两个一样为假,两个不一样则为真]: 10 ^ 20 = 1 1 1 1 0 = 30
~ 按位取反[相反] 所有正整数的按位取反是其本身+1的负数、所有负整数的按位取反是其本身+1的绝对值、零的按位取反是 -1
<< 左移动:  10 << 2 =  0 0 1 0 1 0 0 0 = 40
>> 右移动: 10 >> 2 =  0 0 0 0 0 0 1 0 = 2

#----------------------------------------逻辑运算-------------------------------------------
andornot#----------------------------------------成员运算-------------------------------------------
in 在指定序列则返回True
not in 不在指定序列则返回True

#----------------------------------------成员运算-------------------------------------------
is  判断标识符是否引自一个对象:  id(20)is id(20is not 判断标识符是不是引自不同的对象:  id(20)is not id(30)

 

 

Python字符编码

# 字符编码
ASSIC
Unicode
UTF-8

256 2**8  ASSIC  8位一个字节 ord('a'):查看对应的字母、数字、符号对应的数字

一个字节变成2个字节 65536 2**16  Unicode   存储占两个字节

UTF-8 三个字节存一个汉字 ,解决Unicode占容量大的问题

gbk 每个汉字表对应ASSIC一个数字

Python默认ASSIC


s = u'中文'
s_encode = s.encode('utf-8')
print(s_encode)
s_decode = s_encode.decode('utf-8')
print(s_decode)

#result
》》b'\xe4\xb8\xad\xe6\x96\x87'
》》中文

encode 转码  unicode→utf-8
decode 解码  
以unicode读取到内存,utf-8存储到硬盘

#指定编码格式
例:
   # coding:utf-8
   #_*_coding:utf-8 _*_

 

Python模块导入

#导入模块

<!--import语句-->
   导入Python源文件,只需在另一个源文件执行import语句

import module

>>> import os
>>> os.system('adb devices')
List of devices attached
adb server is out of date.  killing...
* daemon started successfully *
596cb85a        device

<!--保存dos命令行内容-->
>>> import os
>>> a = os.popen('adb devices').read()
>>> a
'List of devices attached\n596cb85a\tdevice\n\n'

#subprocess  命令行操作


》》import sys
》》print(sys.argv[0]) 取执行脚本后面的参数


<!--别名-->
import multiprocessing as mult


<!--from..import语句-->
    Python的from语句让你从模块中导入一个指定的部分到当前命名空间

from modname import name1

》》import sys impot argv


<!--from..import*语句-->
    把一个模块的所有内容全部导入到当前命名空间

from modname import *

 

 

Python流程控制

#流程控制
if...else

》》
name = input('please input your name')

global age
global msg
for i in range(10):
    age = int(input('age'))
    if age > 29:
        msg = 'this smaller!'
    elif age == 29:
        msg = '\033[32;1mgood!\003[0m'
        break
    else:
        msg = 'this bigger!'

    print('you still got %s shots!' % (9-i))

print('''
personal information of %s:
         name: %s
         age: %d
----------------------------
%s
''' % (name, name, age, msg))

<!--高亮-->
显示颜色格式:\033[显示方式;字体色;背景色m......[\033[0m]
------------------------------------------
-------------------------------------------
字体色     |       背景色     |      颜色描述
-------------------------------------------
30        |        40       |       黑色
31        |        41       |       红色
32        |        42       |       绿色
33        |        43       |       黃色
34        |        44       |       蓝色
35        |        45       |       紫红色
36        |        46       |       青蓝色
37        |        47       |       白色
-------------------------------------------
-------------------------------
显示方式     |      效果
-------------------------------
0           |     终端默认设置
1           |     高亮显示
4           |     使用下划线
5           |     闪烁
7           |     反白显示
8           |     不可见
-------------------------------


while 默认死循环

》》
count = 0
while True:
    print('loop:', count)
    count += 1


while...else 当循环条件不满足时,执行else语句
》》
count = 0
while count < 10:
    print('loop:', count)
    count += 1
else:
    print('ending....')

#result
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
ending....


break 跳出循环
continue 跳出本次循环
》》
str_hello = 'hello'
for str_ in str_hello:
    if str_ == 'e':
        continue
    print(str_)


》》
count = 0
num = int(input('which loop do you want it to be printed out?'))
while count < 10000:
    if count == num:
        print('this is you got the number', count)
        choice = input('do you want to continue?(y/n)')
        if choice == 'n':
            break
        else:
            while num <= count:
                print('sx')
                num = int(input('which loop do you want it to be printed out?'))
    else:
        print('loop:', count)
    count += 1
else:
    print('ending....')

 

 

Python格式输出

#用户交互

》》
name = input('请输入用户名:')
password = input('请输入密码:')
print(name, password)

#reslut
》》
请输入用户名:luting
请输入密码:123456
luting 123456

#格式化输出
》》
name = input('请输入用户名:')
password = input('请输入密码:')

print('''
输入的账号密码为:
   账号:%s
   密码:%s

#result
》》
请输入用户名:luting
请输入密码:123456

输入的账号密码为:
   账号:luting
   密码:123456
''' % (name, password))

# 格式化:%s[str] %d[number] %f[float]

 

练习

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 from __future__ import print_function
 4 '''
 5 功能点:
 6       1.循环输出计数器
 7       2.根据输入的数字,停止循环输出
 8       3.当输入Y/N后继续循环。或退出
 9       4.若输入的数字,已经小于计数器,则抛出友好性提示信息
10 '''
11 import sys
12 while True:
13     input_order = input('请输入操作指令:(1:继续/0:退出)')
14     if input_order == '0':
15         sys.exit()
16     else:
17         count = 0
18         input_num = 0
19         while count < 1000:
20             if count == input_num:
21                 input_num = int(input('请输入要中断的数字 (0-1000)'))
22                 while input_num <= count:
23                     if input_num == 0:
24                         sys.exit()
25                     else:
26                         print('已经过了')
27                     break
28             else:
29                 print('loop:', count)
30                 count += 1

 

 

#!/usr/bin/python3
# coding:utf-8
from __future__ import print_function
import os
import sys

__author__ = 'luting'

'''
编写登录接口
  1.输入用户名密码
  2.认证成功后显示欢迎信息
  3.输错三次后锁定
'''

test_data = {'user': 'luting', 'password': '123456'}
lock_path = os.path.join(os.getcwd(), 'lock.txt')

try:
    while True:
        with open(lock_path, 'r') as file:
            lock_data = file.readlines()
            lock_list = []
            for lock_num in lock_data:
                lock_list.append(lock_num.strip())
            login_count = 0
            input_username = (input('请输入账号:')).strip()
            if input_username == "":
                print('输入的账号不可为空!')
            elif input_username not in test_data['user']:
                print('输入的账号不存在!')
            else:
                if input_username in lock_list:
                    print('%s,你的账号已被锁住!' % input_username)
                    clear_order = input('是否要清空lock文件中的用户(1:清空/0:不执行并退出)')
                    if clear_order == '1':
                        with open(lock_path, 'w') as fil:
                            fil.truncate()
                        print('%s lock文件已清空,请继续登录' % input_username)
                    else:
                        print('%s 欢迎下次继续使用 ' % input_username)
                        sys.exit()
                    continue
                else:
                    while login_count < 3:
                        input_password = input('请输入密码:')
                        if input_username == test_data['user'] and input_password == test_data['password']:
                            print('\033[31;1m欢迎基佬入坑!\033[0m')
                            sys.exit()
                        else:
                            print('您输入的账号:%s 有误,请再次输入!还有 \033[31;1m%s \033[0m机会' % (input_username, 2 - login_count))
                        login_count += 1
                    else:
                        with open(lock_path, 'a') as f:
                            f.write(('%s' % input_username) + '\n')
                        sys.exit()
except FileNotFoundError as error:
    print('FileNotFoundError:{0}'.format(error))

 

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 import random
 4 import sys
 5 '''
 6 猜数字的游戏:
 7     1.由一个人随机写一个整数1-99(如:21)
 8     2.一群小伙伴轮流猜数字,如第一个人猜一个数(如:48),则缩小范围为(1-48)
 9     3.如第二个人猜一个数(如:9),则缩小范围为(9-48)
10     4.以此类推,值到猜中数字(21),游戏结束
11 '''
12 
13 __author__ = 'luting'
14 
15 secret_num = random.randint(1, 100)
16 
17 print('Please enter an integer 1 - 100')
18 print('*'*50)
19 while True:
20     num_input = input('Please enter an integer').strip()
21     if num_input == '':
22         print('\033[1;31;0m Order is empty,Please input again!\033[0m')
23     elif num_input.isdigit() is False:
24         print('\033[1;31;0m Input is not typing Numbers,Please input again!\033[0m')
25     elif int(num_input) not in [num for num in range(1, 101)]:
26         print('\033[1;31;0mThe input range crosses the line!\033[0m')
27     elif int(num_input) == secret_num:
28         print('\033[1;31;0mCongratulations on your guess!\033[0m')
29         while True:
30             continue_order = str(input("Do you want to continue 'Y' or 'N'")).strip()
31             if continue_order == '':
32                 print('\033[1;31;0m Order is empty,Please input again!\033[0m')
33             elif continue_order not in ['Y', 'N']:
34                 print('\033[1;31;0m Order is Error,Please input again!\033[0m')
35             elif continue_order == 'Y':
36                 break
37             else:
38                 sys.exit()
39     else:
40         if int(num_input) < secret_num:
41             print('\033[1;31;0mThe answer is wrong, please input %s - %s go on!\033[0m' % (num_input, secret_num))
42             continue
43         elif int(num_input) > secret_num:
44             print(print('\033[1;31;0mThe answer is wrong, please input %s - %s go on!\033[0m' % (secret_num, num_input)))
45             continue

 

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 from __future__ import print_function
 4 '''
 5 交换a,b值
 6 '''
 7 
 8 
 9 def change_value(a, b):
10     a, b = b, a
11     return a, b
12 
13 print(change_value(1, 2))
14 print(change_value('hello', 'world'))

 

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 from __future__ import print_function
 4 '''
 5 在排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数
 6 依次进行比较和调整,让较大的数往下沉,较小的往上冒,即:当相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换
 7 '''
 8 
 9 nums = [3, 2, 1, 9, 10, 78, 6]
10 
11 for i in range(len(nums)):
12     for j in range(i):
13         if nums[i] < nums[j]:
14             nums[i], nums[j] = nums[j], nums[i]
15     print(nums)

 

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 from __future__ import print_function
 4 '''
 5 28~10000的完美数
 6 '''
 7 
 8 for i in range(1, 10001):
 9     if i > 28:
10         list_value = []
11         for j in range(1, i):
12             if i % j == 0:
13                 list_value.append(j)
14         if sum(list_value) == i:
15             print(i)

 

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 from __future__ import print_function
 4 '''
 5 需求:
 6     1、使用while循环输入 1 2 3 4 5 6     8 9 10
 7     2、求1-100的所有数的和
 8     3、输出 1-100 内的所有奇数
 9     4、输出 1-100 内的所有偶数
10     5、求1-2+3-4+5 ... 99的所有数的和
11 '''
12 
13 # 第一题
14 list_value = [var for var in range(1, 11)]
15 count = -1
16 while count < len(list_value)-1:
17     count += 1
18     if list_value[count] == 7:
19         continue
20     print(list_value[count])
21 
22 # 第二题
23 print(sum([var for var in range(1, 101)]))
24 
25 # 第三题
26 odd_num = []
27 for num in range(1, 101):
28     if num % 2 == 1:
29         odd_num.append(num)
30 print(sum(odd_num))
31 
32 # 第四题
33 even_num = []
34 for num in range(1, 101):
35     if num % 2 == 0:
36         even_num.append(num)
37 print(sum(even_num))
38 
39 # 第五题
40 num = [n for n in range(1, 100)]
41 odd_value = num[::2]
42 even_value = num[1::2]
43 print(sum(odd_value)-sum(even_value))

 

posted @ 2017-12-17 16:25  未凉残念浮生若梦  阅读(302)  评论(0编辑  收藏  举报