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

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:

主站蜘蛛池模板: 法库县| 苍山县| 东光县| 阳春市| 佛冈县| 宿松县| 项城市| 樟树市| 平南县| 鹤山市| 镇远县| 安塞县| 印江| 通辽市| 镇宁| 武胜县| 常宁市| 宿州市| 张家川| 漯河市| 阜南县| 安康市| 九台市| 上蔡县| 扎囊县| 汾阳市| 临桂县| 富源县| 彰化县| 灌云县| 凤山县| 岫岩| 阜宁县| 扎赉特旗| 剑阁县| 若尔盖县| 丰原市| 天水市| 大兴区| 津南区| 巴彦县|