条件语句
- if 语句
if phone_balance < 5 :
phone_balance += 10
bank_balance -= 10
冒号后为满足if的条件后要执行的语句
- elif 以及else语句
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')
python中用缩进封装代码块
注意格式输出语法 message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
条件布尔表达式
即在if语句中使用非布尔对象代替布尔表达式,python检查其真假值并判断是否运行缩进代码
python中视为false的内置对象
- 定义为false的常量: None
和False
- 任何数字类型的零: 0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- 空序列和空集合: ""
,()
,[]
,{}
,set()
,range(0)
errors = 3
if errors:
print("You have {} errors to fix!".format(errors))
else:
print("No errors to fix!")
- 并:`and`,或:`or`
for循环
- for 循环的组成部分
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city.title())
⚠ 标准命名应为一个单数一个复数,.title()
作用是首字母大写
- 创建列表 -->
append()
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
- 创建列表 -->
range()
range(start = 0, stop, step = 1)
以上为默认值,stop比序列的最后一个数字大一,同list的遍历
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title()
⚠ 此种写法并未对names对象本身进行修改,所以没有效果
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
for name in names:
name = name.lower().replace(" ", "_")
print(names)
也可以使用其重复某个操作
for i in range(3):
print("Hello!")
附:每日一题
if (x>3) : print("True") else: print("False")
,若 x=2,则该段代码执行结果是?
答:False