1.if条件语句
1.1 简单的if语句:单分支if语句
>>> age = 18
>>> if age >=18:
... print("You are an adult!")
...
You are an adult!
1.2 if-else语句:双分支if语句
>>> age = 17
>>> if age >= 18:
... print("You are an adult!")
... else:
... print("Sorry, you are too young!")
...
Sorry, you are too young!
双分支if-else语句类似于三目运算符。如果条件(紧跟在if后面)为真,表达式的结果为提供的第一个值,否则为第二个值(else之后的值)。
>>> age = 17
>>> print("You are an adult ") if age >= 18 else print("Sorry, you are too young!")
Sorry, you are too young!
1.3 if-elif-else语句:多分支if语句
要检查多个条件,可使用elif。elif是else if的缩写,由一个if子句和一个elseelse子句组成,也就是包含条件的else子句。elif语句可以有多个,但else语句至多有一个。
>>> grade = int(input("Please input a grade:"))
Please input a grade:88
>>> if 0 <= grade < 60:
... print("Fail")
... elif 60 <= grade < 75:
... print("Pass")
... elif 75 <= grade < 85:
... print("Well")
... elif 85 <= grade < 100:
... print("Excellent")
... else:
... print("Invalid input!!")
...
Excellent
1.4 if语句嵌套
例如查看16是否能被2和4整除
>>> num = 16
>>> if num % 2 == 0:
... if num % 4 == 0:
... print("{} can divisible by 2 and 4".format(num))
... else:
... print("{} can divisible by 2,not by 4".format(num))
... else:
... print("{} cann't divisible by 2")
...
16 can divisible by 2 and 4
2. 循环语句
2.1 while循环
while循环不断地运行,直到指定地条件不满足为止。
注意,在Python中,没有do…while循环。
while 条件:
语句
>>> current_number = 1
>>> while current_number <= 5:
... print(current_number)
... current_number += 1
...
1
2
3
4
5
(1)while循环使用else语句
while 条件:
代码块1
else:
代码块2
while循环使用else之后语句,只有在循环正常结束时才会执行。若while循环在执行过程中中断了,也即是说执行了break语句,这里的else语句就不会被执行。
i = 0
while i < 5:
print(i)
i += 1
else:
print("循环完毕")
ycy@ubuntu18:~$ python3 while_else.py
0
1
2
3
4
循环完毕
2.2 for循环
for 变量 in 可迭代对象:
代码块1
else:
代码块2
用for循环实现为可迭代对象中每个元素执行代码块。
>>> numbers = ['1', '2', '3', '4']
>>> for i in numbers:
... print(i)
...
1
2
3
4
(1)range()函数
Python内置了一个创建分为的函数range()。范围类似于切片。其包含起始位置,但不包含结束位置。
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(2, 5)
[2, 3, 4]
>>> range(0, 5, 2)
[0, 2, 4]
使用range()函数来创建一个列表
>>> list(range(5))
[0, 1, 2, 3, 4]
(2)for循环嵌套
for循环打印99乘法表
for i in range(1,10):
for j in range(1, i+1):
print(str(i)+"*"+str(j)+"="+str(i*j),end='\t')
print()
(3)for循环使用else语句
for循环之后也可使用else语句,用法同while。
li = [1, 2, 3, 4, 5]
for i in li:
print(i)
else:
print("循环结束")
ycy@ubuntu18:~$ python3 for_else.py
1
2
3
4
5
循环结束
3. 跳出循环
(1)break:用来跳出整个当前循环。
li = [1, 2, 3, 4, 5]
for i in li:
if i == 3:
break
print(i)
ycy@ubuntu18:~$ python3 break.py
1
2
(2)continue用来结束当前迭代,并跳到下一次迭代开头。这意味着跳过循环体中余下的语句,但不结束循环。
li = [1, 2, 3, 4, 5]
for i in li:
if i == 3:
continue
print(i)
ycy@ubuntu18:~$ python3 contine.py
1
2
4
5
注:多层循环地跳出可以使用标志位
4. pass语句
pass语句什么也不做。当语法上需要语句但程序不需要动作时,可以使用它。
可以后期添加代码,也可用于调试,语法上是不会报错的。
>>> for i in range(5):
... pass
...