选择语句
单分支选择结构
a = int(input("enter a number smaller than 10:"))
if a < 10:
print(a)
单分支结构中,如果条件语句判断为False,则结束判断
Python中表达式为False的情况
False
0
0.0
空值None
空序列(字符串、列表、元组、字典、集合)
空range对象
空迭代对象
注意:Python条件表达式中不能用=,而要用==来判断是否相等
双分支选择结构
if 条件表达式:
语句1
else:
语句2
举例:
s = input('请输入一个数字:')
if int(s)<10:
print('s是小于10的数字')
else:
print('s是一个大于等于10的数字')
三元条件运算符
格式:
条件为真时的值 if (条件语句) else 条件为假时的值
上面的例子还可以写成:
s = int(input("请输入一个数字:"))
print("s大于10") if s>10 else print("s小于等于10")
多分支选择结构
#测试多分支选择结构
score = int(input("please enter the score:"))
grade = ""
if score<60:
grade = "failed"
elif score<80:
grade = "pass"
elif score<90:
grade = "good"
else:
grade = "excellent"
print("Your score is {0}, grade is {1}".format(score, grade))
注意:多分支结构中的几个分支是有逻辑关系的,不能随意变换顺序
练习:已知坐标x,y,求象限
x = int(input("Please enter the x:"))
y = int(input("Please enter the y:"))
if x>0 and y>0: print("1st quadrant")
elif x<0 and y>0: print("2nd quadrant")
elif x<0 and y<0: print("3rd quadrant")
elif x>0 and y<0: print("4th quadrant")
elif x==0 and y==0: print("the origin point")
elif x==0: print("on the x-axis")
elif y==0: print("on the y-axis")
选择结构嵌套
成绩不同分数与对应等级:
#测试选择结构的嵌套
score = int(input("please enter your score (between 0-100):"))
grade = ""
if score>100 or score<0:
score = int(input("please enter your score (★between 0-100★)"))
else:
if score>=90:
grade = "A"
elif score>=80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "E"
print("your score is {0}, your grade is {1}".format(score, grade))
print("*"*20)
注意:两个print的缩进位置
score = int(input("please enter your score (between 0-100):"))
grade = "ABCDE"
num = 0
if score>100 or score<0:
score = int(input("please enter your score (★between 0-100★)"))
else:
num = score//10
if num <6:
num = 5
print(grade[9-num])
注意:这个循环是有个问题的,当你输入不符合规则的数字超过一次后,就会终止程序了,所以需要下一节的while循环
while循环语句
循环结构:只要条件不为假,就会一直执行循环内部的语句
注意:循环体里的语句一定要改变条件表达式,才能使循环趋于结束,否则就是个死循环
操作:利用while循环打印0-10的数字
#测试while循环
num = 0
while num<=10:
print(num)
num += 1
#计算1-100之间数字的累加和
num2 = 0
sum_all = 0
while num2<=100:
sum_all = sum_all + num2
num2 += 1
print("1-100数字相加为:", sum_all)