条件判断-循环笔记1

课程内容

1、条件判断
2、循环
3、函数
4、类

条件判断

if condition:
   do somthing
else:
    do somthing
  File "<ipython-input-4-ccbf315b7275>", line 2
    do somthing
              ^
SyntaxError: invalid syntax

卖蔬果,合计金额32.5,满30打九折, 求实际花费

total_cost=32.5
if total_cost>30:
   discount=0.9
else:
    discount=1
    
total_cost*=discount
print('实际花费为: {}元'.format(total_cost))

实际花费为: 29.25元

卖蔬果,合计金额32.5,满30打九折,满50打8折, 求实际花费

total_cost=60
if total_cost>50:
   discount=0.8
elif total_cost>30:
    discount=0.9

else:
    discount=1
    
total_cost*=discount
print('实际花费为: {}元'.format(total_cost))
实际花费为: 48.0元

重点

1.条件判断可以任意组合
elif可以有任意多个,else可有可无
条件判断可以嵌套

  1. condition
condition=('e')
if condition:
    print('Ture')
else:
    print('False')
Ture
condition=('')
if condition:
    print('Ture')
else:
    print('False')
False

###从理解的角度来讲,一个值被当作布尔值,概念上更像是有与没有的区别

and or not

##布尔型变量做运算

a=[1,2,3]
b=10
print(a and b)
print(b and a)
print(a or b)
print(b or a)
print(not b)
10
[1, 2, 3]
[1, 2, 3]
10
False

条件判断的近亲-断言

if not condition:
    crash program
#意思是:我断言它是肯定是这样的,如果不是,就崩溃
  File "<ipython-input-34-46d15215a3c8>", line 2
    crash program
                ^
SyntaxError: invalid syntax
age=18
assert age==20,"他居然不是20岁"
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-37-334d2b7cb1eb> in <module>
      1 age=18
----> 2 assert age==20,"他居然不是20岁"


AssertionError: 他居然不是20岁
age=18
assert age==18

循环

for遍历循环,while 条件循环

costs=(3,6,7)
for cost in costs:
    print('消费{}元'.format(str(cost).center(10)))
消费    3     元
消费    6     元
消费    7     元

###长度为20的随机列表

import random
random.randint(1,10)
6
import random
random_numbers=[]
while len(random_numbers)<20:
    random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))  
[3, 4, 7, 9, 7, 8, 6, 3, 6, 5, 2, 9, 6, 7, 3, 8, 5, 2, 6, 6] 20

编程建议,能用for循环,就不用while循环

random_numbers=[]
for i in range(20):
      random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))         
[10, 7, 5, 3, 5, 10, 8, 3, 8, 5, 7, 2, 5, 9, 10, 4, 10, 3, 1, 1] 20

循环条件跟数量没关系时,只能用while
###题目:往空裂帛添加随即数,直到添加的为9,则终止

random_numbers=[]
while (9 not in random_numbers):
    random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))      
[10, 5, 2, 1, 5, 1, 5, 9] 8

###重点:只有一个元素的列表
###问题[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4TdYN5l-1571494145620)(attachment:image.png)]

a=[1]
b=(2,)
type(a),type(b),b,len(b)
(list, tuple, (2,), 1)
a=[1]
b=(2)
type(a),type(b)
(list, int)
random_numbers
[10, 5, 2, 1, 5, 1, 5, 9]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值