Python Basic Learning Notes (vi)

Source: Internet
Author: User

It is very impatient to learn this, the data structure of the front looks very good, but still can not use them to do anything practical.

More usage of basic statements

Use a comma output

>>> print ' Age: ', 25age:25

This feature is useful if you want to output text and variable values at the same time, but do not want to use string formatting:

>>> name = ' Chongshi ' >>> salutation = ' Mr ' >>> greeting = ' Hello. ' >>> print Greeting,salutation,namehello. Mr Chongshi

Module Import function

When importing functions from a module, you can use the

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 the features from the given module into.

If two modules have an open function, you can use a function like this:

Module.open (...)

Module.open (...)

Of course there are other options: You can add an as clause at the end of the statement and give the name after the clause.

>>> Import Math as Foobar   #为整个模块提供别名 >>> foobar.sqrt (4) 2.0>>> from math import sqrt as Foob Ar  #为函数提供别名 >>> foobar (4) 2.0

Assignment statements

Sequence Unpacking

>>> x, y, z = 1,2,3>>> print x,y,z1 2 3>>> x,y=y,x>>> print X,Y,Z2 1 3

You can get or delete any key-value pairs in the dictionary, and you can use the Popitem side

>>> scoundrel ={' name ': ' Robin ', ' Girlfriend ': ' marion '}>>> key,value = Scoundrel.popitem () >> > key ' name ' >>> value ' Robin '

Chained assignment

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

>>> x = y = 42# effect:>>> y = 42>>> x = y>>> x42

Add Value

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

Control statements

If statement:

Name = Raw_input (' What's your name? ') If Name.endswith (' Chongshi '):    print ' Hello.mr.chongshi ' #输入 >>> What is your Name?chongshi  # The input error here will have no result, because the program is not robust # output Hello.mr.chongshi

ELSE clause

Name = Raw_input (' What's your name? ') If Name.endswith (' Chongshi '):    print ' Hello.mr.chongshi ' else:print ' Hello,strager ' #输入 >>> what is your NAME?HH  #这里输和错误 # output Hello,strager

elif clause

It is shorthand for "else if"

num = input (' Enter a numer: ') if num > 0:    print ' The Numer is positive ' Elif num < 0:    print ' The number is neg Ative ' Else:print ' The nuber is zero ' #输入 >>> enter a numer:-1# output the number is negative

Nesting

Let's take a look at the If nesting example (Python is indented to wrap the line)

Name = Raw_input (' What's 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 contents of the first print, input Mrs.zhangshan, output the contents of the second print, if you enter "Zhangsan", output the content of the third print, if you enter a different name, The output will be the last result (Hello.stranger)

Assertion

An Assert statement can set a checkpoint in a program if it is necessary to ensure that a condition in the program must be true for the program to function properly.

>>> age = 10>>> Assert 0 < Age < 100>>> age = -1>>> Assert 0 < Age < 100, ' The age must is realistic ' Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>
   
    assert 0 < Age <, ' The must is realistic ' assertionerror:the age must being realistic
   

Looping statements

Print a number from 1 to 100 (while loop)

x= 1while x <=:    print x x + = # output 1234. 100

Then look at the following example (while loop), with a loop to ensure the input of the user's name:

Name = "While not" name:    name = raw_input (' Please enter your name: ') print ' hello.%s! '%name# input >>> please ente R your name:huhu# output hello.huhu!

Print a number from 1 to 100 (for loop)

For number in range (1,101): print number# output 1234 ... 100

is more concise than the while loop, but the while example is easier to understand based on our previous experience of learning other languages.

A simple for statement can loop all the keys of a dictionary:

D = {' X ': 1, ' Y ': 2, ' z ': 3}for key in D:print key, ' corresponds to ', D[key] #输出 >>> y corresponds-2x corresponds to 1z corresponds to 3

Break statement

Break is used to end the loop, assuming that the maximum square number within 100 is found, then the program can iterate from 100 to 0 with a step of 1

From math import sqrtfor N in range (99,0,-1):    root = sqrt (n)    if root = = Int (root):        print n        break# output >> ;> 81

Continue statements

Continue ends the current iteration, "jumps" 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 ' #输入 >>> enter Something:huzhiheng  #输入长度大于3, prompting information input is of sufficient Lengthenter something:ha        #输入长度小于3, required to re-enter Something:hah       #输入长度等于3, prompting information input is of sufficient lengthenter Something:quit       #输入内容等于quit, results

Python Basic Learning Notes (vi)

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.