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

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:

主站蜘蛛池模板: 兴安盟| 大港区| 广宁县| 石台县| 高阳县| 千阳县| 嘉鱼县| 大宁县| 木里| 重庆市| 三门峡市| 娄烦县| 会同县| 宁陕县| 乐清市| 苍溪县| 濉溪县| 特克斯县| 崇仁县| 巴中市| 元氏县| 伊川县| 宽城| 洪泽县| 沈丘县| 商水县| 屏东县| 三河市| 湘潭市| 梧州市| 潮州市| 锦屏县| 合阳县| 韩城市| 韶关市| 新昌县| 乌拉特后旗| 福安市| 永春县| 鞍山市| 根河市|