一、条件判断语句
根据Python的缩进规则:Tab缩进(四个空格),区分代码块。
pass关键字可以省略逻辑,但是if else 代码块不报错(条件判断语句中,冒号不能省略)
if 条件1: 代码块1 elif 条件2: 代码块2 else: 代码块3
age = 3 if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') if a == 9: pass elif a != 9: pass else pass
只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
if判断条件还可以简写,比如写: if x: print('True')
# -*- coding:utf-8 -*- ''' input()返回的数据类型是str,str不能直接和整数比较,可以进行类型转换。 ''' a = input("请输入:") age = int(a) if age >= 20: print("已成年") elif age > 50: print("中年") else: print("其他") if age < 20: print("未成年") elif age < 0: print("输入有误:") else: print("age=%d" % (age))
二、循环结构语句
关键字: while ... : while ... : 代码块1 [else: 代码块2] for ... in ... : continue # 跳出当前循环 break # 跳出整个循环
while循环
# -*- coding:utf-8 -*- ''' 计算1~100的累计和 ''' i = 1 sum = 0 while i<=100: sum += i i += 1 print("1~100的累积和为:%09d"%(sum))
count = 1 while count < 10: continue # 跳出当前循环 print(123) # 永远不会执行 print('end')
count = 1 while count < 10: print(count) # 输出 1 2 3 ... 9 count = count + 1 else: print('else') #当count=10时,跳出循环,执行一次else print('...')
while嵌套应用:九九乘法表
m = 1 while m <= 9: n = 1 while n <= m: print("%d * %d = %d" % (n, m, m * n), end="\t") if m == n: print() n += 1 m += 1
练习:
#1、使用while循环输入 1 2 3 4 5 6 8 9 10 n = 1 while n < 11: if n == 7: pass else: print(n) n = n + 1 #2、求1-100的所有数的和 n = 1 sum = 0 while n < 101: sum = sum + n n = n + 1 print(sum) #3、输出1-100内所有奇数 n = 1 while n < 101: tmp = n % 2 if tmp == 0: pass else: print(n) n = n + 1 # 4、求1-2+3-4+5-6...99的所有数的和 n = 1 s = 0 while n < 100: tmp = n % 2 if tmp == 0: s = s - n else: s = s + n n = n + 1 print(s)
用户登录(三次机会重试)
count = 0 while count < 3: user = input('>>>') pwd = input('>>>') if user == 'alex' and pwd == '123': print('欢迎登录') ... break else: print('用户名或者密码错误') count = count + 1
for循环
for 临时变量 in 列表或者字符串等: 循环满足条件时执行的代码 else: 循环不满足条件时执行的代码
#!/usr/bin/env python # -*- coding:utf-8 -*- for a in range(1,101): if a % 2 == 0: continue # 跳出当前循环 if a > 50: break # 跳出整个for循环 print(a) for c in "abcd": print(c,end="\t") # a b c d