条件控制
if – elif – else语句
if condition_1: statement_block_1 elif condition_2: statement_block_2 else: statement_block_3 #Python中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。 #每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。 #使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。 #在Python中没有switch – case语句。
if – else嵌套
if 表达式1: 语句 if 表达式2: 语句 elif 表达式3: 语句 else: 语句 elif 表达式4: 语句 else: 语句 #例如: num=int(input("输入一个数字:")) if num%2==0: if num%3==0: print ("你输入的数字可以整除 2 和 3") else: print ("你输入的数字可以整除 2,但不能整除 3") else: if num%3==0: print ("你输入的数字可以整除 3,但不能整除 2") else: print ("你输入的数字不能整除 2 和 3")
循环语句
while - else 语句
count = 0 while count < 5: print (count, " 小于 5") count = count + 1 else: print (count, " 大于或等于 5")
for 语句
1. for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
2. break 语句用于跳出当前循环体。
languages = ["C", "C++", "Perl", "Python"] for x in languages: print(x) sites = ["Baidu", "Google","Nowcoder","Taobao"] for site in sites: if site == "Nowcoder": print("牛客教程!") break print("循环数据 " + site) else: print("没有循环数据!") print("完成循环!") #最后输出 #循环数据 Baidu #循环数据 Google #牛客教程! #完成循环!
range()遍历
1. 如果你需要遍历数字序列,可以使用内置range()函数,它会生成数列。
2. 也可以使range()以指定数字开始并指定不同的增量。
3. 结合range()和len()函数以遍历一个序列的索引。
4. continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
5. 循环语句可以有 else 子句,它在穷尽循环,或者条件变为 false时导致循环终止时,被执行。但循环被break终止时不执行。
for i in range(5): print(i) for i in range(5,9) : print(i) for i in range(0, 10, 3) : print(i) a = ['Google', 'Baidu', 'Nowcoder', 'Taobao', 'QQ'] for i in range(len(a)): print(i, a[i]) for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, '等于', x, '*', n//x) break else: print(n, ' 是质数')
函数
1. 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。
2. 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
3. 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
4. 函数内容以冒号起始,并且缩进。
5. return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
def 函数名(参数列表): 函数体