python-1 python基础知识
python第一课代码笔记
hello world
[root@heartbeat-data-1 python]# vim hello1.py #!/usr/bin/env python print ('hello world!') [root@heartbeat-data-1 python]# python hello1.py hello world!
注意
#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;
#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。
#!/usr/bin/python相当于写死了python路径;
#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法
[root@heartbeat-data-1 python]# vim hello2.py def main(): print("hello") main() IndentationError: expected an indented block 缩进错误 [root@heartbeat-data-1 python]# vim hello2.py def main(): print("hello") main()
变量
[root@heartbeat-data-1 python]# vim plus.py x = 2 y = 3 print (x + y) [root@heartbeat-data-1 python]# python plus.py 5 [root@localhost python]# vim plus.py def main(): x = 2 y = 4
print(x + y) main() # python plus.py
6 大写的一般是常量,小写的是变量 [root@heartbeat-data-1 python]# vim test.py x = 2 y = 3 z = x x = 5 print ('Z:',z) print ('X:',x) [root@heartbeat-data-1 python]# python test.py Z: 2 X: 5 [root@heartbeat-data-1 python]# vim test1.py a = 'ABC' b = a a = 'XYZ' print(b) print(a) [root@heartbeat-data-1 python]# python test1.py ABC XYZ 单行注释:#,多行注释:’’’ 三个引号 #print ‘ddd’ [root@localhost python]# vim zhushi.py print
''' print 'ddd' print 'ddd' print 'ddd' ------------------
'''
[root@localhost python]# python zhushi.py
print 'ddd'
print 'ddd'
print 'ddd'
------------------
理解字符編碼:
#_*_coding:utf8_*_
在脚本里面添加以上那句话,可解决中文问题
ASSIC(8进制) UNICODE(16进制) UTF8(可变长度的) ASSIC:1个字节8位,2的8次方,最多存256个数 UNICODE:2的16次方,最多存65536 UTF8:可变长度的 [root@heartbeat-data-1 Python-3.4.4]# python >>> ord('a') 97 >>> ord('A') 65 >>> a = 'wwp' >>> type(a) <class 'str'> >>> len(a) 3
In [1]: name = '咖啡可乐'
In [2]: name
Out[2]: '\xe5\x92\x96\xe5\x95\xa1\xe5\x8f\xaf\xe4\xb9\x90'
In [3]: name.encode('utf-8')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-3-977844d87663> in <module>()
----> 1 name.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
读取文件时使用的编码默认时ascii而不是utf8,导致的错误
解决方法
In [6]: import sys
In [7]: reload(sys)
<module 'sys' (built-in)>
In [9]: sys.setdefaultencoding('utf8')
In [10]: name.encode('utf-8')
Out[10]: '\xe5\x92\x96\xe5\x95\xa1\xe5\x8f\xaf\xe4\xb9\x90'
In [12]: name_utf8=name.encode('utf-8')
In [13]: len(name_utf8)
Out[13]: 12
模块
>>> import os >>> os.system('df -h') Filesystem Size Used Avail Use% Mounted on /dev/sda5 44G 2.2G 39G 6% / tmpfs 491M 0 491M 0% /dev/shm 0 >>> os.system('free -m') total used free shared buffers cached Mem: 981 741 239 0 29 587 -/+ buffers/cache: 125 855 Swap: 2047 0 2047 0
内置模块
os内置模块 |
用于提供系统级别的操作 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd os.curdir 返回当前目录: ('.') os.pardir 获取当前目录的父目录字符串名:('..') os.makedirs('dirname1/dirname2') 可生成多层递归目录 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() 删除一个文件 os.rename("oldname","newname") 重命名文件/目录 os.stat('path/filename') 获取文件/目录信息 os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/" os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" os.pathsep 输出用于分割文件路径的字符串 os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix' os.system("bash command") 运行shell命令,直接显示 os.environ 获取系统环境变量 os.path.abspath(path) 返回path规范化的绝对路径 os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是绝对路径,返回True os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 |
sys内置模块
|
sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的版本信息 sys.maxint 最大的Int值 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform 返回操作系统平台名称 sys.stdout.write('please:') val = sys.stdin.readline()[:-1] |
交互式
交互式:raw_input默认输出的都是字符串 input 输出的是数字 raw_input和input的区别:input本身格式是什么就调用什么,raw_input默认输出的都是字符串
普通版本
[root@python scripts]# vim test0.py #!/usr/bin/env python #_*_coding:utf-8 _*_ name = raw_input('Please input your name:') age = raw_input("age:") print name , age
升级版 [root@python scripts]# vim test1.py #!/usr/bin/env python #_*_coding:utf-8 _*_ name = raw_input('Please input your name:') age = raw_input("age:") job = raw_input("job:") salary = raw_input("salary:") print ''' Personal information of %s: Name: %s Age : %s Job : %s Salary: %s --------------------- ''' % ( name,name,age,job,salary) %s代表字符串 %d代表数字 %f 代表浮点数
流程控制
流程控制语句: if语句 if else
#!/usr/bin/env python #_*_coding:utf-8 _*_ name = raw_input('Please input your name:') age = input("age:") job = raw_input("job:") salary = raw_input("salary:") if age > 30: msg = 'You are too fucking old!' else: msg = 'You are still young' print ''' Personal information of %s: Name: %s Age : %d Job : %s Salary: %s --------------------- %s '''
% ( name,name,age,job,salary,msg)
if elif else
#!/usr/bin/env python #_*_coding:utf-8 _*_ name = raw_input('Please input your name:') age = input("age:") job = raw_input("job:") salary = raw_input("salary:") if age > 40 : msg = 'You are too fucking old!' elif age > 30 : msg = 'You are still have a few years to hook up' else : msg = 'You are still young' print ''' Personal information of %s: Name: %s Age : %d Job : %s Salary: %s --------------------- %s '''
% ( name,name,age,job,salary,msg)
for 语句:
#!/usr/bin/env python #_*_coding:utf-8 _*_ name = raw_input('Please input your name:') job = raw_input("job:") salary = raw_input("salary:") real_age = 29 for i in range(10) : age = input('age:') if age > 29 : print 'big!' elif age == 29 : print '\033[32;1mright!\033[0m' 带颜色 break else : print 'small' print 'You still got %s shots!' % (9 - i) print ''' Personal information of %s: Name: %s Age : %d Job : %s Salary: %s --------------------- '''
% (name,name,age,job,salary) while循环 [root@python scripts]# vim test4.py count = 0 while True: print 'loop;',count count +=1 版本1 print_num = input ('which loop do you want it to be printed out?') count = 0 while count < 100000000: if count == print_num: print 'There you got the num:',count choice = raw_input('Do U want to continue the loop?y/n') if choice == 'n': break else: print 'Loop:',count count +=1 else: print 'Loop:count',count 版本2 print_num = input ('which loop do you want it to be printed out?') count = 0 while count < 100000000: if count == print_num: print 'There you got the num:',count choice = raw_input('Do U want to continue the loop?y/n') if choice == 'n': break else: print_num = input('which loop do you want it to be printed out?') else: print 'Loop:',count count +=1 else: print 'Loop:count',count 版本3 [root@python software]# vim test.py #_*_coding:utf-8_*_ print_num = input ('which loop do you want it to be printed out?') count = 0 while count < 100000000: if count == print_num: print 'There you got the num:',count choice = raw_input('Do U want to continue the loop?y/n') if choice == 'n': break else: while print_num <= count: print_num = input ('which loop do you want it to be printed out?') print "the num have passed" else: print 'Loop:',count count +=1 else: print 'Loop:count',count