if 及循环语句


 1. if 语句

  • if语句支持嵌套
  • 当代码块不想执行任何内容时,需用pass占位
if 条件:
  代码块
else:
  代码块
if 条件:
  代码块
elif 条件:
  代码块
else:
  代码块
if 1==1:
    if 2==2:
        print('Hello')
    else:
        print('welcome')
else:
    print('bye')
if 1==1:
    pass
else:
    print('hello')

 2. while循环语句

# 死循环
import time

while 1==1:
    print('OK',time.time())
#--------------------------------------------

import time

count = 0

while count < 10:
    print('OK',time.time())
    count += 1
print(123)
#--------------------------------------------

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

 

# 使用while循环输入1 2 3 4 5 6    8 9 10

count = 1
while count < 11:
    if count != 7:
        print(count,end=' ')
        count += 1
    else:
        print(' ',end=' ')
        count += 1
# -------------------------------------------------

# 求1-100的所有数的和

s = 0
count = 0
while count < 100:
    count +=1
    s += count
print(s)
# -------------------------------------------------

# 输出1-100内的所有奇数

count = 1
while count <= 100:
    if count%2 != 0:
        print(count, end=' ')
    count += 1
# -------------------------------------------------

#输出1-100内的所有偶数

count = 1
while count <= 100:
    if count%2 ==0:
        print(count, end=' ')
    count += 1
# -------------------------------------------------

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

count = 0
s1 = 0
s2 = 0
while count < 99:
    count += 1
    if count%2 !=0:
        s1 += count
    else:
        s2 += count
print(s1-s2)

# 即就是:
count = 1
s = 0
while count < 100:
    if count%2 !=0:
        s += count
    else:
        s -= count
    count += 1
print(s)
# -------------------------------------------------

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

count = 0
while count < 3:
    user = input('请输入用户名:')
    pwd = input('请输入密码:')
    if user == 'root' and pwd == 'root':
        print('欢迎登录')
        break
    else:
        if count != 2:
            print('用户名或密码输入有误,请重新输入,若连续输入错误3次,今日将锁定账户')
        else:
            print('连续输入错误3次,账户已锁定')
    count += 1

3. for循环语句

for 变量名 in 字符串
    代码块

4. break和continue

  • continue,终止当前循环,开始下一次循环
  • break,终止所有循环
count = 0
while count < 10:
#当count等于7时,执行continue终止当前循环,不再执行后面的print和count+=1,直接回到while开头开始下一次循环
    if count == 7:
        count += 1
        continue
    print(count)
    count += 1
# -------------------------------------------------

count = 0
while count < 10:
    count += 1
    print(count)
    break
    print(111)
print('end')
#结果为1和end,遇到break终止所有循环,不会执行print(111),直接跳出循环向下继续执行
# -------------------------------------------------

test = '朝辞白帝彩云间'

for item in test:
    print(item)
    break
#

for item in test:
    continue
    print(item)
# 什么也不输出

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM