Python_2(form19)

previous:Python

--------------------------------------------------------------------------------------------

- 19 - My trip to Walmart and Sets

Sets : 1,in curve brace {} ,2 have no duplicate 

groceries = {'beer', 'cereal','milk','apple', 'avacodo', 'beer'}
print(groceries, groceries.__len__())

if 'cereal' in groceries:
    print('We have got milk')
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
{'beer', 'avacodo', 'cereal', 'milk', 'apple'} 5
We have got milk

Process finished with exit code 0

 ----20 - Dictionary ------------------------------------------------------------------------------------------------

a dictionary in python is a Key Value pair.

classmates = {'Tony': "iron man", 'Emma': "pretty girl", 'Charles': "ProfessorX", 'Rogen':"Wolf"}
#print(classmates)
#print(classmates['Tony'])
for x, y in classmates.items():
    print(x+" is "+y)
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
Tony is iron man
Emma is pretty girl
Charles is ProfessorX
Rogen is Wolf

Process finished with exit code 0

----21 - Modules ------------------------------------------------------------------------------------------------

Modules:a set of a bounch of function.

usage of Modules:import module

module:feel.py

feel.py

def tsushi(fish):
    print(fish+" can be used to cook Tsushi")

func1.py

import feel
import random
feel.tsushi("tuna")
x = random.randrange(1, 100)
print(x)
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/func1.py
tuna can be used to cook Tsushi
19

Process finished with exit code 0

 ----22 - Download an Image from the Web ------------------------------------------------------------------------------------------------

IDE: JetBrains PyCharm Community Edition 2017.2 x64:

file-setting - project Name( chose the one you want to use)-project interpreter :

1) on the right ,is   downloaded modules form web

2) + ,install module(downloaded),could select 

3) - ,uninstall  module

use random to generate a random number as a img name

use urllib.request  to download

image will be download,and stored in project folder.

import random
import urllib.request

def download_webImage(url):
    name = random.randrange(1,1000)
    #str(number) convert a number to string
    full_name = str(name) + ".jpg"
    urllib.request.urlretrieve(url, full_name)

download_webImage("https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=220dd86ab48f8c54f7decd7d5b404690/960a304e251f95ca5c948c32c9177f3e660952d4.jpg")

 ----23 - How to Read and Write Files ------------------------------------------------------------------------------------------------

