Python Crash Course

Python Crash Course

List

  1. Create Lists:
    books=["A","B","C"];
  2. Accessing List:
    books[2];//accessing the item where index=2;
  3. Modify:
    books[2] = "D";
  4. Adding:
    books.append("E"); // add one item to the ending.
  5. Insert
    books.insert(3,"F"); //insert "F" to the place where index = 3.
  6. Remove:
    del books[2]; //delete the item where index=2.
    books.pop(); //remove one item from the right And return the item.
    books.pop(2); //remove the item where index=2 from left AND return the item.
    books.remove("B"); //remove the item of B when you did not know the index of "B".
  7. Sort: The original List will change Sort
    books.sort(); // sort from a...z
    books.sort(reverse=True); //sort in reverse alphabet z...a
  8. Sorted: if you want maintain the original List
    books.sorted(); //assignment to new variable and Original List no changed.
  9. Reverse:
    books.reverse();
  10. Length:
    len(books);
  11. Loop Through The List:
for x in books:
  print(x);
  1. Range:
    range(1,5); //a set of number : 1,2,3,4. can been Loop.
  2. List():
    list(range(1,5)); // switch a set number to list . [1,2,3,4].
  3. sum(digits),min(digits),max(digits):
  4. List Comprehensions:
squares = [value**2 for value in range(1,5)];
print(squares);  #[1,4,9,16].
  1. Slice Of List:
    books[0:3]: // Return List Of Index = 0,1,2.
    books[2]: // Return Item Of Index = 2.
    books[:4]: // Starting at Left And return 4 items.
    books[2:]: // Starting From index =2 to Ending.
    books[-2:]: // Starting From the right, return 2 Items.
  2. Copy Of List:
    books_copy = books[:]//RIGHT, The two Lists have no relationship.
    books_copy = books; //WORRY,The two Lists have no relationship.
    For Example:
my_books = ['PHP','Python'];
your_books = my_books;
my_books.append('JavaScript');
your_books.append('Java');
print(my_books);   #['PHP', 'Python', 'JavaScript', 'Java']
print(your_books); #['PHP', 'Python', 'JavaScript', 'Java']
# Don`t Worry about the details in this example for now,
# Basically, if you`re trying to work with a copy of a list,
# REMEMBER copying the list using a slice.

18 .Tuple:

books_tuple = ("PHP","Python","JavaScript");
# 1. A tuple looks just like a list except you use parentheses instead of square brackets.
# 2. Once Define One Tuple, you can not change any Item of Tuple.
# 3. But you can redefine the tuple.
books_tuple = ("PHP","Python"); //RIGHT, can redefine.

19 .split(): To make String to List

names = 'chen jian ma jia li'
print(names.split())   # ['chen', 'jian', 'ma', 'jia', 'li']

If Statements

  1. if...elseif...else...
cars = ["Audi","bMW",'Tokyo']
for car in cars:
    if car == 'Audi':
        print(1)
    elif car =='bMW':
        print(2) 
    else:
        print(3)

2 .Multiple Conditions:

3>1 and 3>2; //TRUE
3>1 or 3>2; //TRUE 

3 .Wether a item In or Not In List:

books = ['PHP','Python']
'HTML' in books #return FALSE.
'HTML' not in books #return TRUE.

if 'HTML' in books:
    print(0)
else:
    print(1)

4 .Whether one list is Empty:

books=[];
if books:
  print("No Empty")
else:
  print("Empty")

Dictionary

# 1. Some Operation Of Dictionary.
alien = {'color':'green', 'points':99}  #new Dictionary
print(alien['color'])    #1.Access Values in a Dictionary, return 'green'.
alien['age'] = 26        #2.Add New key-value in Dictionary.
alien['color'] = 'red'   #3.Modifying values in a dictionary.
del alien['points']      #4.Removing key-value Paris
# 2. Looping Through All Key-Value Paris.
chenjian = {
    'wife':'majiali',
    'Job':'PHPer',
    'age':24
}
for key,value in chenjian.items():
  print(key)
  print(value)

# The Method Of items(), make Dictionary returns a list of key-value
# chenjian.items()  //return dict_items([('wife', 'majiali'), ('age', 24), ('Job', 'PHPer')])

#Job
#PHPer
#age
#24
#wife
#majiali
[Finished in 0.0s]

