Python Basics 5th conditions, loops and other statements

Source: Internet
Author: User
Tags for in range stdin unpack

Python 2.7.5 (default, May, 22:43:36) [MSC v.1500 + bit (Intel)] on Win32#chapter 5 conditions, loops and other statements #5.1 print and import A lot of other information # for very many applications, using the logging module to log logs is more appropriate than the print statement #5.1.1 use a comma output # to see that each number of participants has voluntarily inserted a space character >>> print ' Age: ', 42Age : 42>>> (1, 2, 3) #print的參数并不像我们预期那样构成一个元组 >>> print 1,2,31 2 3>>> print (1, 2, 3) ;>> name= ' Gumby ' >>> salution= ' Mr. ' >>> greeting= ' Hello, ' >>> print greeting, salution , Namehello, Mr Gumby>>> greeting= ' Hello ' >>> print greeting, ', ', salution, Namehello, Mr GUMBY&GT;&G t;> Print greeting + ', ', Salution, Namehello, Mr gumby# assuming a comma at the end, the next statement will be printed on the same line as the previous statement (it only works in the script and is not valid in an interactive Python session) print ' Hello, ', print ' world! ' #输出Hello, world! #5.1.2 Import Statement #import somemodule#from somemodule import somefunction#from somemodule Import Somefunction, anotherfunction, yetanotherfunction#from somemodule Import * #为模块提供别名 >>> import math as Foobar >>> foobar.sqrt (4) 2.0#Provide aliases for functions >>> from math import sqrt as foobar>>> Foobar (4) 2.0# aliases for functions with the same name in different modules #from Module1 import open as O Pen1#from module2 Import Open as open2#5.2 assignment magic #5.2.1 sequence unpacking (sequence unpacking) >>> x, y, z = 1, 2, 3>>> p Rint x, Y, Z1 2 3>>> x, y = y, x>>> print x, y, z2 1 3>>> values = 1,2,3>>> values (1, 2, 3) >>> x,y,z=values>>> x1>>> y2>>> z3>>> scoundrel={' name ': ' Robin ', ' Girlfriend ': ' Marion '}>>> key, value = Scoundrel.popitem () >>> key ' girlfriend ' >>> value '    Marion ' >>> x, y, z = 1,2traceback (most recent call last): File "<pyshell#31>", line 1, in <module> X, y, z = 1,2valueerror:need more than 2 values to unpack>>> X,y,z=1,2,3,4traceback (most recent call last): Fil E "<pyshell#32>", line 1, in <module> X,y,z=1,2,3,4valueerror:too many the values to Unpack#python 3.0 have another solution Package features #a,b,rest*=[1,2,3,4] #rest的结果将会是 [3,4] #5.2.2 Chained assignment #x=y=somefunction# equivalent to #y=somefunction#x=y#5.2.3 increment assignment (augmented assignment) >>> x=2>>> x + = 1>>> x *= 2>>> x6>>> fnord = ' foo ' >>> fnord + = ' Bar ' >>> fnord *= 2>> > Fnord ' foobarfoobar ' #语句块: Indent fun #5.4 conditions and Conditional statements # false None 0 "" () [] {} will be interpreted as false >>> truetrue>>> Fal sefalse>>> true = = 1true# Standard Boolean value is False (0) and True (1) >>> false = = 0true>>> true + false + 4243#bool Functions can be used (similar to list, str, and tuple) to convert other values >>> bool (' I think, therefore I am ') true>>> bool true>>> BOOL (") false>>> bool (0) false>>> bool ([]) false>>> bool (()) false>>> bool ({}) false#5.4.2 condition run and if statement >>> name = Raw_input (' What's your name?

' What is your name? gumby>>> if Name.endswith (' Gumby '): ... print ' Hello, Mr Gumby ' ... Hello, Mr. gumby#5.4.3 Else clause >>> name = Raw_input (' What's your name? ' What is your name?

