Python自学笔记六——循环

在上一个例子中,使用了ifelse判断猜年龄的方法,但程序在执行一次后即终止。如果需要用户不断猜,直到猜中为止,则必须引入循环。

●while循环

首先用while循环对程序进行修改,实现不断猜直到猜中为止。将上一个代码修改为:

1 |  age_of_somebody = 28
2 |  while True:
3 |     guess_age = int(input("guess the age:"))
4 |     if age_of_somebody == guess_age:
5 |        print("You got it!")
6 |        break
7 |     elif age_of_somebody > guess_age:
8 |        print("Think bigger....")
9 |     else:
10|        print("Think smaller....")

需注意的几点:

1.2行语句 while True:,True必须要大写,且后面要跟“:”;

2.在进行修改或写循环语句时,特别注意要思考清楚哪些语句是包含在循环体内的内的,应该在哪个点break断开;

3.if/else一样,要注意行首的缩进,同级语句要始终保持一致。

那么,如果要求用户输入有限次数,例如,只允许用户猜3次年龄,猜不对则结束程序,应该如何修改代码呢?

1 |  age_of_somebody = 28
2 |  count = 0
3 |  while True:
4 |     if count == 3:
5 |        break
6 |     guess_age = int(input("guess the age:"))
7 |     if age_of_somebody == guess_age:
8 |        print("You got it!")
9 |        break
10|     elif age_of_somebody > guess_age:
11|        print("Think bigger....")
12|     else:
13|        print("Think smaller....")
14|     count +=1

如以上代码,在代码中添加计数器count,赋予初值0,并在每次循环结束前用count+=1(等同于count=count+1)给计数器+1,直到第四次时跳出循环,结束程序。要注意count添加的位置,保持count+=1与循环语句同级。

另外一种写法是:将

3 |  while True:

4 |     if count == 3:

5 |        break

修改为:

While count < 3: 效果完全相同。


●for循环

python中如何使用for循环?先用最简单例子熟悉:

1 |  for i in range(10):

2 |      print ("i:",i)

以上即是一个完整的for循环,其功能是循环打印从09i的值,应该注意:此处i没有提前声明和赋予初值,因为是简写;i换成其他变量,如abx,仍可运行。用for循环,三次猜某人年龄的代码可简写为:

1 |  age_of_somebody = 28

2 |  for i in range(3)

3 |     guess_age = int(input("guess the age:"))

4 |     if age_of_somebody == guess_age:

5 |        print("You got it!")

6 |        break

7 |     elif age_of_somebody > guess_age:

8 |        print("Think bigger....")

9 |     else:

10|        print("Think smaller....")

代码:

1 |for i in range(1,10,3):

2 |    print ("i:",i)

打印结果为1,4,7。由此可见,for i in range(I,Y,B)的结构中,I代表i的初始值,Y代表范围,B代表步长。所以 range10)实际上市range0,10,1)的简写,I默认为0B默认为1

●countinue

countine表示结束本次循环,继续跳入下次循环。注意对比breakbreak是跳出整个循环)。

猜你喜欢

转载自www.cnblogs.com/red1d0t/p/9186780.html