当前位置:   article > 正文

Python(二):条件语句和循环语句_for num in range(1,10,2)

for num in range(1,10,2)

1.条件语句

  • if语句
  • if-else语句
  • if-elif-else语句
  • assert关键词

1.1 if语句

if expression:
	expr_true_suite
  • 1
  • 2
  • if 语句的 expr_true_suite 代码块只有当条件表达式 expression 结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。
  • 单个 if 语句中的 expression 条件表达式可以通过布尔操作符 and,or和not 实现多重条件判断。

例:

if 2 > 1 and not 2 >3:
	print('U r right')
# U r right
  • 1
  • 2
  • 3

1.2 if-else语句

if expression:
    expr_true_suite
else:
    expr_false_suite
  • 1
  • 2
  • 3
  • 4

Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。

例:

temp = input("猜猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为str
if guess == 666:
	print("你也太了解小姐姐了!")
	print("猜对也没有奖励")
else:
	print("猜错啦!")
print("游戏结束!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

if语句支持嵌套,即在一个if语句中嵌入另一个if语句,从而构成不同层次的选择结构。Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。

例:

temp = input("不妨猜猜小哥哥想的是哪个数字:")
guess = int(temp)
if guess > 8
	print("大了大了")
else:
	if guess == 8:
		print("猜对啦")
		print("猜对也没有奖励哦")
	else:
		print("小了小了")
print("游戏结束")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

if-elif-else语句

if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
    .
    .
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。

例:

temp = input('请输入成绩')
source = int(temp)
if 100 >= source >= 90:
	print('A')
elif 90 >= source >= 80:
	print('B')
elif 80 >= source >= 60:
	print('C')
elif 60 > source >= 0:
	print('D')
else:
	print('输入错误')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

1.4 assert关键词

assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。

my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0

# AssertionError
  • 1
  • 2
  • 3
  • 4
  • 5

2.循环语句

  • while循环
  • while-else循环
  • for循环
  • for-else循环
  • range()函数
  • enumerate()函数
  • break语句
  • continue语句
  • pass语句
  • 推导式
  • 综合例子

2.1 while循环

while语句最基本的形式包括一个位于顶部的布尔表达式,一个或多个属于while代码块的缩进语句。

while 布尔表达式:
    代码块
  • 1
  • 2

while循环的代码块会一直循环执行,直到布尔表达式的值为布尔假。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号