Python学习笔记(4):控制流

Python的控制语句有if、while、for、break、continue。

1. if语句

下面是一个猜数字游戏例子:

# Filename: if.py



number = 10

guess = int(input("Enter a integer:"))



if guess == number:

    print("Congratulations, you guessed it.")

elif guess < number:

    print("No, it is a little higher than that")

else:

    print("No, it is a little lower than that")

注意if语句结尾处包含一个冒号(:),所有控制语句结尾处都需要冒号。Python没有switch语句,您可以用if...elif...else来完成相同功能。

2. while语句

您可能发现上面猜数字游戏,每次都要启动一下才能猜,下面可以用while语句来控制直到你猜中才退出游戏。

# Filename: while.py



number = 10

running = True



while running:

    guess = int(input("Enter a integer:"))



    if guess == number:

        print("Congratulations, you guessed it.")

        running = False

    elif guess < number:

        print("No, it is a little higher than that")

    else:

        print("No, it is a little lower than that")

else:

    print("The game is over.")

其实与while相对的else是多余的,与直接把它的语句放在在while语句块后面的效果相同。

3. for语句

# Filename: for.py



for i in range(1, 5):

    print(i)

else:

    print("The for loop is over.")

输出结果为:

1

2

3

4

The for loop is over.

4. break语句

# Filename: break.py



while True:

    s = input("Enter something:")

    if s == "quit":

        break

    print("Length of the string is", len(s))



print("Done")

5. continue语句

# Filename: continue.py



while True:

    s = input("Enter something:")

    if s == "quit":

        break

    if len(s) < 3:

        continue

    print("Input is of sufficient length")

你可能感兴趣的:(python)