这次我们直接在编辑器里面进行操作,我用的编辑器是Pycharm
用Python作选择
一、判断结构 if
这里是最简单的一个判断程序
a = 1
if a == 2:
print("a is 2")
print("Progamed ended!")
运行结果:
(1)多重比较 if 嵌套语句
a = 1
name = "Gorit"
if a == 2:
print("a is 2")
if name == "Gorit":
print('My name is Gorit')
运行结果:
什么都没有,这是因为第一个判断结构为假,所以程序就直接跳过第二个判断结构,所以程序就直接运行结束了
我们试试把a改成2试试看
(2)python中还会提供大于,小于,大于等于,小于等于还有不等于的操作
if a<5:
if a<=5:
if a>=5:
if a!+5:
(3)更多的判断条件(对上面的代码进行改进 (逻辑‘与’,‘或’)
a = 2
name = "Gorit"
if a == 2 and name == "Gorit": #and相当于C语言种的&& 与操作,两个式子同为真时才为真
print("a is 2")
print('My name is Gorit')
a = 222
name = "Gorit"
if a == 2 or name == "Gorit": #逻辑或,相当于C语言当中的“||”,两者中有一个为真就是真
print("a is 2")
print('My name is Gorit')
运行结果:
(4)多重选择
我们总不能一直用 if 进行判断,所以Python提供了另一种判断的结构即 if elif 功能同 C语言中 if else
score = int(input("input your English scores!:"))
if score >=90 and score <=100:
print("A")
elif score >=80 and score <=89:
print("B")
elif score >=70 and score <=79:
print("C")
elif score <70:
print("D")
另一种
score = int(input("input your English scores!:"))
if score >=90 and score <=100:
grade = 'A'
elif score >=80 and score <=89:
grade = 'B'
elif score >=70 and score <=79:
grade = 'C'
else :
grade = 'D'
print("Your grades is",grade)
运行结果
圈圈中的部分是我们输入的成绩,其实最后一个elif 可以换成else 但是要注意条件的限制
这就是判断结构的大部分内容啦!如有疑问可以在下方留言