2:if 语句

if 语句

语法形式:
第一种,只有两个分支:

if 表达式:
    something
else:
    something

第二种,有多个分支:

if 表达式1:
    do something 1
elif 表达式2:
    do something 2
elif 表达式3:
    do something 3
else:
    balabala

python 通过 '==' 判断相等,'!=' 判断不相等,'in' 和 'not in' 判断包含,也可以直接通过布尔类型判断。

a = 12
b = 3

# 1 通过 == 判断
if a == b:
    print('test')
else:
    print('youyou')
# 运行结果 youyou
    
# 2 通过 != 判断
if a != b:
    print('test')
else:
    print('youyou')
# 运行结果 test

# 3 in、 not in 用法
str1 = 'test wawawa'
if 'test' in str1: #若'test'存在于字符串 str1 里,则打印'zhenbang'.
    print('zhenbang')
else:
    print('meishenmo')

# 4 布尔类型
str1 = 'test wawawa'
if str1: # 若 str1 的值存在,则打印 str1
    print(str1)
else:
    print('not exist')

判断成绩的小例子:

# if 判断成绩
 """
 输入一个分数;
 大于等于90 优秀,
 小于90 大于等于80 良好,
 大于等于60 小于80 及格,
 小于60 不及格。
 """
score = input("请输入你的成绩:")
# input 接收到的类型全部都是字符串。python3.2 以后没有 raw_input。
print(type(score)) #查看变量类型
score = int(score) #转换成 int 型
if score >= 90:
    print('优秀')
elif score < 90 and score >= 80:
    print('良好')
elif score <80 and score >= 60:
    print('及格')
else:
    print('不及格')

猜你喜欢

转载自www.cnblogs.com/mayytest1202/p/9692314.html