Python -- 4. if()操作 & for操作

1. 条件测试
每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试 。

  • ==, !=, <, <=, >, >=
  • and, or
  • 检查特定值是否包含在列表中, in / not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")


2. if 语句
(1).简单的if 语句

age = 19
if age >= 18:
    print("You are old enough to vote!")

(2).if-else 语句

age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")

(3).if-elif-else 结构

age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

(4).使用多个elif 代码块

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5
print("Your admission cost is $" + str(price) + ".")

(5).省略else 代码块
Python并不要求if-elif 结构后面必须有else 代码块。



3. 使用if 语句处理列表
确定列表不是空的
在if 语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True ,并在列表为空时返回False 。

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")


4. for 操作

for iterating_var in sequence:
statements(s)

唯一要注意的是,in 后面是个序列:

for i in 100 #是错误的
for i in range(100) #要改成序列的样子
    xxxxxx

初始化,也要注意:

for i=1 in range(100) #也是错误的
#------------------------------
i = 1
for i in range(100) #这样才是对的

for 的步长都是整数,没有小数

for i in range(1, 10, 0.5) #是错误的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值