从零开始的python自学之旅(三)
Day 2
- if语句
示例:
嵌套if的示例:score=int(input('请输入成绩')) if score>=90 and score<=100: #也可以写成90<=score<=100,下同 print('你的评分是A') elif score>=80 and score<90: print('你的评分是B') elif score >= 70and score<80: print('你的评分是C') elif score >= 60and score<70: print('你的评分是D') elif score >=0and score<60: print('你不及格') else : print('你输入的成绩有错')
变种写法:identity=input('请输入你的身份') price=int(input('请输入你的消费金额')) if price<=0: print('输入的消费金额有误') else: if identity=='会员': if price>200: money=price*0.8 elif price>100: money=price*0.9 else: money=price print('支出金额为',money) elif identity=='非会员': if price>200: money=price*0.95 else: money=price print('支出金额为', money) else: print('你的身份输入错误')
num_a=int(input('第一个数')) num_b=int(input('第二个数')) print(str(num_a)+'大于等于'+str(num_b) if num_a>=num_b else str(num_a)+'小于'+str(num_b))
- pass语句
用于具体代码待定的地方,如:num = int(input()) if num > 100: pass else: pass
- range()函数
1.range(stop)
2.range(start,stop)r=range(10) print(list(r)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3.range(start,stop,step)r=range(3,10) print(list(r)) #[ 3, 4, 5, 6, 7, 8, 9]
以第三种生成序列的方式为例,检验9是否存在于该序列r=range(2,10,2) print(list(r)) #[2, 4, 6, 8]
print(9 in r) #False
print(8 in r) #True
- 循环语句
1.while()
2.for-in循环a=0 sum=0 while a<100: a += 1 if a%2==0: #这里改成 if a%2: 即可改为求奇数和,拓展,求偶数和可以改成 if not bool(a%2): sum+=a print(sum)
因此,可通过这个特性,更改求100内偶数和的代码for item in 'Python': print(item) #会依次打印出P y t h o n for i in range(10): print(i) #会依次打印出0 1 2 3 4 ....9
a=0 sum=0 for i in range(101): if not bool(i%2): sum+=i print(sum)