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:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,504评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,434评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,089评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,378评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,472评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,506评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,519评论 3 413
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,292评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,738评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,022评论 2 329
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,194评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,873评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,536评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,162评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,413评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,075评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,080评论 2 352

推荐阅读更多精彩内容