fw = open('stamp.txt', 'w')
fw.write('this syntx well first create a new file named stamp.txt 
')
fw.write('Try write something into a file 
')
fw.close()

fr = open('C:/Users/30478/Desktop/stamp.txt', 'r')
text = fr.read()
print(text)
fr.close()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/main.py
this syntx well first create a new file named stamp.txt 
Try write something into a file 
sky

Process finished with exit code 0

C:Users30478Desktopstamp.txt

this syntx well first create a new file named stamp.txt 
Try write something into a file 
sky

 ----24 - Downloading Files from the Web ------------------------------------------------------------------------------------------------

python目录前加一个r:r是保持字符串原始值的意思,就是说不对其中的符号进行转义。因为windows下的目录字符串中通常有斜杠"",
而斜杠在Python的字符串中有转义的作用。例如: 表示换行如果路径中有 ew就会被转义。加上r就是为了避免这种情况。
from urllib import request

goog_url = "https://query1.finance.yahoo.com/v7/finance/download/GOOG?period1=1500721097&period2=1503399497&interval=1d&events=history&crumb=EoXe3TOhKsy"

def download(csv_url):
    response = request.urlopen(csv_url)
    csv = response.read()
    csv_str = str(csv)
    lines = csv_str.split("\n")
    filename = r"goog.csv"
    fw = open(filename, "w")
    for line in lines:
        fw.write(line+'
')
    fw.close()

download(goog_url)

 ----Tutorial - 25-27 - How to Build a Web Crawler (3/3) -----------------------------------------------------------------------------------------------

import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = "https://www.incnjp.com/forum.php?mod=forumdisplay&fid=591&filter=sortid&sortid=6&searchsort=1&goods_type=5&goods_area=2" 
              "&page=" + str(page)
        print(url)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        #for link in soup.find_all('a', {'class': 'item-name'}):
        for link in soup.find_all('a'):
            href = link.get('href')
            #print(href)
            if href is None:
                break
            print(href[0: 6])
            print("!!!" + href[0: 6] is 'thread')
            #if href[0: 6] is 'thread': is variable the same memory,== value is same
            if href[0: 6] == 'thread':
                print(href[0: 6])
                print("!!!" + href)
                get_single_item_data("https://www.incnjp.com/" + href)
        page += 1

def get_single_item_data(item_url):
    sourse_code = requests.get(item_url)
    plain_text = sourse_code.text
    soup = BeautifulSoup(plain_text)
    for item_name in soup.findAll('span', {'id': 'thread_subject'}):
        print(item_name.string)

trade_spider(1)

 ---- 28 - You are the only Exception ------------------------------------------------------------------------------------------------

def x1():
    tuna = int(input("input a number:
"))
    print(tuna)

def xxx():
    # go loop until get a number input
    while True:
        try:
            number = int(input("input a number:
"))
            print(18/number)
            break
        #excpetion
        except ValueError:
            print("Make sure enter a number")
        except ZeroDivisionError:
            print("Don't pick zero")
        #general exception
        except:
            break
        #try - except - finally(always executed )
        finally:
            print("Input is over.")
xxx()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/testErrorAndExceptoin.py
input a number:
x
Make sure enter a number
Input is over.
input a number:
x
Make sure enter a number
Input is over.
input a number:
0
Don't pick zero
Input is over.
input a number:

7
Make sure enter a number
Input is over.
input a number:
2.5714285714285716
Input is over.

Process finished with exit code 0

 ----29 - Classes and Objects------------------------------------------------------------------------------------------------

class Enemy:
    life = 3
    def attact(self):
        print("It's painful!")
        self.life -= 1

    def checkLife(self):
        if self.life <= 0:
            print('Game Over!')
        else:
            print(str(self.life) + "life left")

#use class by made object  ,ememy1 is a object of ememy class
ememy1 = Enemy()
ememy2 = Enemy()

ememy1.attact()
ememy1.attact()
ememy2.attact()
ememy1.checkLife()
ememy2.checkLife()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
It's painful!
It's painful!
It's painful!
1life left
2life left

Process finished with exit code 0

 ----30 - init ------------------------------------------------------------------------------------------------

class tuna:

    def __init__(self):
        print("Game start!")

    def checkLife(self, si):
        print(si)
#use class by made object
ememy1 = tuna()
ememy1.checkLife("sssss ssss")

class Enemy:
    def __init__(self,x):
        self.energy = x
    def get_energy(self):
        print(self.energy)

json = Enemy(10)
andy = Enemy(90)
json.get_energy()
andy.get_energy()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
Game start!
sssss ssss
10
90

Process finished with exit code 0

  ----31 - Class vs Instance Variables------------------------------------------------------------------------------------------------

class girl:
    gender = "girl"
    def __init__(self, name):
        self.name = name

ammy = girl("ammy")
anna = girl("anna")
#gender is a class variable,name is a instance variable
print(ammy.name + " is a " + ammy.gender)
print(anna.name + " is a " + anna.gender)
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/classAndObject.py
ammy is a girl
anna is a girl

Process finished with exit code 0

  ----32 - Inheritance------------------------------------------------------------------------------------------------

class Parent():
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")
class Child(Parent):
    def print_first_name(self):
        print("Charly")
#overwrite
    def print_middle_name(self):
        print("Blue")

charly = Child()
charly.print_first_name()
charly.print_middle_name()
charly.print_last_name()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/parent.py
Charly
Blue
Robert

Process finished with exit code 0

 inherit a class  from other  python file

parent.py

class Parent:
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")
import parent
class Child(parent.Parent):
    def print_first_name(self):
        print("Charly")
#overwrite
    def print_middle_name(self):
        print("Blue")

charly = Child()
charly.print_first_name()
charly.print_middle_name()
charly.print_last_name()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/children.py
Charly
Blue
Robert

Process finished with exit code 0

  ----33 - Multiple Inheritance------------------------------------------------------------------------------------------

 parent.py

class Parent():
    def print_last_name(self):
        print("Robert")
    def print_middle_name(self):
        print("alean")

class Study():
    def object1(self):
        print("I am good at math")

children.py

import parent

#pass :in class need a line of code ,but not want do anything,just write pass,fix the syntxerror
class Child(parent.Parent, parent.Study):
    pass
charly = Child()

charly.print_middle_name()
charly.print_last_name()
charly.object1()

console

C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/children.py
alean
Robert
I am good at math

Process finished with exit code 0

  ----34 - threading-----------------------------------------------------------------------------------------------

import threading
class Clcthread(threading.Thread):
    #if we don't want to use variable just put  a '_' over there
    def run(self):
        for _ in range(10):
            print('Loop for 10 times' + threading.current_thread().getName())

x = Clcthread(name="Run thread 1")
y = Clcthread(name="Run thread 2")
x.start()
y.start()
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/threadingtest.py
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 1
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2
Loop for 10 timesRun thread 2

Process finished with exit code 0

  ----38 - Unpack List or Tuples------------------------------------------------------------------------------------------------

 Tuples 数组

package =['December 25', '2017', '2000']
date, year, price = package
print(date)

#python cookbook

def drop_first_last(grades):
    first, *middle, last = grades
    avg = sum(middle)/len(middle)
    print(len(middle), "students", avg,  "on avg score")

drop_first_last([65, 76, 88, 91, 98, 100])

 first, *middle, last = sorted(grades) it drops minimum and maximum values.

C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/Unpack.py
December 25
4 students 88.25 on avg score

Process finished with exit code 0

 ----Python Programming Tutorial - 40 - Lamdba -----------------------------

#lambda: small function without name.
answer = lambda x: x*7
print(answer(5))
C:Users30478AppDataLocalProgramsPythonPython36python.exe C:/Users/30478/PycharmProjects/YouTubeTutorial/lambdatest.py
35

Process finished with exit code 0
原文地址:https://www.cnblogs.com/charles999/p/7397961.html