当前位置:首页 / 文章测试 / python学习

python学习

开始打字练习

4. More Control Flow Tools

As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter.

4.1. if Statements

Perhaps the most well-known statement type is the if statement. For example:

x = int input "Please enter an integer: "

Please enter an integer: 42

if x < 0:

x = 0

print Negative changed to zero

elif x == 0:

print Zero

elif x == 1:

print Single

else:

print More

More

There can be zero or more elif parts, and the else part is optional. The keyword elif'is short for ‘else if and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

If you ‘re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful. For more details see match Statements.

4.2. for Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers like in Pascal, or giving the user the ability to define both the iteration step and halting condition as C, Python ‘s for statement iterates over the items of any sequence a list or a string, in the order that they appear in the sequence. For example no pun intended:

声明:以上文章均为用户自行发布,仅供打字交流使用,不代表本站观点,本站不承担任何法律责任,特此声明!如果有侵犯到您的权利,请及时联系我们删除。