02 python入门-if、while、for

程序一般的结构包括:顺序结构、选择结构、循环结构

1.if条件语句:

(1)简单的if语句:

if 条件:
    语句

(2)if语句的嵌套:

if 条件:
    语句1
elif 条件:
    语句2
elif 条件:
    语句3 #elif可以根据自己的需要嵌套
else:
    语句4

示例:猜拳游戏,电脑随机生成0-剪刀、1-石头、2-布,与玩家输入比较,输出相应的结果

import random

player = input('请输入:剪刀(0)  石头(1)  布(2):')

player = int(player)

computer = random.randint(0,2)

# 用来进行测试
#print('player=%d,computer=%d',(player,computer))

if ((player == 0) and (computer == 2)) or ((player ==1) and (computer == 0)) or ((player == 2) and (computer == 1)):
    print('获胜,哈哈,你太厉害了')
elif player == computer:
    print('平局,要不再来一局')
else:
    print('输了,不要走,洗洗手接着来,决战到天亮')

2.while循环

(1)简单的while循环

while 条件:
    语句

(2)while嵌套(里面也可以嵌套if语句)

while 条件:
    语句1
    while 条件:
        语句2

应用:

(1)打印如下图形

    *
    * *
    * * *
    * * * *
    * * * * *

示例程序: 

i = 1
while i<=5:
    j=1
    while j<=i:
        print("* ",end='')
        j+=1
    print('\n')
    i+=1

(2)打印九九乘法表

示例程序:

i = 1
while i<=9:
    j=1
    while j<=i:
        print("%d*%d=%-2d "%(j,i,i*j),end='')
        j+=1
    print('\n')
    i+=1

3.for循环

像while循环一样,for可以完成循环的功能。在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

 for 临时变量 in 列表或者字符串等:
        循环满足条件时执行的代码
    else:
        循环不满足条件时执行的代码

示例:

name = ''

for x in name:
    print(x)
else:
    print("没有数据")

4.break和continue

  • break/continue只能用在循环中,除此以外不能单独使用

  • break/continue在嵌套循环中,只对最近的一层循环起作用

  • break结束最近一层的整个循环,continue结束本次循环

示例:

 i = 0
  while i<10:
      i = i+1
      print('----')
      if i==5:
          break
      print(i)
#结果不再打印5之后的数字
 i = 0

  while i<10:
      i = i+1
      print('----')
      if i==5:
          continue
      print(i)
#结果只是不打印5这个数字

猜你喜欢

转载自blog.csdn.net/qq_22169787/article/details/84654823