It's our wits that make us men.

2019/7/6 python入门-if

Posted on By LuLu

python入门-if

if

if简单测试

spots=['qd','cd','xm','wh','bj']
for spot in spots:
	if spot=='qd':
		print(spot.upper())
	else:
		print(spot.title())
  • 简单例子,if后面不加括号,但是if和else后面都有冒号
car='Audi'
car.lower()=='audi'
  • python区分大小写,但可以用lower方法,比较时都当成小写,lower方法也不会改变原来的值
requested_toppings='mushrooms'
if requested_toppings !='anchovies':
	print("Hold the anchovies")
  • 不相等比较
age_0=20age_1=18
(age_0<21)and(age_1>17)
(age_0<21)or(age_1>17)
spots=['qd','cd','xm','wh','bj']
'qd' in spots  ##会返回true
'qd' not in spots  ##会返回flase
  • and检查多个条件,or检查多个条件,in检查特定值是否在里面,not in 检查特定值不在里面
squares=[]
for value in range(1,11):
	square=value**3
	squares.append(square)
print(squares)

  • 1-10的立方 value**3

使用列表的一部分——切片

players=['charles','martina','michael','florence','eli']
print(players[0:3])
  • 用方括号,加指定索引,第一个元素到索引前三个,没有索引自动从第一个开始[:4],末尾也是,最后三名[-3: ]
players=['charles','martina','michael','florence','eli']
for player in players[:3]:
	print(player.title())
  • for遍历切片,以上代码遍历前三个
my_foods=['charles','martina','michael','florence','eli']
friend_foods=my_foods[ : ]
  • 复制列表, 赋值列表比直接赋值给它意义更大,更加方便
my_foods=['charles','martina','michael','florence','eli']
friend_foods=my_foods[ : ]
my_foods.append('hi')
friend_foods.append('hello')
for my_food in my_foods:
	print(my_food)
for friend_food in friend_foods:
	print(friend_food)
  • 复制列表可以各自添加

元组

适用于存储在程序运行期间可能变化的数据集,不可变的(不能修改的)列表称为元组

dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
  • 定义元组需要用到括号,调用用方括号,元组中的值不能修改
dimensions=(200,50)
for dimension in dimensions:
	print(dimension)
  • for循环遍历元组
dimensions=(200,50)
for dimension in dimensions:
	print(dimension)
dimensions=(200,60)
for dimension in dimensions:
	print(dimension)
  • 修改元组,给元组变量赋值