Python program structure


Python's program consists of packages, modules (that is, a Python file) and functions. A package is a collection of modules. A module is a collection of functions and classes that deal with a certain type of problem.

Python程序的结构和函数的运用 - Fly - 从C开始

The package must contain at least one __init__.py file, and the content of this file can be empty. Used to identify the current folder as a package.


if statement

>;>;>; x = int(raw_input("Please enter an integer: "))
>;>;>; if x < 0:...         x = 0...         print 'Negative changed to zero'...     elif x == 0:...         print 'Zero'...     elif x == 1:...         print 'Single'...     else:...         print 'More'...


##for statement
>;>;>; # Measure some strings:
...     a = ['cat', 'window', 'defenestrate']
>;>;>; for x in a:
...         print x, len(x)
... 
cat 3
window 6
defenestrate 12


Use The range function implements a counting loop
>;>;>; for i in range(3): print i, 'Pythons'
...
0 Pythons
1 Pythons
2 Pythons


while statement
>;>;>; x = 'spam'
>;>;>; while x:
...          print x,
...          x = x[1:]
...
spam pam am m


break continue pass else loop

    break jump out of the loop

  • continue jump to the top of the loop

  • pass does nothing, just a placeholder empty statement

  • else runs and only runs if the loop exits normally
  • while <条件测试>;:     <语句>;
         if <条件测试>;: break      #现在跳出循环,忽略else
         if <条件测试>;: continue #现在转到循环顶部
    else:    <语句>;                           #如果没有遇到break