官术网_书友最值得收藏!

Flow control and iteration

Python programs consist of a sequence of statements. The interpreter executes each statement in order until there are no more statements. This is true if both files run as the main program as well as files that are loaded via import. All statements, including variable assignment, function definitions, class definitions, and module imports, have equal status. There are no special statements that have higher priority than any other and every statement can be placed anywhere in a program. There are two main ways of controlling the flow of program execution, conditional statements and loops.

The ifelse, and elif statements control the conditional execution of statements. The general format is a series of if and elif statements followed by a final else statement:

    x='one' 
if x==0:
print('False')
elif x==1:
print('True')
else: print('Something else')
#prints 'Something else'

Note the use of the == operator to test for the same values. This returns true if the values are equal; it returns false otherwise. Note also that setting x to a string will return something else rather than generate a type error as may happen in languages that are not dynamically typed. Dynamically typed languages such as Python allow flexible assignment of objects with different types.

The other way of controlling program flow is with loops. They are created using the while or for statements, for example:

主站蜘蛛池模板: 昌都县| 兴国县| 时尚| 乳山市| 张家界市| 小金县| 德江县| 阳江市| 鱼台县| 神木县| 阜阳市| 阿坝县| 通化市| 扶绥县| 衡阳市| 南澳县| 罗平县| 丰台区| 黎平县| 苏尼特右旗| 商河县| 四平市| 庆阳市| 灌南县| 西充县| 兴国县| 北海市| 镇远县| 娱乐| 宁乡县| 仁布县| 河西区| 包头市| 崇左市| 炎陵县| 璧山县| 河源市| 米易县| 新野县| 永善县| 晋宁县|