美文网首页
Python基础教程一

Python基础教程一

作者: 起个名字真难999 | 来源:发表于2017-10-28 14:45 被阅读19次

    [toc]

    1.起步

    2.变量和简单数据类型

    1.变量

    message = "hello world python"
    print(message)
    

    2.命名

    1.命名与使用
    2.使用变量时避免命名错误

    3.字符串

    1.使用方法修改字符串的大小写
    name = 'ada lovelace'
    print(name.title())
    
    输出得到:
    Ada Lovelace
    

    title()以首字母大写的方式显示每个单词,即每个单词的首字母都改为大写

    print(name.upper())
    print(name.lower())
    
    得到:
    ADA LOVELACE
    ada lovelace
    
    
    2.拼接字符串

    用“+” 来拼接字符串

    “\t,\n”来空格与换行

    3.删除空白
    1. rstrip() 删除末尾的空白
    2. lstrip() 删除头部的空白
    3. strip() 删除字符串两端的空白
    msg = ' python '
    print(msg.rstrip())
    print(msg.lstrip())
    print(msg.strip())
    
    得到
     python
    python 
    python
    
    
    4.使用字符串避免语法错误

    单引号与单引号一对,
    双引号与双引号是一对,
    一般要成对出现,且。

    4.使用函数str()避免类型错误

    age = 23
    msg = "Happy "+str(age)+" rd Birthday"  # 必须使用str()否则python识别不了
    
    
    print(msg)
    

    3.列表简介

    1.列表是什么

    bicycles = ['trek','cannondale','redline','specialized']
    
    print(bicycles)
    
    1.访问列表元素
    print(bicycles[0])
    
    得到
    
    trek
    
    
    2.索引从0而不是1开始

    2.修改,添加和删除元素

    1.修改列表元素
    names =['zhangsan','lisi','wangwu','zhaoliu']
    print(names)
    
    names[0] = 'zhangsanfeng'
    print(names)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu']
    
    
    2.列表中添加元素
    • 在列表末尾添加元素

      names.append('qianda')
      print(names)
      得到:
      
      ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu', 'qianda']
      
      
      cars = []
      cars.append('honda')
      cars.append('honda2')
      cars.append('honda3')
      print(cars)
      
      得到
      
      ['honda', 'honda2', 'honda3']
      
      
    • 在列表中插入元素

        cars.insert(0,'honda0')
        print(cars)
      
        得到:
        ['honda0', 'honda', 'honda2', 'honda3']
      
      
    3.2.3列表中删除元素
    • 使用del语句删除元素
       nicks =['zhangsan','lisi','wangwu','zhaoliu']
       del nicks[0]
       print(nicks)
    
       得到:
       ['lisi', 'wangwu', 'zhaoliu']
    
    
    • 使用方法pop()删除元素
      有时候要将元素从列表中删除,并接着使用它的值,方法pop()可删除列表末尾的元素,并让你能够接着使用它。
       nicks =['zhangsan','lisi','wangwu','zhaoliu']
       print(nicks)
    
       poped_nicks = nicks.pop();
       print(nicks)
       print(poped_nicks)
       
       得到:
       ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
       ['zhangsan', 'lisi', 'wangwu']
       zhaoliu
    
    
    • 弹出列表中任何位置处的元素
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    poped_nicks = nicks.pop(0)
    print('The first name is '+poped_nicks.title()+'.')
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    The first name is Zhangsan.
    
    

    如果不确定使用del语句还是pop()方法,有一个简单的标准:如果你要从列表中删除的一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()

    • 根据值删除元素
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    nicks.remove('lisi')
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhangsan', 'wangwu', 'zhaoliu']
    
    

    3.组织列表

    1.使用方法sort()对列表进行永久性排序--按字母排序
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    nicks.sort();
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['lisi', 'wangwu', 'zhangsan', 'zhaoliu']
    
    还可以按字母顺序相反的顺序排列列表元素,只需要向sort()方法传递参数reverse = True
    
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    nicks.sort(reverse = True);
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
    
    
    2.使用方法sorted()对列表进行临时排序--按字母排序
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    print(sorted(nicks))
    
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['lisi', 'wangwu', 'zhangsan', 'zhaoliu']
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    
    还可以相反顺序临时排序
    
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    print(sorted(nicks,reverse = True))
    
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    
    
    3.倒着打印列表,按元素反转列表排序
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks)
    
    nicks.reverse()
    print(nicks)
    
    得到:
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['zhaoliu', 'wangwu', 'lisi', 'zhangsan']
    
    
    
    方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复原来的排列顺序,只需要再次调用reverse()
    
    4.确定列表的长度
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(len(nicks))
    
    得到:4
    
    
    

    4.使用列表时避免索引错误

    注意元素的个数,另外访问最后一个元素时,都可使用索引-1,倒数第2个可以使用索引-2,依次类推

    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks[-1])
    
    得到:
    zhaoliu
    
    

    4.操作列表

    1.遍历整个列表

    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    for nick in nicks:
        print(nick)
        
    得到:
    zhangsan
    lisi
    wangwu
    zhaoliu
    
    for cat in cats:
    for dog in dogs
    for item in list_of_items
    
    使用单数和复数的式名称可帮助判断代码段处理的是单个列表元素还是整个列表。
    
    
    1.在for循坏环中执行更多的操作

    在每条记录中打印一条消息。

    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
        print(nick.title()+", welcome to china")
        
    得到:
    Zhangsan, welcome to china
    Lisi, welcome to china
    Wangwu, welcome to china
    Zhaoliu, welcome to china   
    
    

    执行多行代码,这里需要注意一下,接下来的代码都是需要缩进的

    
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
        print(nick.title()+", welcome to china")
        print("hello,python")
        
    得到:
    Zhangsan, welcome to china
    hello,python
    Lisi, welcome to china
    hello,python
    Wangwu, welcome to china
    hello,python
    Zhaoliu, welcome to china
    hello,python
    
    
    2.在for循环结束后执行一些操作
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
        print(nick.title()+", welcome to china")
        print("hello,python")
    
    print("print all message and print finish!")
    
    得到:
    Zhangsan, welcome to china
    hello,python
    Lisi, welcome to china
    hello,python
    Wangwu, welcome to china
    hello,python
    Zhaoliu, welcome to china
    hello,python
    print all message and print finish!
    
    可以看到最后一条要打印的消息只打印一次,最后一条没有缩进,因此只打印一次
    
    
    

    2.避免缩进错误

    • 忘记缩进
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
    print(nick.title()+", welcome to china")
    
    得到:
      File "/Users/liuking/Documents/python/python_learn/test.py", line 22
        print(nick.title()+", welcome to china")
            ^
    IndentationError: expected an indented block
    
    • 忘记缩进额外的代码行
    其实想打印两行的消息,结果只打印了一行,print("hello,python") 忘记缩进了,结果只是最后一条打印了这条消息
    
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
        print(nick.title()+", welcome to china")
    print("hello,python")
    
    得到:
    Zhangsan, welcome to china
    Lisi, welcome to china
    Wangwu, welcome to china
    Zhaoliu, welcome to china
    hello,python
    
    • 不必要的缩进
    message = 'hello python world'
        print(message)
    
    得到:
      File "/Users/liuking/Documents/python/python_learn/test.py", line 20
        print(message)
        ^
    IndentationError: unexpected indent
    
    
    • 循环后不必要的缩进
    第三个打印的消息没有缩进,结果每一行都被打印出来了。
    
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    for nick in nicks:
        print(nick.title()+", welcome to china")
        print("hello,python")
    
        print("print all message and print finish!")
        
    得到:
    Zhangsan, welcome to china
    hello,python
    print all message and print finish!
    Lisi, welcome to china
    hello,python
    print all message and print finish!
    Wangwu, welcome to china
    hello,python
    print all message and print finish!
    Zhaoliu, welcome to china
    hello,python
    print all message and print finish!
    
    
    
    • 遗漏了冒号
      漏掉了冒号,python不知道程序意欲何为。

    3.创建数值列表

    1.使用函数range()

    函数range()让你能够轻松地生成一系列的数字。

    for value in range(1,5):
        print(value)
    
    得到:
    1
    2
    3
    4
    
    只打印了1〜4 函数range()从指定的第一个值开始数,并在到达你指定的你第二个值后停止。
    
    2.使用range()创建数字列表

    要创建数字列表,可使用函数list()将range()的结果直接转换为列表,如果将range()作为list()的参数,输出将为一个数字列表。

    numbers = list(range(1,6))
    print(numbers)
    
    得到:
    [1, 2, 3, 4, 5]
    

    把10个整数的平方加入列表中,并打印出来

    squares = []
    numbers = range(1,11)
    for number in numbers:
        squares.append(number**2)
    
    print(squares)
    
    得到:
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    3.对数字列表执行简单的统计计算

    最小值,最大值,求和

    digits = [1,2,3,4,5,6,7,8,9,0]
    print(min(digits))
    print(max(digits))
    print(sum(digits))
    
    得到:
    0
    9
    45
    
    

    4.使用列表的一部分

    1.切片
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    print(nicks[0:3])  前一个数从0开始,后一个数从1开始数
    print(nicks[2:3])  从2开始,截止到第4个元素
    print(nicks[2:])   从2开始,没有指定截止数据,直接数到末尾
    print(nicks[:2])   没有指定开始,默认从0开始
    print(nicks[:])    没有指定开始,也没有指定结束的,直接复制整个列表
    print(nicks[-2:])  从倒数第2个开始
    
    
    得到:
    ['zhangsan', 'lisi', 'wangwu']
    ['wangwu']
    ['wangwu', 'zhaoliu']
    ['zhangsan', 'lisi']
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    ['wangwu', 'zhaoliu']
    
    2.遍历切片
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    for nick in nicks[0:3]:
        print(nick.title())
        
    得到:
    Zhangsan
    Lisi
    Wangwu
    
    
    3.复制列表---需要特别注意了
    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    nicks_copy = nicks[:]
    print("original nicks")
    print(nicks)
    
    print("copy nicks")
    print(nicks_copy)
    
    得到:
    original nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    copy nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
    
    

    为了核实我们确实有两个列表,
    我们可以再添加一下东西

    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    nicks_copy = nicks[:]
    
    nicks.append('zhangsanfeng')
    nicks_copy.append('zhangwuji')
    
    
    print("original nicks")
    print(nicks)
    
    print("copy nicks")
    print(nicks_copy)
    
    得到:
    original nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng']
    copy nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangwuji']
    
    

    如果我们只是简单的nicks赋值给nicks_copy就不能得到两个列表

    nicks =['zhangsan','lisi','wangwu','zhaoliu']
    
    nicks_copy = nicks;
    
    nicks.append('zhangsanfeng')
    nicks_copy.append('zhangwuji')
    
    
    print("original nicks")
    print(nicks)
    
    print("copy nicks")
    print(nicks_copy)
    
    得到:
    original nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']
    copy nicks
    ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']
    
    因为nicks和nicks_copy都指向同一个列表,所以都打印出了相同的列表,这里要特别注意
    
    
    

    5.元组

    python将不能修改的值称为不可变的,而不可变的列表被称为元组。有的时候需要创建一系列不可修改的元素,元组可以满足这种需要。

    • 定义元组

    元组看起来像列表,但使用圆括号而不是方括号来标识,定义元组后,就可以使用索引来访问其元素。

    point = (200,50,300,90)
    print(point[0])
    print(point[1])
    print(point[2])
    print(point[-1])
    
    得到:
    200
    50
    300
    90
    
    
    • 遍历元组中的所有值
    points = (200,50,300,90)
    for point in points:
        print(point)
        
    得到:
    200
    50
    300
    90
    
    
    • 修改元组变量
      虽然不能修改元组的元素,但可以给存储元组的变量赋值。重新定义整个元组。
    print("original data")
    points = (200,50,300,90)
    for point in points:
        print(point)
    
    print("\nmodify data")
    points = (1,2,3,4)
    for point in points:
        print(point)
        
    得到:
    original data
    200
    50
    300
    90
    
    modify data
    1
    2
    3
    4
    
    

    5.if语句

    1.条件测试

    • 检查相等用‘==’
    • 检查不相等用‘!=’
    • 检查多个条件
      1. 使用and检查多个条件:要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一;如果每个测试都通过了,整个表达式为就为True,如果至少有一个测试没有通过,则整个表达式为False
      2. 使用or检查多个条件:至少有一个条件满足,就能通过整修测试,仅当两个测试都没有通过时,使用or的表达式才为False
    • 检查特定值是否包含在列表中,使用关键字in
    request_topping = ['mushrooms','onions','pineapple']
    print('mushrooms' in request_topping)
    print('mush' in request_topping)
    
    得到:
    True
    False
    
    
    • 检查特定值是否不包含在列表中,使用关键字not in
    request_topping = ['mushrooms','onions','pineapple']
    print('mushrooms' not in request_topping)
    print('mush' not in request_topping)
    
    得到:
    False
    True
    
    

    2.if语句 主要注意的是代码缩进,

    • if
    • if-else
    • if-elif-else
    • 多个elif代码块
    • 省略else代码块

    6.字典

    1.字典的简单使用

    在Python中字典是一系列的键值对,每一个键都与一个值相关联,与键相关联的值可以是数字,字符串,列表,乃至字典。

    • 访问字典的值
    alien_0 = {'color':'green','point':5}
    print(alien_0['color'])
    
    得到:
    green
    
    
    • 添加键值对
    alien_0 = {'color':'green','point':5}
    print(alien_0)
    
    alien_0['x_point'] = 250
    alien_0['y_point'] = 100
    print(alien_0)
    
    得到:
    {'color': 'green', 'point': 5}
    {'color': 'green', 'y_point': 100, 'x_point': 250, 'point': 5}
    
    
    • 先创建一个空字典
    alien_0 = {}
    alien_0['x_point'] = 250
    alien_0['y_point'] = 100
    print(alien_0)
    
    得到:
    {'y_point': 100, 'x_point': 250}
    
    
    • 修改字典中的值
    alien_0 = {}
    alien_0['y_point'] = 100
    print(alien_0)
    
    alien_0['y_point'] = 1000
    print(alien_0)
    
    得到:
    {'y_point': 100}
    {'y_point': 1000}
    
    
    • 删除-键值对
    alien_0 = {'color':'green','point':5}
    print(alien_0)
    
    del alien_0['point']
    print(alien_0)
    
    得到:
    {'color': 'green', 'point': 5}
    {'color': 'green'}
    
    

    2.遍历字典

    • 遍历所有的键值对
    values = {'1':'one','2':'two','3':'three','4':'four'}
    for value in values.items():
        print(value)
    
    for key,value in values.items():
        print("\nkey:"+key)
        print("value:"+value)
        
    
    得到:
    ('1', 'one')
    ('3', 'three')
    ('2', 'two')
    ('4', 'four')
    
    key:1
    value:one
    
    key:3
    value:three
    
    key:2
    value:two
    
    key:4
    value:four
    
    
    1.遍历字典中所有的键
    values = {'1':'one','2':'two','3':'three','4':'four'}
    
    for value in values.keys():
        print(value)
        
    得到:
    1
    3
    2
    4
    
    
    2.遍历字典中所有的值
    values = {'1':'one','2':'two','3':'three','4':'four'}
    
    for value in values.values():
        print(value)
        
    得到:
    one
    three
    two
    four
    
    
    3.按顺序遍历字典中所有键
    values = {'first':'one','second':'two','three':'three'}
    
    for value in sorted(values.keys()):
        print(value)
        
    得到:
    first
    second
    three
    
    

    7.用户输入和while循环

    1.函数input()工作原理

    注意:用户输入只能从终端运行,不能直接通过sublime来运行。

    os x系统从终端运行python程序:

    1. liukingdeMacBook-Pro:~ liuking$ cd Desktop
    2. liukingdeMacBook-Pro:Desktop liuking$ ls
    3. input.py
    4. python3 input.py
    5. 输出得到结果
    6. 
    
    

    首先:写一段python 文件

    name = input("Please enter your name: ")
    print("Hello,"+name)
    
    在终端中运行得到:
    
    liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
    Please enter your name: kobe bryant
    Hello,kobe bryant
    liukingdeMacBook-Pro:Desktop liuking$ 
    
    

    多行输入展示:

    多行展示可以用+=来追加字符串。

    prompt = "If you tell us who you are,we can personalize the message you see."
    prompt += "\nWhat is your first name?"
    name = input(prompt)
    
    print("\n Hello,"+name)
    
    得到:
    liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
    If you tell us who you are,we can personalize the message you see.
    What is your first name?zhang
    
     Hello,zhang
    liukingdeMacBook-Pro:Desktop liuking$ 
    
    

    注意以下几点:

    1. 使用int()来获取数值输入
    height = input("How tall are you ,in inches? ")
    height = int(height)
    
    if height >= 36:
        print("\n you're tall enought to ride")
    else:
        print("\nyou'll be able to ride when you're a little older.")
        
    得到:
    liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
    How tall are you ,in inches? 43
    
     you're tall enought to ride
    liukingdeMacBook-Pro:Desktop liuking$ 
    
    注意这里使用了int()把数据类型转换了一下,
    
    
    1. 求模运算符

    求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少

    >>> 5%3
    2
    >>> 6%2
    0
    >>> 
    
    

    2.Whil循环

    1.使用While循环
    number = input("遍历你输入的数据:")
    number = int(number)
    begin = int(0)
    while begin <= number:
        print(begin)
        begin += 1;
        
    得到:
    liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
    遍历你输入的数据:10
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    
    2.让用户选择何时退出
    promt = "\nTell me something and I will repeat it back to you:"
    promt += "\n Enter 'quit'  to end the program."
    message = ""
    while message != 'quit':
        message = input(promt)
        if message != 'quit':
            print(message)
        
    终端运行得到:
    liukingdeMacBook-Pro:DeskTop liuking$ python3 input.py
    
    Tell me something and I will repeat it back to you:
     Enter 'quit'  to end the program: NBA
    NBA
    
    Tell me something and I will repeat it back to you:
     Enter 'quit'  to end the program: CBA
    CBA
    
    Tell me something and I will repeat it back to you:
     Enter 'quit'  to end the program: quit
    liukingdeMacBook-Pro:DeskTop liuking$ 
    
    

    其它使用方式:

    • 使用boolean 标记来判断
    • 使用break退出循环
    • 使用continue

    3.使用While循环来处理列表和字典

    1.在列表之间移动元素
    unconfirmed_users = ['one','two','three']
    confirmed_users = []
    
    while unconfirmed_users:
        current_user = unconfirmed_users.pop()
        print("verifying User:"+current_user)
        confirmed_users.append(current_user)
    
    # 显示所有已验证用户
    print("\n The following users have been confirmed: ")
    for user in confirmed_users:
        print(user.title())
        
        
    得到:
    verifying User:three
    verifying User:two
    verifying User:one
    
     The following users have been confirmed: 
    Three
    Two
    One
    
    
    2.使用用户输入来填充字典
    
    responses = {}
    
    # 设置一个标志,指出调查是否继续
    polling_active = True
    
    while polling_active:
        # 提示输入被调查者的名字和回答
        name = input("\nWhat is your name?")
        response = input("Which mountain would you like to climb someday?")
    
        # 将答案存在字典中
        responses[name] = response
    
        # 看看是否还有人要参加调查
        repeat = input("would you like to let another person respond?(Y/N)")
        if repeat == 'N':
            polling_active = False
    
    # 调查结果,显示结果
    print("\n----Poll results-----")
    for name,response in responses.items():
        print(name+" would like to climb "+ response+".")
        
    在终端运行得到:
    
    liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
    
    What is your name?Kobe
    Which mountain would you like to climb someday?武当山    
    would you like to let another person respond?(Y/N)Y
    
    What is your name?姚明
    Which mountain would you like to climb someday?灵山   
    would you like to let another person respond?(Y/N)N
    
    ----Poll results-----
    Kobe would like to climb 武当山.
    姚明 would like to climb 灵山.
    liukingdeMacBook-Pro:Desktop liuking$ 
    
    
    

    完。

    相关文章

      网友评论

          本文标题:Python基础教程一

          本文链接:https://www.haomeiwen.com/subject/sqkspxtx.html