jon>>> if Name.endswith (' Gumby '): ... print ' Hello, Mr Gumby ' ... else: ... print ' Hello, stranger ' ... Hello, stranger#5.4.4 elif clause >>> num = input (' Enter a number: ') Enter a number:0>>> if num > 0: ... print ' The number is positive ' ... elif num < 0: ... print ' The number is negative ' ... else: ... print ' The Numb Er is zero ' ... The number is zero#5.4.5 nested code block >>> name = Raw_input (' What's your name? ' What is your name? Mrs. gumby>>> if Name.endswith (' Gumby '): ... if Name.startswith (' Mr. '): ... print ' Hello, Mr Gumby ' ... elif name.startswith (' Mrs. '): ... print ' Hello, Mrs Gumby ' ... else: ... print ' Hello, Gumby ' ... else: ... print ' Hello, stranger ' ... Hello, Mrs. gumby# chain comparison operation # When comparing objects, you can use the built-in CMP functions >>> age=10>>> 0<age<100true>>> age=-1 >>> 0<age<100false# equality operator >>> "foo" = = "foo" true>>> "foo" = = "Bar" false>>> "Foo "=" foo "File" <stdin> ", line 1syntaxerror:can ' t assign to literal# identity operator # Avoid using the IS operator for such immutable values as comparable numbers and strings .>> > x=y=[1,2,3]>>> z=[1,2,3]>>> x = = ytrue>>> x = = ztrue>>> x is yTrue>>> x is zfalse>>>>>> x are zfalse>>> x = [1,2,3]>>> y = [2,4]>>> x is not yTrue> >> del x[2]>>> y[1]=1>>> y.reverse () >>> x = ytrue>>> x is yfalse#in: membership operator &G t;>> name = Raw_input (' What's your name? ' What is your name?

