python流程控制

一、条件判断语句

1、格式:

if <条件判断1>:

  执行命令

elif <条件判断2>:

  执行命令2

else:

  执行命令3

2、例子:

# 判断分数的等地,多分支
score = int(input("Please input grade(0-100):"))
if score > 100:
    print("grade not more than 100..")
elif score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
elif score >= 0:
    print("D")
else:
    print("grade more than 0..")

二、循环语句

1、while语句

格式:

while True:

  执行代码

1)break

退出循环

2)continue

跳过本次循环,进行下一轮循环

3、while……else……

作用:while语句执行完成(没有break),执行else语句

格式:

while True:

  执行命令

else:

  执行命令

4、死循环

例子

# 使用while循环打印1,2,3,4,5,7,8,9
count = 0
while count < 10:
    count += 1
    if count == 6:
        continue
    print(count)
# 求1-100的和
sum_count = 0
count = 1
while count <= 100:
    sum_count += count
    count += 1
print(sum_count)
# 求1-100偶数的和
sum_count = 0
count = 1
while count <= 100:
    if count % 2 == 0:  # 判断偶数
        sum_count += count
    count += 1
print(sum_count)
# 求1-100奇数的和
sum_count = 0
count = 1
while count <= 100:
    if count % 2 != 0:  # 判断奇数
        sum_count += count
    count += 1
print(sum_count)
# 求1-2+3-4...到100的和
sum_count = 0
count = 1
while count <= 100:
    if count % 2 != 0:  # 判断奇数
        sum_count += count
    else:   # 判断为偶数
        sum_count -= count
    count += 1
print(sum_count)
# 用户有三次登录机会
_username = 'tom'
_password = 'abc123'
count = 1
while count <= 3:
    name = input("请输入用户名:")
    password = input("请输入密码:")
    if name == _username and password == _password:
        print("登录成功")
        break
    else:
        if count == 3:
            print("退出")
        else:
            print("请再输入一次")
    count += 1

1、for循环

格式:

for i in iterable:

  print(i)

for i in range(100):
    print(i)

 

 

# 使用while循环打印1,2,3,4,5,7,8,9
count = 0
while count < 10:
    count += 1
    if count == 6:
        continue
    print(count)
posted @ 2019-04-27 21:40  市丸银  阅读(97)  评论(0编辑  收藏  举报