一、语句
每一行代码,都是一条语句。
语句分类:
- 最基本的语句:赋值语句,函数/方法。
- 条件语句:if。
- 循环语句:for/while。
- 函数语句:def等。
- 模块语句:import。
# 函数
print(1)
# 方法
lst.append(1)
二、条件语句
python.org:if 语句
liaoxuefeng:条件判断
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
if 判断条件:
执行语句……
elif 判断条件:
执行语句……
else:
执行语句……
可以有零个或多个elif 部分,以及一个可选的 else 部分。
关键字 ‘elif’ 是 ‘else if’ 的缩写,用于避免过多的缩进。
一个 if … elif … elif … 序列可以看作是switch或case语句的替代。
基本判断语句
# 基本判断语句
score = input('请输入成绩:')
print('该学生成绩为:' + score)
print(type(score)) # 注意:input()返回结果都为字符串,如果需要变为数字则用到int()/float()
score = int(score)
if score < 60: # Python代码的缩进规则:具有相同缩进的代码被视为代码块
print('该学生成绩不及格')
两种条件判断:if-else
# 两种条件判断:if-else
flag = False
name = 'luck'
if name == 'python': # 判断变量否为'python'
flag = True # 条件成立时设置标志为真
print( 'welcome boss') # 并输出欢迎信息
else:
print(name) # 条件不成立时输出变量名称
多种条件判断:if-elif-…-else
# 多种条件判断:if-elif-...-else
num = 2
if num == 3: # 判断num的值
print('boss')
elif num == 2:
print('user')
elif num == 1:
print('worker')
elif num < 0: # 值小于零时输出
print('error')
else:
print('roadman') # 条件均不成立时输出
单语句多条件判断:or and
# 单语句多条件判断:or and
num = 5
if num >= 0 and num <= 10: # 判断值是否在0~10之间
print( 'hello') # 输出结果: hello
num = 10
if num < 0 or num > 10: # 判断值是否在小于0或大于10
print( 'hello') # 输出结果: undefine
else:
print( 'undefine')
num = 8
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15): # 判断值是否在0~5或者10~15之间
print( 'hello')
else:
print( 'undefine') # 输出结果: undefine
三、循环语句
for循环
python.org:for 语句
liaoxuefeng:循环
# 通过for遍历序列、映射
# 遍历list
lst = list(range(10))
for i in lst[::2]:
print(i)
print('\n')
# 遍历字典
age = {'Tom':18, 'Jack':19, 'Alex':17, 'Mary':20}
for name in age:
print(name + '年龄为:%s岁' % age[name])
# 嵌套循环
# 建议:不要多于3个嵌套
for i in range(3):
for j in range(2):
print(i,j)
while循环
基本循环语句
# 基本循环语句
count = 0
while count < 9:
print( 'The count is:', count)
count = count + 1
print( "Good bye!")
无限循环
# 无限循环:如果条件判断语句永远为 true,循环将会无限的执行下去
# 要避免无限循环
var = 1
while var == 1 :
num = input("Enter a number :")
print( "You entered: ", num)
print( "Good bye!")
while-else语句
# while-else语句
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")
循环控制
break
# break语句
# 用来终止循环语句,即便循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
s = 0
n = 1
while n > 0:
s = s + n
n = n + 1
if n == 20:
break
print(s)
s = 0
for i in range(10):
for j in range(5): # 使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。
s = s + (i*j)
print('第%i次计算' %(i+j))
if s > 20:
break
print('结果为%i' % s)
continue
continue:在语句块执行过程中跳出该次循环,执行下一次循环
# continue语句
# 用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
s = 0
for i in range(50):
if i%2 == 0:
s += i
else:
continue
print('第%i次计算'%(i/2))
print('结果为%i' % s)
pass
# pass语句
# 空语句,是为了保持程序结构的完整性。(不中断也不跳过)
for letter in 'Python':
if letter == 'h':
pass
print( '当前字母 : h,但是我pass了')
print( '当前字母 :', letter)
print( "Good bye!")