Python basic learning notes (6)

Source: Internet
Author: User

 

I'm tired of learning this. The previous data structures seem pretty good, but I still cannot use them to do anything practical.

 

Basic statement usage

 

Output with commas

 
>>>Print 'Age:', 25Age:25

If you want to output both text and variable values without using string formatting, this feature is very useful:

>>> Name ='Chongshi'>>> Salutation ='Mr'>>> Greeting ='Hello.'>>>PrintGreeting, salutation, namehello. Mr chongshi

 

 

Module import function

When importing functions from a module, you can use

Import somemodule

Or

Form somemodule immport somefunction

Or

From somemodule import somefunction. anotherfunction. yetanotherfunction

Or

From somemodule import *

The last version only determines that you want to import all functions from the specified module.

If both modules haveOpenFunction, you can use the function as follows:

Module. Open (...)

Module. Open (...)

Of course, there is another option: you can addAsClause.

>>>ImportMath as foobar#Provide aliases for the entire module>>> Foobar. SQRT (4)2.0 >>>FromMathImportSQRT as foobar#Provide aliases for Functions>>> Foobar (4)2.0

 

Assignment Statement

Sequential unpacking

 
>>> X, y, z = 1, 2, 3 >>>PrintX, Y, Z1 2 3> X, Y =Y, X>>>PrintX, Y, Z2 1 3

any key in the dictionary can be obtained or deleted. - value pairs. You can use popitem Party

 scoundrel = { '  name   ':  '  Robin   ', '   girlfriend   ':  '  Marion   ' }>> key, value =  scoundrel. popitem ()   key   '  name   '>>  value   '  Robin   ' 

Chained assignment

Chained assignment is a shortcut to assign the same value to multiple variables.

 
>>> X = y = 42#Same effect:>>> Y = 42 >>> x =Y>>>X42

Assignment

 
>>> X = 2 >>> x + = 1#(X = x + 1)>>> X * = 2#(X = x * 2)>>>X6

 

 

Control statement

IfStatement:

Name = raw_input ('  What is your name?  '  )  If Name. endswith ( '  Chongshi  '  ):  Print   '  Hello. Mr. chongshi  '  #  Input >>> What  Is Your name? Chongshi #  Input errors here will have no results becauseProgramNot robust  #  Output Hello. Mr. chongshi

 

ElseClause

Name = raw_input ( '  What is your name?  '  )  If Name. endswith ( '  Chongshi  ' ):  Print   '  Hello. Mr. chongshi  '  Else  :  Print   '  Hello, strager  '  #  Input >>> What  Is Your name? HH # Input and error  #  Output Hello, strager

 

ElifClause

It isElse if"

Num = input ( '  Enter a numer:  '  )  If Num> 0:  Print   ' The numer is positive  '  Elif Num < 0:  Print   '  The number is negative  '  Else  :  Print   '  The nuber is zero  '  #  Input >>>Enter a numer: -1 #  Output The number Is Negative

 

Nesting

Next let's take a look.IfNested example (PythonLine feed is represented by indentation)

Name = raw_input ( '  What is your name?  '  )  If Name. endswith ('  Zhangsan  '  ):  If Name. startswith ( '  Mr.  '  ):  Print   '  Hello. Mr. zhangsan  '      Elif Name. startswith ( '  Mrs.  ' ):  Print   '  Hello. MRS. zhangsan  '      Else  :  Print   '  Hello. zhangsan  '  Else  :  Print   '  Hello. Stranger  ' 

If the input is"Mr. zhangsan"Output the firstPrintInputMRS. zhangshan, Outputs the secondPrintIf you enter"Zhangsan",Output the thirdPrintIf the input is another name, the output is the last result (Hello. Stranger)

 

Assertions

if you need to make sure that a certain condition in the program is true for the program to work properly, assert you can set checkpoints in a program.

>>> Age = 10 >>>Assert0 <age <100> age =-1>Assert0 <age <100,'The age must be realistic'Traceback (most recent call last): File"<Pyshell #8>", Line 1,In<Module>Assert0 <age <100,'The age must be realistic'Assertionerror: The age must be realistic

 

 

Loop statement

Print1To100Number (WhileLoop)

 
X = 1WhileX <= 100:PrintX+ = 1#Output1234..100

Let's look at the example below (WhileTo ensure the input of username words in one cycle:

 name =  ''  while   not   Name: name  = raw_input ( '  Please enter your name:   ' )   PR Int   '  hello. % s!   ' %  name  #  input >>>  Please enter your name: huhu  #  output  hello. huhu! 

Print1To100Number (ForLoop)

 
ForNumberInRange (1,101):PrintNumber#Output1234..100

RatioWhileThe cycle is more concise, but based on our previous experience in learning other languages,WhileIs easier to understand.

 

A simpleForStatement to cycle all keys of the dictionary:

D = { '  X  ' : 1, '  Y  ' : 2, '  Z  ' : 3 }  For Key In  D: Print Key, '  Corresponds  '  , D [Key]  #  Output >>> Y corresponds 2 X corresponds 1 Z corresponds 3

 

BreakStatement

Break ends a loop, assume that 100 the maximum number of workers is less than 100 iterations 0 , the step size is -1

FromMathImportSQRTForNInRange (99,0,-1): Root=SQRT (N)IfRoot =INT (Root ):PrintNBreak#Output>>> 81

 

ContinueStatement

ContinueEnd the current iteration and "jump" to the next round of loop execution.

 While True: S = Raw_input ( '  Enter something:  '  )  If S = '  Quit  '  :  Break      If Len (s) <3 :  Continue  Print   ' Input is of sufficient length  '  #  Input >>> Enter something: huzhiheng  #  The input length is greater than 3. Prompt message Input Is  Of sufficient lengthenter something: Ha  #  The input length is less than 3, and re-input is required. Enter something: Hah #  The input length is equal to 3. The prompt message is displayed. Input Is Of sufficient lengthenter something: Quit  #  The input content is equal to quit, and the result is 

 

 

 

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.