while/for 循环

while循环:

循环打印3次 hello

times = 3       # 定义次数为3
a = 'hello'
while times > 0 :

     print(a)

     times -= 1    # 对 times 进行一个 -1 的操作  

循环打印出10,9,8,7,6,5,4,3,2,1

times = 10
while times > 0:
     print(times)
     times -= 1

循环打印出 1,2,3,4,5,6,7,8,9,10   

times = 1
while times < 11:
     print(times)
     times += 1

打印出 1+2+3+4...+10 的结果

times = 1
result = 0  # 存储计算的结果,定义的值是0,不影响计算的结果

while times < 11:
     result += times # 把每一次循环的times的值,累积到 result 中
     times += 1
print(result)

打印出a中的每个元素

a = [11,22,33,44,1,2,3,4]
index = 0                  # 下标 从0开始
while index < len(a) :
    print(a[index])
    index += 1

  

打印出列表里面所有的偶数

a = [11,22,33,44,1,2,3,4]
index = 0                            # 下标 从0开始
while index < len(a) :
if a[index] % 2 == 0:            # 判断 数字 除以2 的余数 是否为0
         print(a[index])
         index += 1

分别打印出奇数和偶数

a = [11,22,33,44,1,2,3,4]
jishu = []
oushu = []
index = 0                    # 下标 从0开始
while index < len(a) :
if a[index] % 2 == 0:                      # 判断 数字 除以2 的余数 是否为0
       oushu.append( a[index] )
else:
       jishu.append( a[index] )
       index += 1

print(jishu)
print(oushu)

while 条件 True/False:

while True:
     print('hello')

 

for循环:

根据列表里面有多少个元素就循环多少次,并打印出来

temp = ['python','java','php','mysql']
for hhh in temp:
     print("在这次循环中,hhh的值是{0}".format(hhh))

range()  函数 顾头不顾尾

range(9)         >>> 生成 0,1,2,3,4,5,6,7,8
range(3,10)      >>> 生成 3,4,5,6,7,8,9
range(1,10,2)    >>> 生成 1,3,5,7,9    

循环3次并打印出变量(i)的值

for i in range(3): # 0,1,2
     print(i)

 练习:用for循环+range() 做这道题

1、让用户输入一个整数,去判断用户输入的整数,是否以程序设置(8)一致

2、告诉用户 大了、小了、猜对了
3、给用户三次机会 去猜,如果用户猜对了,退出游戏

for i in range(3):
     guess = input('请输入一个整数')
     guess = int(guess)
     bingo = 8
     if guess == bingo:
         print('猜对了')
         break
     elif guess > bingo:
         print('大了')
     else:
         print('小了')

  

 

posted @ 2022-02-28 23:19  ls珊  阅读(46)  评论(0编辑  收藏  举报