Python学习笔记--1

  • Python运行小程序
    •   直接在Pyhon中运行,打印结果
      • >>> 200+300+400
        900
        >>> print('s s s ')
        s s s
    •   在cmd下的命令行中运行.py文件,在.py文件中写上内容
      • C:UsersKobe10Python>python hello.py
        900
  • Python的输入输出
    •   直接输出,类似C,也支持一连串的输入,碰到一个逗号,输出一个空格,逗号省去
      • print('hello,world')//输出

        print('The quick brown fox', 'jumps over', 'the lazy dog')//输出一连串
        print('100 + 200 =', 100 + 200)//输出
        <<<100+200=300
    •   输入
      •   输入名字,利用input函数
        name=input()    输入代码
        print(name)     当然你也可以直接输入变量名去查看变量内容<<<name  显示fuzhiqiang
        结果
        C:UsersKobe10Python>python helloworld.py
        fuzhiqiang    输入
        fuzhiqiang    输出
    •   完整的helloworld
      • name=input('输入你的名字')
        print('hello'.name)
        
        C:UsersKobe10Python>python helloworld.py
        输入名字:fuzhiqiang
        hello fuzhiqiang
  • Python基础
    •   pack的基本例子
      • import os         //导入包
        import requests        //导入包
        print(os.getcwd())           //输出包的位置
        
        r=requests.get("http://www.baidu.com")   通过一个网页来抓取其中的内容,内容是一个url
        
        
        print(r.url)     输出对象的信息
        print(r.encoding)    获取编码的方式
        
        输出结果
        D:WorkworkspacTestPython
        ISO-8859-1
        http://www.baidu.com/
    •   数据类型:字符串和变量
      •   字符串
        • print("helloworld")                         双引号
          print('hello world')                         单引号
          print('''this is the first line              双引号
                  tihs is the second
                  last line''')                
          
          age=3
          name='ahuang'
          print('{0} was {1}years old'.format(name, age))     这里{0}代表的是name,1代表的是age,这里是字符串调用一个format函数来进行传值
          
          print(name +" was "+str(age)+' years old')   +是用来进行字符串的连接的,整型的age必须进行强制转换
      •   变量
        • #identifier命名规则
          #第一个字符必须是字母或者下划线,区分大小写,只包含字母,数字,下划线

    •   数据类型:numerics(int  (包含boolean) ,float,complex)
      •   int    无长度限制      float:对应C的double   in  C      complex复数:实部real和虚部imaginary  用z.real和z.image来取两部分
      • #coding=gbk
        import sys
        from sys import float_info
        a=3
        b=4
        
        c=5.6
        d=2.3
        
        e=complex(c,d)
        f=complex(float(a),float(b))
        
        print('a is type',type(a))
        print('c is type',type(c))
        print('e is type',type(e))
        
        print(a+b)
        print(d/c)
        print(b/a)
        print(b//a)   #双除法  //  约等于整型
        
        print(e)
        print(e+f)
        
        print(sys,float_info)#打印电脑中float的范围值
    •   list
      • #coding=gbk
        from lib2to3.fixer_util import String
        
        print('1
        2')    #
           换行
        #创建一个list
        number_list=[1,3,4,5,6] #list就是用[]表示
        print('number_list is '+str(number_list))#将两个内容连接起来必须类型一致,利用str强制转换
        #字符串类型的list
        string_list=['abc','bbb','adfas']
        print('string_list is '+str(string_list))
        #python还可以创建混合类型的list
        mix_list=['python','java',2,3]
        print('mix_list is '+str(mix_list))
        
        #访问list中的元素,list的下标是从0开始的
        second_num=number_list[1]#访问第二个元素
        third_number=number_list[2]
        fourth_mix=mix_list[3]
        print('second_number :{0} third_number :{1} fourth_mix: {2}'.format(second_num,third_number,fourth_mix ))
        
        #更新list元素
        number_list[1]=30
        print('number_list after updates :'+str(number_list))
        #删除list元素
        del number_list[1]
        print('number_list after del :'+str(number_list))

        print(abcd_list[1])
        print(abcd_list[-1])#倒序查询

    •   元组tuple
      • #coding=gbk
        
        #tuple和list的最大区别:list创建之后可以更改,tuple不能更改
        
        number_tuple=(1,2,3)#tuple 的创建时用(),list是用[]
        print(len((1,2,3)))#长度
        print((1,2,3)+(4,5,6))#元祖的连接
        print(('hello ')*4)#元组的重复
        print(3 in (1,2,3))#判断某个元素是否在元组中
        
        #元组的遍历访问
        abcd_tuple=('a','b','c','d')
        print(abcd_tuple[1])
        print(abcd_tuple[-1])
      • tuple元组和list的对比
        • #coding=gbk
          
          #创建一个元素的元组   必须加上,
          a_tuple=(2,)
          
          #创建一个包含list的tuple
          mixed_tuple=(1,2,['a','c'])
          print('mixed_tuple'+str(mixed_tuple))
          
          #当tuple里面包含list时,可以修改tuple里面的list元素
          mixed_tuple[2][0]='d'
          mixed_tuple[2][1]='b'
          print('mixed_tuple'+str(mixed_tuple))
          
          #tuple是不可变list。一旦创建了一个tuple就不能以任何方式改变他
          #tupel与list相同:
          #定义方式相同,一个是[]一个是(),大部分相同
          #不同tuple不存在的方法
          #不能向tuple增加元素。没有append和extend方法
          #不能删除元素,tuple没有remove或pop,可以删除整个tuple
    •   字典dictionary
      • #coding=gbk
        
        #创建一个字典dictionary  {key:value,key:value}  
        phone_book={'tom':123,'jerry':456,'kim':123}
        
        mixed_dirc={'tom':123,11:22.5}
        #字典的查询方式
        print('tom has phone number,'+str(phone_book['tom']))
        
        #修改value
        phone_book['tom']=999
        print('tom has phone number,'+str(phone_book['tom']))
        
        #增加一个键值对
        phone_book['heal']=888
        print('heal has phone number,'+str(phone_book['heal']))
        
        #删除字典元素和字典本身
        del phone_book['tom']
        print('the book after del,'+str(phone_book))
        
        #词典的清空
        phone_book.clear()
        print('the book after del,'+str(phone_book))
        
        #删除整个词典
        del phone_book
        
        #特性
        #一个词典中不允许重复的键值key出现(类似stl中的map)
        rep_test={'name':'fu','age':13,'name':'f'}
        print('rep_test:'+str(rep_test))#这里结果只会出现一个name,不会有两个
        
        #一个词典中key不能改变   最好用数字,字符串和元组充当键值,不能用list(list可以改变)
        list_dict={('name'):'job','age':3}
    •   函数:全局变量,函数的定义
      • #coding=gbk
        from test import reperf
        from _ast import Str
        
        def say_hi():
            print('hi')
        say_hi()
        say_hi()
        
        def print_sum(a,b):
            c=a+b
            print(c)
        print_sum(3, 4)
        
        def hello_some(str):
            print('hello'+str+':')
        hello_some('python')
        
        def repeat_str(str,times):
            repeat_strs=str*times
            return repeat_strs
        repeat_strings=repeat_str('hello', 5)
        print(repeat_strings)
        
        x=60   #全局变量
        def foo(x):
            print('x is '+str(x))
            x=3
            print('change local x is' +str(x))
            
        foo(x)
        print('x is :'+ str(x))
            
            
  • if语句
    • #coding=gbk
      from unittest.test.testmock.testpatch import something
      
      number=59
      guess=int(input("please input a integer: "))#这里是先打印一句话,然后就输入一个数,并且将这个数强制转换成int类型的数
      # print('guess is :'+str(guess))
      
      if guess==number:
          print('this number is true number')
      elif guess<number:   #elif   这个是缩写,else  if
          print('this number is too small')
      else  :
          print('this number is too big')
          
      print('DONE')
  • for语句
    • #coding=gbk
      
      for i in range(1,10)  : #range (a,b)表示的从a->b的所有值,不包括b
          print(i)  #循环打印i  i是从1到9的所有数
          
      a_list=[1,3,5,7,9]  #遍历list
      for i in a_list:
          print(i)
          
      a_tuple=(1,3,5,7,9)#遍历元组
      for i in a_list:
          print(i)
          
      a_dict={'tom':'1','tony':'2'}#遍历字典   单个值的遍历
      for ele in a_dict:
          print(ele) #输出key ,ele  表示的是键
          print(a_dict[ele])  #打印键对应的值
      
      for key,ele in a_dict.items():#这个是通过键值对同时遍历,item()函数的功能
          print(key,ele)
  • while语句
    • #coding=gbk
      from unittest.test.testmock.testpatch import something
      
      number=59
      guess_flag=False
      
      while guess_flag==False:
          guess=int(input("please input a integer: "))#这里是先打印一句话,然后就输入一个数,并且将这个数强制转换成int类型的数
      # print('guess is :'+str(guess))
      
          if guess==number:
              guess_flag=True
              print('this number is true number')
          
          elif guess<number:   #elif   这个是缩写,else  if
              guess_flag=False
              print('this number is too small')
          else  :
              guess_flag=False
              print('this number is too big')
          
      print('DONE')
    • break和continue的用法和循环用法
      • #coding=gbk
        
        number=59
        num_chance=3
        print('you have 3 chances to guess')
        
        for i in range(1,num_chance+1):  #range 表示1到num_chance+1之间的数,不包括chance+1
            print('chance '+str(i))
            guess=int(input('enter an integer'))
            if guess==number:
                print('this num is true')#猜对跳出
                break
            
            elif guess <number:
                print('this num is too small,you have ', num_chance-i,'chance to guess')
            else:
                print('this num is too big,you have ', num_chance-i,'chance to guess')
        
        number=59   #break 和continue的用法
        while True:
            guess=int(input('enter an integer'))
            if guess==number:
                print('this num is true')#猜对跳出
                break
            
            elif guess <number:
                print('this num is too small,you have ', num_chance-i,'chance to guess')
                continue
            else:
                print('this num is too big,you have ', num_chance-i,'chance to guess')
                continue
    •   continue和pass的区别
      • #coding=gbk
        
          
        a_list=[0,1,2]
        
        print('using continue')
        for j in a_list:
            if not j: #这个表示当J等于0的时候程序直接运行, 当j不等于0的时候,打印j
                continue
            print(j)
          
        b_list=[0,1,2]  
        print('pass using ')
        for i  in b_list:
            if not i :
                pass  #pass表示程序跳过这一样  直接跳到后一个代码执行,直接打印所有的数字
            print(i)
    •   输入输出机制
      •    
        #coding=gbk
        
        #输入输出方式介绍    input
        str_1=input('enter a string')
        str_2=input('enter other string :')
        
        #output the String   str()或者format()
        print('str_1 is : '+str(str_1)+'. str_2 is :'+str(str_2))
        print('str_1 is {} + str_2 is {}'.format(str_1, str_2)) #format中利用{}进行字符的表示,类似于C语言

         文件的输入输出

      • #coding=gbk
        
        some_sence='''
        i love learning python
        because python is fun_tests
        end also easy to use
        '''
        
        #open for 写入文件
        f=open('hello.txt','w')#创建一个文件
        #写入这个文件的内容
        f.write(some_sence)#写出文件内容
        f.close()#关闭文件
        
        #读取文件
        f=open('hello.txt')#打开一个已经存在的文件   读文件不需要模式r
        while True:
            line=f.readline()#行读取   读取一行赋值给line
            if len(line)==0:#当内容为空,跳出循环
                break
            print(line)
        f.close()#打开文件写入文件都需要关闭文件最后

         异常和语法错误

      • #coding=gbk
        # 
        # while True:
        #     try:
        #         x=int(input('please enter a number :'))
        #         break
        #     except ValueError:#这是数据输入异常
        #         print('not valid input,try again...')
        #         
        
        try:
            f=open('myfile.txt')
            line=f.readline()
            i=int(line.strip())#将读取的内容强制转换为int类型
        except OSError as err:   #抛出系统异常,  err=oserror
            #OS error :[Errno 2] No such file or directory: 'myfile.txt'
            print('OS error :{}'.format(err))
        except ValueError:
            #could not convert data to an integer::当文件内容是字符的时候   就是valueerror
            print('could not convert data to an integer')
原文地址:https://www.cnblogs.com/Kobe10/p/5698474.html