Basic knowledge of python syntax

When developing the beautiful beauty picture station, the collection used python

4 spaces are recommended for python indentation

 

if loop

if else

if expression

    statement(s)

if 1<2:

    print "hello"

elif 'a':

    print "world"

else:

    print "END"

Run in this format, if the condition is true, run the following program, if not, do not execute else

example:

#!/usr/bin/python

a = int(raw_input("please input a number:"))

if a >= 90:

    print 'A'

elif a >= 70:

    print 'B'

elif a >= 60:

    print 'C'

else:

    print 'D'

print 'This is you score!'

 

while loop

while loop is used in conditional loop

Example 1

#!/usr/bin/python

x = ''

while x != 'q':

    print 'hello'

    x = raw_input("please input :")

    if not x:

        break

    if x == 'quit'

        continue

    print 'continue'

else:

    print 'world'

 

Use while loop to iterate through files

Example 2

fd = open('/work/python/1.txt')

while True:

    line = fd.readline()

    if not line:

        break

    print line,

fd.close()

 

The for loop is used in a loop with a number of times

iterate over the list

Example 1

#!/usr/bin/python

for i in range(10):

    if i % 2 ==0:

        print i,

Example 2: List rewriting

#!/usr/bin/python

print [i for i in range(10) if i % 2 == 0]

Example 3: List rewriting

#!/usr/bin/python

for z in [i for i in range(10) if i % 2 == 0]:

    print z

iterate over the dictionary

dic1 = {'a':100, 'b':100, 'c':100, 'd':100}

Example 1

for k in dic1:

    print k

Example 2

for k in dic1:

    print k dic1[k]

Example 3

for k in dic1:

#, to remove newlines

    print "%s-->%s" % (k, dic1[k]), 

Example 4

#Use iteritems() and a for loop to iterate over the values ​​in the dictionary

for k, v in dic1.iteritems():

    print k, v

Example 5

#Use for loop to write multiplication formula

for i in xrange(1,10):

    for k in xrange(1,i+1):

        print "%s X %s = %s" % (i, k, i*k),

    print

The else of the for loop exits, and the else content will be executed after the for loop ends.

Example 6

Several syntax usages of #for loop

import sys

import time

for i in xrange(10):

    if i == 1:

        continue

    elif i == 3:

        pass

    elif i == 5:

       break

    elif i == 7:

        sys.exit()

else:

    print i

    time.sleep(1)

print "2"

Example 7 Using a for loop to traverse the contents of a file

#!/usr/bin/python

fd = open('/work/python/2.txt')

for line in fd:

    print line,

 

The enumerate() method means enumeration and enumeration in the dictionary

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326523035&siteId=291194637