Python3基础知识:条件循环语句

版权声明:转载请随意! https://blog.csdn.net/qq_41723615/article/details/89074112

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

while...循环语句

number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
    guess = int(input("请输入你猜的数字:"))
 
    if guess == number:
        print("恭喜,你猜对了!")
    elif guess < number:
        print("猜的数字小了...")
    elif guess > number:
        print("猜的数字大了...")

在 while … else 在条件语句为 false 时执行 else 的语句块:

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

语句组

while (flag): print ('欢迎访问菜鸟教程!')

for循环语句:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

range()函数

遍历数字序列,可以使用内置range()函数。

>>>for i in range(5):
...     print(i)
...
0
1
2
3
4

也可以使用range指定区间的值:

>>>for i in range(5,9) :
    print(i)
 
    
5
6
7
8
>>>

也可以使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'):

>>>for i in range(0, 10, 3) :
    print(i)
 
    
0
3
6
9
>>>for i in range(-10, -100, -30) :
    print(i)
 
    
-10
-40
-70

可以结合range()和len()函数以遍历一个序列的索引

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ

可以使用range()函数来创建一个列表:

扫描二维码关注公众号,回复: 5822925 查看本文章
>>>list(range(5))
[0, 1, 2, 3, 4]

break和continue语句和Java的一样用法。

pass是空语句,是为了保持程序结构的完整性。

猜你喜欢

转载自blog.csdn.net/qq_41723615/article/details/89074112