Python基础

基本用法

  • 定义:test=’aa’,变量无类型
  • print(‘print something’)
  • input_data = input(‘input message’)
  • if else
    1
    2
    3
    4
    if 3>= 1:
    XXX
    else:
    XXX

Lists and Dictionaries

  • list = [‘a’,’b’,12] -> 可存储任意类型
  • remove and delete of list

    1
    2
    list.remove(index or value);
    del list[index]
  • add item to list

    1
    list.append('xxx')
  • dictionary(key:value)

    1
    slang={'cheerio':'goodbye','yonks':'ages'}
  • add or update dictionary item

    1
    slang['smashing'] = 'terrific'
  • remove dictionary item

    1
    del slang[‘cheerio']
  • get dictionary item

    1
    slang.get(‘cheerio')
  • Comparing lists : my_list==your_list;true->same elements and same order

  • Comparing Dictionaries : my_dict == your_dict;true->same elements order没有要求
  • List of list : 二维数组menus[0][1]
  • dictionary of lists : key value,value是list dic[‘key’][2]

Loops

  • for loop

    1
    2
    for price in prices:
    do somthing(不需要花括号,有缩进)
  • random

    1
    2
    3
    4
    import random
    random.random() ->[0.0,1.0];
    random.choice([1,2,3,4,5,6]) ->a random choice from list;
    random.randint(1,1000) ->random number in this range
  • range(10) -> [0,1,2,3,4,5,6,7,8,9]

  • range(start-num,stop-num,step-num)
  • for dictionary

    1
    2
    for name,price in menu_prices.items():
    print(name,’:$’,price)
  • print(name,’:$’,format(price,’.2f’),sep=‘ ‘)

  • while
    1
    2
    while (x>= 1):
    XXX

Functions

  • 定义

    1
    2
    3
    def average(numbers):
    ...
    return avg
  • main(): best practice in Python

  • scope: 不同方法中同名变量为不同变量,当一个方法调用另一个方法,两个方法中的同名变量属于各自方法不会相互影响值,当这个变量在两个方法外定义,则该变量是全局的,它们同一变量

Files

  • open

    1
    2
    3
    4
    5
    open(‘filename’,’w’)
    # -> 2nd param:
    # w-write(while override the file)
    # a-append(while append data to the file)
    # r-read
  • write & close

    1
    2
    file.write(‘XXX')
    file.close()
  • read

    1
    2
    # open file for r mode
    file_name.read()
  • read line

    1
    2
    3
    file_name.redline()
    for line in opend_file:
    line.strip() # 过滤前后空白
  • show, time = line.split(‘ - ‘)

  • Exceptions
    1
    2
    3
    4
    5
    6
    7
    try:
    XXX
    except:
    XXX

    except ValueError as err:
    print(err)

Modules

  • Installing & Using modules

    1
    pip install requests
  • http request

    1
    2
    3
    import requests
    my_request=requests.get(‘url’)
    menu_list=my_request.json()
  • Creating Modules

    1
    2
    module_name.py -> module_name.py中定义这个module的方法
    import module_name