循环语句作业与循环补充(continue与break)

作业:

1.使用while循环输入1 2 3 4 5 6 8 9 10(没有7)

 

n = 1
while n < 11:
    if n == 7:
        pass
    else:
        print(n)
    n = n + 1
print('结束')

 

2.求1-100所有数的和

 

n = 1
s = 0
while n < 101:
    s = s + n
    n = n + 1
print(s)

 

3.输出1-100的所有奇数

 

n = 1
while n <101:
    print(n)
    n = n + 2
print('结束')

 

 

n = 1
while n <101:
    temp = n % 2
    if temp == 0:
        pass
    else:
        print(n)
    n = n + 2
print('结束')

 

4.输出1-100的所有偶数

 

n = 1
while n < 101:
    temp = n % 2
    if temp == 0:
        print(n)
    else:
        pass
    n = n + 1
print('结束')

 

5.求1-2+3-4+5...99的所有的数的和

 

n = 1
s = 0
while n < 101:
    temp = n % 2
    if temp == 0:
        s = s - n
    else:
        s = s + n
    n = n + 1
print(n)

6.用户登录(三次机会重试)

count = 0
while count < 3:
    user = input('请输入用户名')
    pwd = input('请输入密码')
    if user == 'alex' and pwd == '123':
        print('欢迎登录')
        break
    else:
        print('用户名或密码错误')
        count = count + 1
    

注意:1.如果if语句里面加and,只需要在最后输入一个冒号:

        2.IF下面的代码块注意空格一致

 

7.补充:a. while else 

count = 0
while count < 0:
    print(count)
    count = count + 1
else:
    print('else')

        b.continue(终止当前循环开始下一次循环)

count = 0
while count < 10:
    if count == 7:
        count = count + 1
        continue
    print(count)
    count = count + 1

注意:如果符合条件那么continue下面的代码都不再执行!

 

            c.break(终止所有循环直接跳出)

count = 0
while count < 10:
    count = count + 1
    print(count)
    break
    print('haha')
print('hehe')
    

8.死循环:

注意最后print的是否空格区别。

count = 0
while count < 10:
  print('继续运行')
  count = count + 1
print('结束运行')

posted on 2018-04-27 23:03  monster7  阅读(324)  评论(0)    收藏  举报

导航