1 . Looping Through a Dictionary`s Keys in Order:
for key1 in chenjian.key()
2 .set(),Python identi es the unique items in the list and builds a set from those items.

chenjian = {
    'wife':'majiali',
    'Job':'PHPer',
    'Jobbbb':'PHPer'
}
print(set(chenjian))
# {'Jobbbb', 'wife', 'Job'}
# [Finished in 0.0s]

3 .Nesting

Sometimes you’ll want to store a set of dictionaries in a list or a list ofitems as a value in a dictionary.

Chapter 7: User Input And While Loops

1 .input():The input() function pauses your program and waits for the user to entersome text.

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

2 .int():Change to Number.
3 .str():Change to String.
4 .while loops:

num = 1
while num < 5:
    print(num)
    num+=1

Chapter 8: Function

1 .When Use *topping means to tell python to make one empty Tuple namedtopping And Pack whatever values received into this tuple. Can been use for...in... to loop out.

def some(*topping):
    print(topping)
some('A','B','C','D')
some('A','B')

# ('A', 'B', 'C', 'D')
# ('A', 'B')
# [Finished in 0.0s]

2 .When Use **topping means to tell python to make one empty Dictionary namedtopping And Pack whatever values received into this Dictionary. Can been use for...in... to loop out.

def somes(**topping):
    print(topping)
somes(name='chenjian',age=26,birth='AnHui')

# {'age': 26, 'birth': 'AnHui', 'name': 'chenjian'}
# [Finished in 0.0s]

3 .Importing an Entire Module, When Use, need use dot to connect the Module Name and Function Name.

import module_name
module_name.function_name()

4 .importing Specific Functions,*** When Use, No need use dot***.

# import one function.
from module_name import function_name
function_name()

# import 3 functions.
from module_name import function_0, function_1, function_2
function_0()
function_1()
function_2()

# import all function
from module_name import *

5 .Rename of Function in Module Or Module, When the Name is exist in the program Or the Name too long.

# Rename Module
import module_name as new_module_name
new_module_name.function_name()

#Rename The Function Of Module
from module_name import function_name as new_function_name

Chapter 9 : Classes

1 .Define:

class Dog():
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.heigh = '90cm'
    def about_me(self):
        return "My Name Is " + self.name
    def change_hei(self,newvalue):
        self.heigh = newvalue

my_dog = Dog('peter',4)
my_dog.change_hei('200cm')
print(my_dog.heigh)  #'200cm'
print(my_dog.about_me()) #'My Name Is peter'

2 .** Inheritance**:1.super():The super() function is a special function that helps Python make connections between the parent and child class.

class Car():
     def __init__(self, make, model, year):
         self.make = make
         self.model = model
         self.year = year
     def get_descriptive_name(self):
         long_name = str(self.year) + ' ' + self.make + ' ' + self.model
         return long_name.title()
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

# 2016 Tesla Model S
# [Finished in 0.0s]

3 .Importing Classes:

from module_name import Class_Name
OR
from module_name import Class_Name_1, Class_Name_2 

# Importing an Entire Module
import module_name

# Importing All Classes from a Module
from module_name import *

4 .the Python standard library:The Python standard library is a set of modules included with every Pythoninstallation.

Chapter 10: FILES AND EXCEPTIONS

1 .File:
The Contents Of demo.txt is :

      A
 B
C
-----Read-----
with open('file_name') as content_object:
  print(content_object.read())        # Return All Content,Can Use `for...in..` to lopping.
  print(content_object.readline())        #Return The Content Of First Line
  print(content_object.readlines())       #Return All Content, And Store Each lines as Lists `['      A\n', ' B\n', 'C']`


-----Write-----
operation = 'w'   # write mode, It will cover origin content
operation = 'r'    # read mode
operation = 'a'   # append mode, It will append at the end of origin content
operation = 'r+' # read and write mode.
with open('file_name', operation) as content_object:
  content_object.write('New Contest')  

2 .Exceptions

  • special Objects when an error occurs
  • If you write the code to handle the exceptions, when error occur, the program will continue running
  • If you did not write the handle exceptions, The code will stop and show a traceback, which includes a report of the exception that was raised.
try:
    print(2/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
try:
    result = 2/1
except ZeroDivisionError:
    print('You can not divide by Zero')
else:
    print(result)
# Failing Silently--->When error occur, nothing happen
try:
    print(2/0)
except ZeroDivisionError:
    pass

3 .Storing Data By JSON: json.dump(), json.load(),``

import json
data = ['A','B','C','D']
with open('data.json', 'w') as JsonObject:
    json.dump(data, JsonObject)
# data.json ----> ["A", "B", "C", "D"]
import json
with open('data.json') as DataObject:
    print(json.load(DataObject))
# Print ---> ['A', 'B', 'C', 'D']

Chapter 11 : TESTING YOUR CODE, About unit-test module.

Assert Methods Available from the unittest Module,unittest. From TestCase class

Method Use
assertEqual(a, b) Verify that a == b
assertNotEqual(a, b) Verify that a != b
assertTrue(x) Verify that x is True
assertFalse(x) Verify that x is False
assertIn(item, list) Verify that item is in list
assertNotIn(item, list) Verify that item is not in list

1 .Test Function:

# add.py
def add(first,second,third=0):
    return first+second+third
# test_add.py
import unittest
from add import add

class NamesTestCase(unittest.TestCase):
    def test_add(self):
        want_test = add(6,4)
        self.assertEqual(want_test,10)
    def test_3_add(self):
        want_test = add(6,4,2)
        self.assertEqual(want_test,12)
unittest.main()   # tell python to run the test file.

PS: 1. an assert method:Assert methods verify that a result you received matches the result youexpected to receive.

2 .Test Class:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子传睹,更是在濱河造成了極大的恐慌厌均,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)伪很,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)奋单,“玉大人锉试,你說(shuō)我怎么就攤上這事±辣簦” “怎么了呆盖?”我有些...
    開(kāi)封第一講書人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)贷笛。 經(jīng)常有香客問(wèn)我应又,道長(zhǎng),這世上最難降的妖魔是什么乏苦? 我笑而不...
    開(kāi)封第一講書人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任株扛,我火速辦了婚禮尤筐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘洞就。我一直安慰自己盆繁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布旬蟋。 她就那樣靜靜地躺著油昂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪倾贰。 梳的紋絲不亂的頭發(fā)上冕碟,一...
    開(kāi)封第一講書人閱讀 52,246評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音匆浙,去河邊找鬼安寺。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吞彤,可吹牛的內(nèi)容都是我干的我衬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼饰恕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了井仰?” 一聲冷哼從身側(cè)響起埋嵌,我...
    開(kāi)封第一講書人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎俱恶,沒(méi)想到半個(gè)月后雹嗦,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡合是,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年了罪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片聪全。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡泊藕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出难礼,到底是詐尸還是另有隱情娃圆,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布蛾茉,位于F島的核電站讼呢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏谦炬。R本人自食惡果不足惜悦屏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧础爬,春花似錦甫贯、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至失乾,卻和暖如春常熙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碱茁。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工裸卫, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人纽竣。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓墓贿,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蜓氨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子聋袋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容