Python学习

来源:互联网 发布:手机数据分析公交 编辑:程序博客网 时间:2024/05/29 18:44
一、输出print "hello world"退出Python解释器quit(),exit(),ctrl+D二、新建Python文件[badou@master python_test]$ touch 1.py#!/usr/bin/python 指定目录,告诉操作系统执行这个脚本时,调用/usr/bin下的Python解释器#!/usr/bin/env python 防止操作系统用户没有将Python装在默认路径,会先到env设置里查找Python的安装路径,再调用对应路径下的解释器[root@master python_test]# vim 1.py    #!/usr/bin/pythonprint "hello world"[root@master python_test]# python 1.py hello world三Python语法1、输出字符串print "hello world"name='zhangsan'<!--定义变量-->print "your name is %s" %(name)print "your name is %s" %("zhangsan")print "your name is" , name2、整数print "he is %d years old" %(14)3、浮点数print "his height is %f m" %(1.82)4、指定小数位的浮点数print "his height is %.2f m" %(1.82)5、指定占位符右对齐print "name:%10s Age:%8d height:%8.2f" %("lisi",25,1.83)6、指定占位符左对齐print "name:%-10s age:%-8d height:%-8.2f" %("lisi",25,1.83)7、科学计数法format(0.0015,'.2e')     四、函数因为函数有返回值,如果不加return的话,会出现nonedef print_your_name(name):        print "his name is ", nameprint print_your_name("1")print print_your_name("2")输出his name is  1Nonehis name is  2Nonedef print_your_name(name):        print "his name is ", name        return ("%s,is a good man" %name)print print_your_name("1")print print_your_name("2")输出his name is  11,is a good manhis name is  22,is a good manhello world                     五、数据结构hashmap,array,setpython 中数据结构会变化hashmap ->dict->{}array ->list->[]set ->set->set()用法#dictcolor={"red":0.2,"green":0.2}print colorprint color["red"]#listcolor_list=["red","blue"]print color_listprint color_list[1]#set同Javaseta_set = set()a_set.add("111")a_set.add("222")a_set.add("111")print a_set六、条件#ifa=1if a>0:  print 'a gt 0'elif a==0: print 'a eq 0'else: print 'a lt 0'#fora_list =[]a_list.append('11')a_list.append('33')a_list.append('22')for value in a_list:   print valueb_dict={}b_dict['aa']=1b_dict['bb']=2b_dict['cc']=3for value in b_dict:  print valuefor key,value in b_dict.items():  print key+" "+str(value)c_set =set()c_set.add('a')c_set.add('b')c_set.add('c')for value in c_set:  print valuesum=0for value in range(1,11):  sum+=value  print value  print sum#whilecnt=2while cnt>0:  print 'aaa'  cnt -=1#print duali=1while i<10:  i+=1  if i%2>0:    continue  print i七、字符串#Stringstr ='ABCDEF'print len(str)print str[2:5]print str.lower()八、异常#try...catchtry:  a=6  b=a/0except Exception,e:  print Exception,":",etry:  print '1111'  fh=open('testfile','r')  print '2222'except IOError,e:  print '3333:',eelse:  print '4444'  fh.close()九、导包#import moduleimport mathprint math.pow(2,3)print round(4.9)import randomitems =[1,2,3,4,5,6]random.shuffle(items)print itemsa=random.randint(0,3)print a//随机取三个s_list = random.sample('abcdefg',3)print s_list

原创粉丝点击