从零开始的python自学之旅(三)

从零开始的python自学之旅(三)

Day 2

  • 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('你输入的成绩有错')
    
    嵌套if的示例:
    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)
    r=range(10)
    print(list(r)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    2.range(start,stop)
    r=range(3,10)
    print(list(r)) #[ 3, 4, 5, 6, 7, 8, 9]
    
    3.range(start,stop,step)
    r=range(2,10,2)
    print(list(r)) #[2, 4, 6, 8]
    
    以第三种生成序列的方式为例,检验9是否存在于该序列
    print(9 in r) #False
    print(8 in r) #True

  • 循环语句
    1.while()
    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)
    
    2.for-in循环
    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
    
    因此,可通过这个特性,更改求100内偶数和的代码
    a=0
    sum=0
    for i in range(101):
        if not bool(i%2):
            sum+=i
    print(sum)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值