python基础
1、python 简介
各种网站都有关于 Python 的简介
Python is powerful... and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open.
2、python 版本区别
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language
Python 2.7 是一个兼容版本,but Python 2.7 would be supported until 2020
print 用法不同:
# python 2.x print "Hello World!" print >>sys.stderr, "fatal error"
# python 3.x print("Hello World!") print("fatal error", file=sys.stderr) (first,*middle,last) = range(10)
Python 3.x 默认支持 Unicode,Python 2.x 默认支持 ASCII
Python 2.x 需要支持中文时:
# /usr/bin/env python # -*- coding: utf-8 -*- print "您好!"
Python 3.x 默认支持中文:
# /usr/bin/env python print("您好!")
Python 3.x 某些库的名称变更
Old Name |
New Name |
_winreg |
winreg |
ConfigParser |
configparser |
copy_reg |
copyreg |
Queue |
queue |
SocketServer |
socketserver |
markupbase |
_markupbase |
repr |
reprlib |
test.test_support |
test.support |
so,后面的学习选择 python 3.x 版本
3、安装
-
Windows 下安装
-
下载安装包
https:
/
/
www.python.org
/
downloads
/
-
安装
默认安装路径: C:\Program Files\Python35
-
添加环境变量
右键计算机 --> 属性 --> 高级系统设置 --> 高级 --> 环境变量 --> path --> 添加路径
如:添加 ;C:\Program Files\Python35;C:\Program Files\Python35\Scripts
-
Linux 下安装
- 下载安装包
-
- 安装
root@localhost tmp]# tar zxf Python-3.5.2.tgz [root@localhost tmp]# cd Python-3.5.2 # 默认安装在 /usr/loca/ 目录下 [root@localhost Python-3.5.2]# ./configure [root@localhost Python-3.5.2]# make && make install [root@localhost Python-3.5.2]# python3.5 Python 3.5.2 (default, Aug 13 2016, 19:07:36) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
4、第一个程序
在 Linux 的目录中创建 hello.py 文件,并赋予权限
[root@localhost learning]# cat hello.py #!/usr/bin/env python print("Hello World!") [root@localhost learning]# chmod +x hello.py [root@localhost learning]# ./hello.py Hello World!
也可以在解释器中执行
[root@localhost learning]# python Python 3.5.2 (default, Aug 13 2016, 19:07:36) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World!") Hello World! >>>
5、变量
Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
-
变量命名的规则
-
变量名只能是大小写字母,数字以及下划线的组合
-
变量名不能以数字开头
-
变量名不能为以下关键字
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
-
变量的声明与赋值
声明一个变量名为 name,变量 name 的值为 wenchong
>>> name = "wenchong" >>> print(name) wenchong >>> # 当变量 name1 赋值为 name 时,是将变量 name 的值(即内存中的值)赋值给 name1,当 name 再次变化时,不会影响 name1 的值 >>> name1 = name >>> id(name) 139659587567344 >>> id(name1) 139659587567344 >>> name = "Jack" >>> id(name) 139659587549592 >>> id(name1) 139659587567344 >>> print(name,name1) Jack wenchong
6、用户输入
1 #!/usr/bin/env python 2 # Get User Input String 3 name = input("Please Input Name:") 4 """ 5 Python 2.x 6 name = raw_input("Please Input Name:") 7 """ 8 print(name)
第1行:指定解释器
第2行:单行注释
第3-7行:多行注释
第8行:输入用户输入的内容
当输入密码时,希望输入的密码不可见,该模块在 windows 的 pycharm 中不生效
#!/usr/bin/env python import getpass passwd = getpass.getpass("Please Input Passwd: ") print(passwd) [root@localhost learning]# python hello.py Please Input Passwd: password [root@localhost learning]#
7、模块
在捕获输入密码的 python 程序中,其中一行为 import getpass,即为导入模块
-
os 模块
os.mkdir() 创建目录
os.system() 执行系统命令,命令结果无法赋值给变量,只能讲返回码赋值给变量
os.popen() 执行系统命令,命令结果可以赋值给变量
# 导入模块 os >>> import os >>> os.mkdir("testDir") >>> os.system("ls -l") total 4 -rwxr-xr-x 1 root root 238 Aug 13 20:17 hello.py drwxr-xr-x 2 root root 6 Aug 13 20:23 testDir 0 >>> command_res = os.system("ls -l") total 4 -rwxr-xr-x 1 root root 238 Aug 13 20:17 hello.py drwxr-xr-x 2 root root 6 Aug 13 20:23 testDir >>> print(command_res) 0 >>> command_res = os.popen("ls -l").read() >>> print(command_res) total 4 -rwxr-xr-x 1 root root 238 Aug 13 20:17 hello.py drwxr-xr-x 2 root root 6 Aug 13 20:23 testDir
-
sys 模块
sys.path python 解释器查找模块的路径列表
>>> import sys >>> print(sys.path) ['', '/usr/local/lib/python35.zip', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-linux', '/usr/local/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/site-packages'] >>>
-
编写模块
python 的所有文件都可以当做模块使用
[root@localhost learning]# cat mymodel.py #!/usr/bin/env python myname = "Test Model" [root@localhost learning]# python Python 3.5.2 (default, Aug 13 2016, 19:07:36) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import mymodel >>> print(mymodel.myname) Test Model >>>
8、流程控制
-
场景1:用户密码验证
#!/usr/bin/env python import getpass username = "wenchong" passwprd = "pwd123" input_username = input("请输入用户名: ") input_password = getpass.getpass("请输入密码: ") if username == input_username and password == input_password: print("欢迎登陆到天堂...") else: print("无效的用户名或密码")
-
场景2:猜数字小游戏
#!/usr/bin/env python number = 20 input_num = int( input("请猜一个数字: ") ) if input_num == number: print("恭喜您,猜对了") elif input_num > number: print("请猜一个更小的数字") else: print("请猜一个更大的数字")
9、循环
-
场景1:
之前猜数字的小游戏猜一次之后程序就会自动退出,那么有什么办法可以猜一次之后继续猜测,直到猜测正确
#!/usr/bin/env python number = 20 for i in range(10): input_num = int(input("请猜一个数字: ")) if input_num == number: print("恭喜您,猜对了") # 如果猜对了,则退出整个循环 break elif input_num > number: print("请猜一个更小的数字") else: print("请猜一个更大的数字")
-
场景2:
当猜测三个之后,程序会提示是否仍然要继续
#!/usr/bin/env python number = 20 # 定义一个计数器变量 count = 0 for i in range(10): # 当计数器的值大于2时,提示是否继续,如果选择继续,则将计数器重置为0,否则退出整个循环 if count > 2: user_input = input("请问是否仍然要继续?(y/n): ") if user_input == "y": count = 0 continue else: break input_num = int(input("请猜一个数字: ")) if input_num == number: print("恭喜您,猜对了") break elif input_num > number: print("请猜一个更小的数字") else: print("请猜一个更大的数字") # 循环执行一次,即猜测一次数字,计数器加1 # count += 1 等价于 count = count + 1 count += 1