python学习---if---while

分支语句及其拓展

if 条件表达式:
    满足表达式执行的内容


if 条件表达式:
    满足表达式执行的内容
else:
    不满足表达式执行的内容
    # 有多个条件表达式


if  xxxx:
    pass
elif xxxx:
    pass
elif xxxx:
    pass
else:
    pass


a = 3
b = 2

# 三目运算符的变种
print(a if a>b else b)

if a>b:
    print(a)
else:
    print(b)

if_elif应用

求平均成绩
1. 用户输入某个学生的姓名;
2. 输入该学生的语文, 数学与英语的成绩;
3. 打印: 姓名的成绩等级XXXX:

avg_score
90~100   A
80~90    B
70~80     C
0~70     D
other :   invaild score

 stuName = input("姓名:")
chinese = float(input("语文成绩:"))
math = float(input("数学成绩:"))
english = float(input("英语成绩:"))
avgScore = (chinese + math + english) / 3

# if avgScore>90 and avgScore<=100:
if 90 < avgScore <= 100:
    print("%s的等级为%s" % (stuName, 'A'))
elif 80<avgScore<=90:
    print("%s的等级为%s" % (stuName, 'B'))
elif 70<avgScore <=80:
    print("%s的等级为%s" % (stuName, 'C'))
elif 0<avgScore <=70:
    print("%s的等级为%s" % (stuName, 'D'))
else:
    print("%s的成绩是无效的" %(stuName))

循环语句while

while 条件表达式:
    pass

条件表达式若为真,则执行下面语句,为假,则跳出循环;

count = 0
while count < 5:
    print("hello world")
    count += 1  # count = count + 1

输出:

hello world
hello world
hello world
hello world
hello world
循环语句—如何跳出循环
break

break,直接跳出整个循环,循环不再执行

tryCount = 0
while tryCount < 3:
    username = input('用户名:')
    # passwd = input('密码:')
    passwd = getpass.getpass("密码:")
    if username == 'root' and passwd == 'redhat':
        print('login ok')
        break
    tryCount += 1
continue

continue,跳出本次循环,整个循环继续执行

tryCount = 0
while tryCount < 10:
    tryCount += 1
    if tryCount == 2:
        continue
    print(tryCount)
例子
while True:
    cmd = input('Command:')
    if not cmd:
        continue
    elif cmd == 'q':
        break
    else:
        print('execute cmd %s' %(cmd))
while循环练习_猜数字游戏
  1. 系统随机生成一个1~100的数字;
  2. 用户总共有5次猜数字的机会;
  3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
  4. 如果用户猜测的数字小于系统给出的数字,打印”too small”;
  5. 如果用户猜测的数字等于系统给出的数字,打印”恭喜中奖100万”,并且退出循环;

    import random

    sys_num = random.randint(1,100)
    guess_count = 0

    while guess_count < 3:
    # 转换接收的字符串类型为整形
    guess_num = int(input(“Guess Num:”))
    # 猜测次数加1
    guess_count += 1

    # 判断
    if guess_num > sys_num:
        print('tooy big')
    elif guess_num < sys_num:
        print('too small')
    else:
        # break跳出循环;
        print("恭喜中奖100万")
        break
    

    else:
    print(“尝试次数超过3次”)

死循环的几种写法:
# while True:
#     print('hello')
#
#
# while 0<1:
#     print("hello")
#
#
# while 1:
#     print("hello")
if和while后面必须跟的是bool类型, 如果不是布尔类型,转化为bool类型
print(bool("hello"))   # True
print(bool(""))       # False

猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81409854