条件语句
1.If 语句
if 语句可以有条件的实现代码,这意味着如果条件为前面定义的真,就执行后续代码块,如果条件为假,就不执行。
2.else子句
else不是独立的子句,而是if语句的一部分
3 . elif子句
elif是else if 的缩写。由一个if子句和一个else子句组合而成,也就是包含条件的else子句
number=int(input('Enter a number between 1 and 10: '))
if number<=10 and number >=1:
print('Great!')
else:
print('wrong!')
4.assert断言
如果知道必须满足特定条件,程序才能正确运行,可在程序中添加assert语句充当检查点,这很有帮助,还可在条件后面添加一个字符串,对断言做出说明。
age=-1
assert 0<age<100,'the age must be realistic'
Traceback(most recent call last):
File "<stdin>",line 1,in?
AssertionError: the age must be realistic
循环
5.while循环
重复操作多次
x=1
while x<=100
print(x)
x+= 1
- for 循环
一种需求是为序列中每个元素执行代码块,为此,可以使用for语句
numbers=[ 0,1,2,3,4,5,6,7,8,9]
for word in words:
print(number)
7.break
要结束(跳出)循环,可使用break。假设你要找出小于100的最大平方值,可从100开始向下迭代。找到一个平方值后,无需载迭代,因此直接跳出循环。
from math import sqrt
for n in range(99,0,-1):
root=sqrt(n)
if root ==int(root):
print(n)
break
循环 跳出循环
- continue
continuu结束当前迭代,并跳到下一次迭代开头。这基本上意味着跳过循环体重余下的语句,但并不结束循环。这在循环体庞大而复杂,且存在多个要跳过它的原因时很有用。
for x in seq
if condition1: continue
if condition2: continue
if condition3: continue
do_something()
do_something_else()
do_another_thing()
etc()