Introduction to conditions and loops in python

Source: Internet
Author: User
This article mainly introduces conditions and loops in python to obtain any key-value pairs in the dictionary.

>>> x={'a':1,'b':2}>>> key,value=x.popitem()>>> key,value('a', 1)>>> del x[key]Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       del x[key]KeyError: 'a'>>> x{'b': 2}>>> x[key]=value>>> x{'a': 1, 'b': 2}>>> del x[key]
  
 

Incremental assignment

>>> x=2>>> x+=1>>> x*=2>>> x>>> fnord='foo'>>> fnord+='bar'>>> fnord*=2>>> fnord'foobarfoobar'

Conditional execution if statement

>>> name=raw_input('?')?Yq Z>>> if name.endswith('Z'):  \   print 'Hello,Mr.Z'Hello,Mr.Z

Else clause

>>> name=raw_input('what is your name?')what is your name?Yq Z>>> if name.endswith('Z'):    print 'Hello,Mr.Z'else:    print 'Hello,stranger'    Hello,Mr.Z

Elif clause

>>> num=input('Enter a number: ')Enter a number: 5>>> if num>0:    print 'The number is position'elif num<0:    print 'The number is negative'else:    print 'The number is zero'    The number is position

Conditional nested statement

>>> name=raw_input('What is your name?')What is your name?Yq Z>>> if name.endswith('Yq'):    if name.startswith('Z'):        print 'Hello,Yq Z'    elif name.startswith('K'):        print 'Hello,Zyq'    else:        print 'Hello,Yq'else:    print 'Hello,stranger'    Hello,stranger
>>> number=input('Enter a number between 1 and 10:')Enter a number between 1 and 10:6>>> if number<=10 and number>=1:    print 'Great!'else:    print 'Wrong!'    Great!
>>> Age = 10 >>> assert 0> age =-1 >>> assert 0 ", line 1, in
 
  
Assert 0
  

While loop

>>> x=1>>> while x<=100:    print x    x+=1
>>> while not name:    name=raw_input('Please enter your name:')    print 'Hello,%s !' % name    Please enter your name:zyqHello,zyq !

For loop

>>> words=['this','is','an','ex','parrot']>>> for word in words:    print word    thisisanexparrot>>> range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> for i in range(1,8):    print i246

Dictionary loop (iteration)

>>> d={'x':1,'y':2,'z':3}>>> for key in d:    print key,'corresponds to',d[key]    y corresponds to 2x corresponds to 1z corresponds to 3

Parallel iteration

>>> names=['Anne','Beth','George','Damon']  >>> ages=[12,19,18,20]>>> for i in range(len(names)):    print names[i],'is',ages[i],'years old'    Anne is 12 years oldBeth is 19 years oldGeorge is 18 years oldDamon is 20 years old
>>> zip(names,ages)[('Anne', 12), ('Beth', 19), ('George', 18), ('Damon', 20)]>>> for name,age in zip(names,ages):    print name,'is',age,'years old'    Anne is 12 years oldBeth is 19 years oldGeorge is 18 years oldDamon is 20 years old>>> zip(range(5),xrange(100))[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Number iteration

>>> D [1, 2, 4, 4] >>> for x in d: if x = 4: d [d. index (x)] = 6 >>> d [1, 2, 6, 6] >>> S = ['skj', 'kiu', 'olm ', 'piy'] >>>> index = 0 >>> for s1 in S: if 'K' in s1: S [index] = 'hh 'index + = 1 >>> S ['hh', 'hh ', 'olm', 'piy'] >>> for index, s2 in enumerate (S): # The enumerate function provides the index-value pair if 'H' in s2: S [index] = 'df '>>> S ['df ', 'DF', 'olm', 'piy']

Flip, sort iteration

>>> 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'

Break bounce cycle

>>> for n in range(99,0,-1):    m=sqrt(n)    if m==int(m):        print n        break

While True/break

>>> while True:    word=raw_input('Please enter a word:')    if not word:break    print 'The word was '+word    Please enter a word:fThe word was fPlease enter a word:

Loop else statement

>>> for n in range(99,81,-1):    m=sqrt(n)    if m==int(m):        print m        breakelse:    print 'h'    h

List derivation-lightweight loop

>>> [x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> [x*x for x in range(10) if x%3==0][0, 9, 36, 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), (2, 2)]>>> result=[]>>> 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 for g in girls if b[0]==g[0]]['Chris+Clarice', 'Arnold+Alice', 'Bob+Bernice']

Pass

>>> If name = 'nss': print 'Welcome! 'Elif name = 'U': # passelif name = 'Bill ': print 'Access Denied' else: print 'Nobody! '

Del x and y point to a list at the same time, but deleting x does not affect y. Only the name is deleted, not the list itself (value)

>>> x=['Hello','world']>>> y=x>>> y[1]='Python'>>> x['Hello', 'Python']>>> del x>>> y['Hello', 'Python']

Exec

>>> Exec "print 'Hello, world! '"Hello, world! >>> From math import sqrt> exec "sqrt = 1"> sqrt (4) Traceback (most recent call last): File"
   
    
", Line 1, in
    
     
Sqrt (4) TypeError: 'int' object is not callable # Add a dictionary, for namespace >>>> from math import sqrt >>>scope ={}>> exec 'sqrt = 1' in scope >>> sqrt (4) 2.0 >>> scope ['qrt ']
    
   

Note: a namespace is called a scope. You can think of it as a place to save variables, similar to an invisible Dictionary. When executing a value assignment statement such as x = 1, the key x and value 1 are placed in the current namespace, which is generally a global namespace.

>>> len(scope)2>>> scope.keys()['__builtins__', 'sqrt']

Eval evaluate

>>> scope={}>>> scope['x']=2>>> scope['y']=3>>> eval('x*y',scope)>>> scope={}>>> exec 'x=2' in scope>>> eval('x*x',scope)

The above is a detailed description of the conditions and loops in python. For more information, see other related articles in the first PHP community!

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.