python学习笔记(四)之分支和循环

python中比较操作符有:

  >  >=  <  <=  ==  !=

这些操作符返回True或False

 1 >>> 1 < 3
 2 True
 3 >>> 1 > 3
 4 False
 5 >>> 1 == 1
 6 True
 7 >>> 1 != 1
 8 False
 9 >>> 1 == 2
10 False
11 >>> 1 != 2
12 True
View Code

 分支语法

if 条件:

  循环体

else:

  循环体

1 number = 5
2 guess = int(input("please input a number:"))
3 if guess == number:
4     print("T")
5 else:
6     print("F")
View Code

多次分支语法

if 条件:

  循环体

elif 条件:

  循环体

else:

  循环体

 1 scores = int(input("please input your score:"))
 2 
 3 if scores >= 90:
 4     print("A")
 5 elif scores >= 80:
 6     print("B")
 7 elif scores >= 70:
 8     print("C")
 9 elif scores >= 60:
10     print("D")
11 else:
12     print("E")
View Code

while循环语法

while 条件:

  循环体

1 i = 0
2 while i < 10:
3     print(i)
4     i += 1
View Code

一个例子:

 1 import random
 2 secret = random.randint(1,10)
 3 print("----------you are welcome----------")
 4 
 5 for i in range(3):
 6     guess = int(input("please input a number:"))
 7 
 8     if guess == secret:
 9         print("right")
10         break
11     elif guess > secret:
12         print("much big")
13     else:
14         print("much small")
15 else:
16     print("the number is ", secret)
17 
18 print("Over")    
View Code

 条件表达式

  语法:x if 条件 else y

1 x, y = 4, 5
2 small = x if x < y else y
3 print(small)
View Code

断言assert

  assert关键字被成为“断言”,当这个关键字后边的条件为假的时候程序会自动崩溃并抛出AssertionError的异常。例如:

1 >>> assert 3 > 4
2 Traceback (most recent call last):
3   File "<stdin>", line 1, in <module>
4 AssertionError
View Code

  一般来说,可以用Ta在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert关键字就非常有用了。

for循环语法

for 目标 in 表达式:

  循环体

Python中for循环非常智能和强大,可以自动调用可迭代对象的迭代器,返回下一个迭代对象。表达式是一个可迭代对象,如列表,元组,字符串,字典等。

 1 >>> favourite = "python"
 2 >>> for i in favourite:
 3 ...     print(i)
 4 ... 
 5 p
 6 y
 7 t
 8 h
 9 o
10 n
11 >>> number = ['one', 'two', 'three', 'four']
12 >>> for i in number:
13 ...     print(i)
14 ... 
15 one
16 two
17 three
18 four
View Code

range()

语法:range([start, ]stop[,step = 1])

生成从start开始,步长为step,到stop参数的值结束的数字序列。通常搭配for循环使用。

1 >>> list(range(10))
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 >>> list(range(5,10))
4 [5, 6, 7, 8, 9]
5 >>> list(range(5,10,2))
6 [5, 7, 9]
View Code

break 和 continue

  break:跳出循环

  continue:结束本次循环

原文地址:https://www.cnblogs.com/ZGreMount/p/7757920.html