内容包括:
- 条件语句
- 布尔表达式
- For 和 While 循环
- Break 和 Continue
- Zip 和 Enumerate
- 列表推导式
条件语句
f 语句
if
语句是是一种条件语句,根据条件为 true 还是 false 运行或执行相关代码。下面是一个简单的示例:
if phone_balance < 5:
phone_balance += 10
bank_balance -= 10
我们来详细讲解下每部分。
if
语句以关键字if
开始,然后是要检查的条件,在此例中是phone_balance < 5
,接着是英文冒号。条件用布尔表达式指定,结果为 True 或 False。- 这行之后是一个条件为 true 时将执行的缩进代码块。在此例中,仅在
phone_balance
小于 5 时才执行使phone_balance
递增和使bank_balance
递减的行。如果不小于 5,这个if
块中的代码将被跳过。
If、Elif、Else
除了 if
条件之外,if
语句经常还会使用另外两个可选条件。例如:
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
if
:if
语句必须始终以if
条件开始,其中包含第一个要检查的条件。如果该条件为 True,Python 将运行这个if
块中的缩进代码,然后跳到if
语句之后的剩余代码。elif
:elif
条件用来检查其他条件(前提是if
语句中之前的条件结果为 False)。可以从示例中看出,可以使用多个elif
块处理不同的情形。else
:最后是else
条件,它必须位于if
语句的末尾。该条件语句不需要条件。如果if
语句中所有前面的语句结果都为 False 时,将运行else
块中的代码
值得注意的是:
python代码中的,缩进的意义:
缩进
一些其他语言使用花括号来表示代码块从哪开始,从哪结束。在 Python 中,我们使用缩进来封装代码块。例如,if
语句使用缩进告诉 Python 哪些代码位于不同条件语句里面,哪些代码位于外面。
在 Python 中,缩进通常是四个空格一组。请严格遵守该惯例,因为更改缩进会完全更改代码的含义。如果你是 Python 程序员团队的成员,则所有人都必须遵守相同的缩进惯例!
#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example - try changing the value of number
number = 145
if number % 2 == 0:
print("Number " + str(number) + " is even.")
else:
print("Number " + str(number) + " is odd.")
#Third Example - try to change the value of age
age = 35
# Here are the age limits for bus fares
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
# These lines determine the bus fare prices
concession_ticket = 1.25
adult_ticket = 2.50
# Here is the logic for bus fare prices
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
print(message)
python中的逻辑运算符,比较运算符,算数运算,赋值运算符:
运算符
你需要熟悉三个逻辑运算符:
逻辑使用情况 | 布尔型 | 运算符 |
---|---|---|
5 < 3 and 5 == 5 | False | and - 检查提供的所有语句是否都为 True |
5 <= 3 or 5 == 5 | True | or - 检查是否至少有一个语句为 True |
not 5 != 3 | False | not - 翻转布尔值 |
算术运算符 | |
+ | 加 |
- | 减 |
* |
乘 |
/ | 除 |
** | 取幂 |
% | 取余 |
// | 向下取整 |
赋值运算符 | |
= | x = 2 |
+= | x += 3 x = x + 3 |
-= | x -= 2 x = x - 2 |
*= | x *= 1.5 x = x * 0.5 + x |
复杂的布尔表达式
If
语句有时候会使用更加复杂的条件布尔表达式。可能包括多个比较运算符、逻辑运算符,甚至包括算式。例如:
if 18.5 <= weight / height**2 < 25:
print("BMI is considered 'normal'")
if is_raining and is_sunny:
print("Is there a rainbow?")
if (not unsubscribed) and (location == "USA&#