3.复制列表

  1. my_foods = ['pizza', 'falafel', 'carrot cake']
  2. friend_foods = my_foods[:]

四、元组

1.元组的定义

元组就是不可变的列表。

  1. dimensions = (200, 50)
  2. print(dimensions[0])
  3. print(dimensions[1])
  4. 200
  5. 50

元组中的元素不可以被更改。

2.遍历元组中的所有值

  1. dimensions = (200, 50)
  2. for dimension in dimensions:
  3. print(dimension)
  4. 200
  5. 50

3.修改元组变量

  1. dimensions = (200, 50)
  2. print("Original dimensions:")
  3. for dimension in dimensions:
  4. print(dimension)
  5. dimensions = (400, 100)
  6. print("\nModified dimensions:")
  7. for dimension in dimensions:
  8. print(dimension)

五、if语句

1.示例

  1. cars = ['audi', 'bmw', 'subaru', 'toyota']
  2. for car in cars:
  3. if car == 'bmw':
  4. print(car.upper())
  5. else:
  6. print(car.title())

2.条件测试

python使用语义化的方法,用and表示“和”连接多个判断条件,or表示“或”,in表示“包含”,not in表示“不包含”

1.if-elif-else结构

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

else也可被省略。

3.使用if语句处理列表

1.检查特殊元素

  1. requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
  2. for requested_topping in requested_toppings:
  3. print("Adding " + requested_topping + ".")
  4. print("\nFinished making your pizza!")

2.确定列表不是空的

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

3.使用多个列表

  1. available_toppings = ['mushrooms', 'olives', 'green peppers',
  2. 'pepperoni', 'pineapple', 'extra cheese']
  3. requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
  4. for requested_topping in requested_toppings:
  5. if requested_topping in available_toppings:
  6. print("Adding " + requested_topping + ".")
  7. else:
  8. print("Sorry, we don't have " + requested_topping + ".")
  9. print("\nFinished making your pizza!")