jonathan>>> if ' s ' in Name: ... print ' Your name contains the letter ' s '. ' ... else: ... print ' Your name does not contain the "s". ' ... Your name does not contain the letter "s" .>>> "alpha" < "beta" true>>> ' fnord '. lower () = = ' Fnord '. Lowe R () true>>> [up] < [2,1]true>>> [2,[1,4]]<[2,[1,5]]true# boolean operator >>> number = input (' Enter a number between 1 and: ') enter a number between 1 and 10:8>>> if number <=: ... if number ; = 1: ... print ' great! ' ... else: ... print ' wrong! ' ... else: ... print ' wrong! ' ... great!>>> number = input (' Enter a number between 1 and: ') Enter a number between 1 and 10:6>>> if Nu Mber <= and number >= 1: ... print ' great! ' ... else: ... print ' wrong! ' ... great!>>> number = input (' Enter a number between 1 and: ') Enter a number between 1 and 10:11>>> if 1 <= number <=: ... print ' GreAt! ' ... else: ... print ' wrong! ' ... wrong!>>> name = raw_input (' Please enter the Your name: ') or ' <unknown> ' please enter your name:>>> NA Me ' <unknown> ' #短路逻辑和条件表达式 # similar to the ternary operator in C and Java >>> name = ' Jon ' if True Else ' Jack ' >>> name ' Jon ' > >> name = ' Jon ' If False Else ' Jack ' >>> name ' Jack ' #5.4.7 assertion >>> age = 10>>> Assert 0 < A GE < 100>>> age = -1>>> Assert 0 < Age < 100Traceback (most recent call last): File "<stdin > ", Line 1, in <module>assertionerror# conditions can be added with commas and strings to interpret assertions >>> age = -1>>> Assert 0 < Age &lt ; , ' The age must is realistic ' Traceback (most recent call last): File "<stdin>", line 1, in <module>asserti Onerror:the age must is realistic#5.5 loop #5.5.1 while loop >>> x=1>>> while x <=: ... print x ... X +=1...123...100>>> x101>>> name = ">>> While not name: ... name = Raw_input (' Please enter your name: ') ... Please enter your name:please enter your name:please enter your name:jon>>> print ' Hello,%s! '% Namehello, jon! >>> name = ">>> while not name or Name.isspace (): ... name = raw_input (' Please enter your name: '). . Please enter your name:please enter your name:please enter your name:chan>>> print ' Hello,%s! '% Namehello, Cha N!>>> while not Name.strip (): ... name = raw_input (' Please enter your name: ') ...>>> name = ' >&gt ;> while not Name.strip (): ... name = raw_input (' Please enter your name: ') ... Please enter your name:please enter your name:please enter your name:kingston>>> print ' Hello,%s! '% Namehello, kingston! #5.5.2 For Loop >>> words=[' This ', ' was ', ' an ', ' ex ', ' Parrot ']>>> for word in words: ... print word...thisisanexparrot>>> numbers = [0,1,2,3,4,5,6,7,8,9]>>> for number in numbers: ... print number ... 0123456789>>> Range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #假设能使用for循环, try not to use the while loop # when a large sequence needs to be iterated, xrange will be more efficient than range >>> for number in range (1,5) : ..... Print number ... 1234#5.5.3 Loop Traversal dictionary element >>> d={' x ': 1, ' Y ': 2, ' Z ':3}>>> for key in D: ... print key, ' corresponds to ', D[ke Y]...y corresponds to 2x corresponds to 1z corresponds to 3>>> for key, value in D.items (): ... print Kye, ' Co Rresponds to ', value ... Traceback (most recent call last): File "<stdin>", line 2, in <module>nameerror:name ' Kye ' are not defined&gt ;>> for key, value in D.items (): ... print key, ' corresponds to ', value...y corresponds to 2x corresponds to 1z C Orresponds to 3>>> #5.5.4 Some Iteration tools # parallel iterations >>> names = [' Anne ', ' Beth ', ' George ', ' Damon ']>>> ages = [ 102]>>> for in range (len (names)): Syntaxerror:invalid syntax>>> for I in range (len (names) ):p rint names[i], ' is ', ages[i], "year old" Anne is the year of Oldbeth is the year of Oldgeorge is YEar Olddamon is 102 year old>>> for I in range (len (names)):p rint names[i], "is", ages[i], ' years old ' Anne is Y Ears Oldbeth is a years Oldgeorge is a years Olddamon is 102 years old>>> zip (names, ages) [(' Anne ', '), (' Beth ', ('), (' George ', ' + '), (' Damon ', 102)]>>> for name, "Age in Zip" (names, ages):p rint name, ' is ', age, ' years old ' an Ne is a years oldbeth is a years Oldgeorge is a years Olddamon is 102 years old>>> Zip (range (5), xrange (100000 ) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] #在索引上迭代 >>> strings = [' I am xxx ', ' I like losing my face ', ' Say good Bye ']>>> for string in Strings:index = Strings.index (String) # Search for the string in the list of stringsstring S[index]= ' [censored] ' >>> strings[' [censored] ', ' [censored] ', ' [censored] ']>>> strings = [' I am xxx ', ' I like losing my face ', ' Say Goodbye ']>>> for string in strings:if ' xxx ' in Strings:index = Strings.index (String) # Search for the string in The list of stringsstrings[index]= ' [censored] ' >>> strings[' I am xxx ', ' I like losing my face ', ' Say goodbye ']&gt ;>> strings = [' I am xxx ', ' I like losing my face ', ' Say Goodbye ']>>> for string in strings:if ' xxx ' in str Ing:index = Strings.index (String) # Search for the string in the list of stringsstrings[index]= ' [censored] ' >>> &G t;>> string ' Say goodbye ' >>> strings[' [censored] ', ' I like losing my face ', ' Say goodbye ']>>> [' I A M xxx ', ' I like losing my face ', ' Say goodbye ' [' I am xxx ', ' I like losing my face ', ' Say goodbye ']>>> index = 0& Gt;>> for string in strings:if ' xxx ' in string:strings[index]= ' [censored] ' index + = 1syntaxerror:invalid syntax> >> index = 0>>> for string in strings:if ' xxx ' in string:strings[index]= ' [censored] ' Index + = 1>>> Strings[' [censored] ', ' I like the losing my face ', ' Say goodbye ']>>> [' I'm xxx ', ' I like losing my face ', ' Say good Bye ', ' xxx is a sensitive word ' [' I am xxx ', ' I like losing my face ', ' Say goodbye ', ' xxx was a sensitive word ']>>> for index, string in EN Umerate (strings): If ' xxx ' in string:strings[index]= ' [censored] ' >>> strings[' [censored] ', ' I like losing my Face ', ' Say goodbye ']>>> strings = [' I'm xxx ', ' I like losing my face ', ' Say goodbye ', ' xxx is a sensitive word ' ] #enumerate函数能够在提供索引的地方迭代索引-value pair .>>> for index, string in Enumerate (strings): If ' xxx ' in string:strings[index]= ' [censored] ' >>> strings[' [censored] ', ' I like losing my face ', ' Say goodbye ', ' [censored] '] #翻转和排序迭代 >> > Sorted ([4,3,6,8,3]) [3, 3, 4, 6, 8]>>> sorted (' Hello, world! ') [', ', '! ', ', ', ' H ', ' d ', ' e ', ' l ', ' l ', ' l ', ' o ', ' o ', ' R ', ' W ']>>> list (Reversed (' Hello, World ')) [' d ', ' l ', ' R ' , ' O ', ' w ', ' ', ', ', ' o ', ' l ', ' l ', ' e ', ' H ']>>> '. Join (Reversed (' Hello, world! ')) '! Dlrow, Olleh ' #5.5.5 Jump out of the loop #break>>> from math import sqrt>>> to N in range (99, 0,-1); SyntaxError: Invalid syntax>>> for n in range (0,-1): root = sqrt (n) if root = = Int (root):p rint nbreak81# continue# while True/break customary use method >>> Word = ' dummy ' >>> while Word:word = Raw_input (' "Please enter a word: ') # processing Word:print ' The word was ' + wordplease enter a word:firstthe word is firstplease enter a word:secondthe word was secondplease en ter a word:the word is >>> word = raw_input (' Please enter a word: ') "Please enter a word:first>>> whil E Word:print ' The word was ' + Wordword = raw_input (' Please enter a word: ') the word was firstplease enter a Word:secondt He word was secondplease enter a word: >>> when true:word = raw_input (' Please enter a word: ') if not word:break print ' The word was ' + wordplease enter a word:firstthe word is firstplease enter a word:secondthe word was Secondplea Se Enter a word: #5.5.6 Loop in the ELSE clause # Original scheme from math import sqrtbreak_out = falsefor N in range (1): root = sqrt (n) if Ro OT = = Int (root): Break_out = trueprint nbreakif not break_out:print "didn ' t find it!" #结果Didn ' t find it! #改进方案from math import sqrtfor N in range (, Bayi,-1): root = sqrt (n) if root = = Int (root):p rint Nbreakelse :p rint "didn ' t find it!" #结果Didn ' t find it! #列表推导式 (List comprehension)--Lightweight loop >>> [x*x for X in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 8 1] #能够和if子句联合使用 >>> [x*x for x in range] if x 3 = = 0][0, 9,, 81]>>> [(x, Y) for x in range (3) for Y In range (3) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1)]>>> >>> RESULT=[]&G T;>> for x in range (3): For Y in range (3): Result.append ((x, y)) >>> result[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]>>> girls=[' Alice ', ' Bernice ', ' Clarice ']>>> boys=[' Chris ', ' Arnold ' , ' Bob ']>>> [B + ' + ' +g for B in boys-G in girls if b[0] = = g[0]][' Chris+clarice ', ' arnold+alice ', ' Bob+bernice ' ] #更优方案 >>> girls = [' Alice ', ' Bernice ', ' Clarice ']>>> boys = [' Chris ', ' Arnold ', ' Bob ']>>> lettergirls={}>>> for girl in Girls: Lettergirls.setdefault (Girl[0], []). Append (girl) >>> print [+ + ' + ' +g for B in boys for G in lettergirls[b[0]]][' ch Ris+clarice ', ' arnold+alice ', ' bob+bernice ']>>> lettergirls{' a ': [' Alice '], ' C ': [' Clarice '], ' B ': [' Bernice ' ]} #5.73 people pass, Del and exec#5.7.1 nothing happened >>> name = ' Bill Gates ' >>> if name = = ' Ralph auldus melish ': ... print ' welcome! ' ... elif name = = ' Enid ': ... elif name = = ' Bill Gates ': ... print ' Access Denied ' ... Access denied#5.7.2 using del delete >>> scoundrel = {' age ': "First name ': ' Robin ', ' Last name ': ' of Locksley ' >>& Gt Robin = scoundrel>>> scoundrel{' Last name ': ' of the Locksley ', ' First name ': ' Robin ', ' age ': 42}>>> robin{' L AST name ': ' of Locksley ', ' First name ': ' Robin ', ' age ': 42}>>> scoundrel = none>>> scoundrel>>> Print scoundrelnone>>> robin{' last name ': ' OF Locksley ', ' First name ': ' Robin ', ' age ': 42}>>> x = 1>>> y = x>>> x=1>>> del x>&g T;> Xtraceback (most recent): File "<stdin>", line 1, <module>nameerror:name ' x ' are not defi ned>>> x = [' Hello ', ' world ']>>> y = x>>> y[1]= ' python ' >>> x[' Hello ', ' Python ']>& Gt;> del x>>> y[' Hello ', ' Python '] #5.7.3 Run and evaluate strings using EXEC and eval # exec in Python 3.0 is a function instead of a statement >>> exec " print ' Hello, world! ' " Hello, world!>>> from math import sqrt>>> exec "sqrt=1" >>> sqrt (4) Traceback (most recent call L AST): File "<stdin>", line 1, in <module>typeerror: ' int ' object was not callable# namespace, or scope (scope) #能够通过in &L T;scope>, where <scope> is the dictionary that plays the role of placing code string namespaces >>> from math import sqrt>>> scope={}>> > exec ' sqrt = 1 ' in scope>>> sqrt (4) 2.0>>> scope [' sqrt ']1>>> len (scope) 2>>> SCOP E.keys () [' __builtins__ ', ' sqrt ']# eval--evaluation string >>> eval (raw_input ("Enter an arithmetic Express:")] Enter an arithmetic Express:6 + * 242>>> scope={}>>> scope[' x ']=2>>> scope[' y ']=3>>> eval (' x * y ', SCO PE) 6>>> scope = {}>>> exec ' x=2 ' in scope>>> eval (' x*x ', scope) 4>>> #5.8 Summary # The print--print statement can be used to print multiple values separated by commas. Assuming that the statement ends with a comma, subsequent print statements will be printed in the same line # import--can provide an alias # assignment with as to a module or function--through the sequence unpacking and chaining assignment functions, multiple variables can be assigned at once, and the variable can be changed in place by incremental assignment # Block-a block is a way of grouping statements by indentation. Blocks can be used in conditions as well as in loop statements, and can also be used in functions and classes using the # condition--several conditions can be used in tandem with If/elif/else. Another variant is called a conditional expression, such as a if B else c. #断言-The assertion is simply that it is certain that something (Boolean expression) is true and that it can be followed behind it. #循环--can use the Continue statement to skip the other statements in the block and then continue the next iteration, Or use the break statement to jump out of a loop # you can also choose to add an else clause at the end of the loop, and then run the contents of the ELSE clause when the break statement inside the loop is not running. #列表推导式--is an expression that looks like a loop. Through it, you can generate new lists from the old list, Apply functions to elements, filter out unwanted elements, and so on. #pass, Del, exec, and eval statements. The pass statement does nothing and can be used as a placeholder. The DEL statement is used to delete a variable (name), or part of a data structure, but cannot be used to delete a value. # The EXEC statement runs the string in the same way that the Python program runs. The built-in eval function evaluates the expression in the string and returns the result. #5.8.1 The new function in this chapter #chr (n) returns a string of characters represented by the ordinal n (0<=n<=256) #eval (source[, globals[, locals]]) evaluates the string as an expression, and the return value #enumerate produces an int value for the iteration (index, value) to #ord (c) to return a single character string #range ([ Start,] stop[, step]) creates a list of integers #reversed (seq) produces a reverse copy of the value in the SEQ, used for Iteration #sorted (seq[, cmp][, key][, reverse]) to return a list copy of the value sorted in SEQ Xrange ([Start,] stop[, step]) create Xrange objects for iterative #zip (seq1, SEQ2,...) Create a new sequence for parallel iterations


Python Basics 5th conditions, loops and other statements

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.