Python 2017.07.19 python web crawler

Source: Internet
Author: User

1.if Else statement: either

If judgment condition 1:

EXECUTE Statement 1

Elif Judgment Condition 2:

EXECUTE Statement 2

Elif Judgment Condition 3:

EXECUTE Statement 3

Else

EXECUTE Statement 4

Write a testiframainder7.py familiarize yourself with the IF statement:

#!usr/bin/env Python
#-*-Coding:utf-8-*-


def isevennum (num):
If num%7==0:
Print (U "%d can be divisible by 7"%num)
Else
Print (U "%d cannot be divisible by 7"%num)

If __name__== ' __main__ ':
Numstr=raw_input ("Please enter an integer:")
Try
Num=int (NUMSTR)
Except ValueError:
Print (U "wrong input, requires an integer")
Exit ()

Isevennum (num)


The results of the implementation are as follows:

2. Limited Loop---for:

For Var in Sequence:

EXECUTE statement

Write a testforgauss.py to familiarize yourself with the FOR Loop statement:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

def cumulative (num):
Sum=0
For I in Xrange (1,num+1):
Sum+=i
return sum

def main ():
While True:
Print (U "========================")
Print (U "Enter exit Exit program")
Str_num=raw_input ("Cumulative from 1 to:")
If str_num== ' exit ':
Break
Try
sum=cumulative (int (str_num))
Except ValueError:
Print (U "only enter a number unless exit input exit")
Continue
Print (U "Cumulative total from 1 to%d is%d"% (int (str_num), sum))

if __name__ = = ' __main__ ':
Main ()


The results of the implementation are as follows:

Looking closely at the expression for the for loop, sequence is a sequence that shows that the For loop is not just for loops in the form of numbers, such as the ability to put a file in a list as a sequence, and then manipulate the file

3. Infinite loop--while: As long as a condition is not met, the loop continues until the condition is met:

While Boolean expression:

EXECUTE statement

Write a testwhilesimulatelogin.py simulated Linux terminal login:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

Import Getpass

Class Fakelogin (object):
def __init__ (self):
Self.name= ' King '
self.password= ' Haha,no pw '
Self.banner= ' hello,you have login system '
Self.run ()

def run (self):
"" "Imitation Linux Terminal login Window" "
Print (U "Sorry, only one user King")
Print (U "secretly tell you that the password is 6 x 8 Kohm")
While True:
Print (U "login:king")
Pw=getpass.getpass ("Password:")

If pw = = ' 88888888 ':
Print (U "%s"%self.banner)
Print (U "Exit program")
Exit ()
Else
If Len (PW) >12:
Print (u "password length should be less than 12")
Continue
Elif Len (PW) <6:
Print (u "password length greater than 6")
Continue
Else
Print (U "Unfortunately, the password is wrong. Keep guessing!! ")
Continue
if __name__ = = ' __main__ ':
F1=fakelogin ()

failed to run at first: Getpass function does not work

Workaround: Do not run on Pycharm and run at Terminal:

4. Interrupt loop--continue,break:continue and break statements can only be used in loops, only for loops;

The Continue function is to start from the beginning of the continue statement to the end of the loop statement, and all the loop statements are not executed, starting again from the next loop.

The break statement functions as an exit loop that ends the loop

Write a random guessing game, familiar with the continue and break statements:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

Import Random

Class Guessnum (object):
"" "This class is used to guess the random number" ""
def __init__ (self):
Print (U "randomly generates a random number of 0-100")
Self.num=random.randint (0,101)
Self.guess ()

def guess (self):
I=0
While True:
Print (U "Guess this random number, 0-100")
Strnum=raw_input ("Enter the number you want to guess:")
I+=1
Try
Print ("******************************")
if int (strnum) <self.num:
Print (U "The number you guessed is too small")
Continue
elif Int (strnum) >self.num:
Print (U "you guessed too big")
Continue
Else
Print (U "you guessed right")
Print (U "You have guessed%d times"%i)
Break
Except ValueError:
Print (U "can only enter numbers, continue to guess!! ")
Continue
Print (U "If there is no continue or break, it will show this, do not believe to try")


if __name__ = = ' __main__ ':
Gn=guessnum ()


The results of the implementation are as follows:

5. Exception Handling---Tyr except: Use try to test for statements that might encounter an exception, except to handle possible exceptions

Try

Statement

Except [Exception,[data ...]:

Do something

Except [Exception,[data ...]:

Do something

Except [Exception,[data ...]:

Do something

Because the same statement may have different exceptions, it will also give a different solution, write a testtryinput.py familiar with the exception handling it:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

Class Tryinput (object):
def __init__ (self):
self.len=10
Self.numlist=self.createlist ()
Self.getnum ()

def createlist (self):
Print (U "creates a list of numbers with a length of%d"%self.len)
Numl=[]
While Len (NUML) <10:
N=raw_input ("Enter an integer:")
Try
Num=int (N)
Except ValueError:
Print (U "input error, required to enter an integer")
Continue
Numl.append (num)
Print (U "s current list is:")
Print (NUML)
Return NUML

def getnum (self):
Print (U "current list is:")
Print (self.numlist)
Instr=none
While instr!= ' EXIT ':
Print (U "Enter exit Exit program")
Instr=raw_input ("Input list subscript [ -10,9]:")
Try
Index=int (INSTR)
Num=self.numlist[index]
Print (the value of "%d" in the "list" is%d "% (index,num))
Except ValueError:
Print (U "input error, list subscript is an integer")
Continue
Except Indexerror:
Print (U "subscript too large, access list out of range")
Continue

if __name__ = = ' __main__ ':
Ti=tryinput ()

The results of the implementation are as follows:

6. Importing Module---Import: a program written in front of it can be used as a module to import the current program , take its essence to the use of its dross, code reusability is terrible, and Python can also be c,c++ according to demand, Java and other programs as modules, arbitrary access.

#同时导入多个模块

Import module[,module2[,......... Modulen]]

#导入模块中的某个函数, class, variable

From ModName import name[,name2[,.......... Namen]]

#导入某个模块中所有

From ModName Import *

Write a module yourself and then import: testimportcolorprint.py:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

Import Sys

Class Colorprint (object):
def __init__ (self,color,msg):
Self.color = Color
self.msg = Msg
Self.cprint (SELF.COLOR,SELF.MSG)

def cprint (self,color,msg):
colors={' black ': ' \033[1;30;47m ', ' Red ': ' \033[1;31;47m ', ' green ': ' \033[1;32;47m ', ' Yellow ': ' \033[1;33;47m ', ' Blue ': ' \033[1;34;47m ', ' White ': ' \033[1;37;47m '}
#注意这里 [] There is no "]" is the right
If Color not in Colors.keys ():
Print (U "input color temporarily not, according to the system default configured color printing")
Else
Print (u "Input color valid, start color printing")
Print (U "%s"%colors[color])
Print (msg)
Print (U "\033[0m")

if __name__ = = ' __main__ ':
Cp=colorprint (Sys.argv[1],sys.argv[2])

must be executed at the terminal with the following results:

Import the Testimportcolorprint module to other programs using:

#!usr/bin/env Python
#-*-Coding:utf-8-*-

From Testimportcolorprint import Colorprint

if __name__ = = ' __main__ ':
P_black=colorprint (' black ', ' I'm black print ')
P_black=colorprint (' Red ', ' I'm red print ')
P_black=colorprint (' green ', ' I'm green print ')

The execution results are as follows (not performed at the terminal):

The prerequisite for importing a Python program as a module is that the two programs are in the same directory, or the path of the modular program is added to the Python system path

Python 2017.07.19 python web crawler

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.