Python Crash Course

Python Crash Course_第1张图片
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:

你可能感兴趣的:(Python Crash Course)