1. if语句

1.1 if-elif-else结构

>>> age=12
>>> if age < 4:
...     price = 0
... elif age < 18:
...     price = 5
... else:
...     price = 10
... 
>>> price
5
  • 可省略else代码块

1.2 使用if判断列表是否为空

>>> str = []
>>> if str:
...     a = 1
... else:
...     a = 0
... 
>>> a
0

2. 用户输入

2.1 input()的简单使用

  • >>> message = input("please input your name: ")
    please input your name: Jack
    >>> message
    'Jack'
    >>> message = "please input something.\nName: "
    >>> name = input(message)
    please input something.
    Name: Jack
    >>> name
    'Jack'
  • 使用函数input()时,python将用户输入解读为字符串。可使用函数int(),将数字的字符串表示转换为数值表示
  • >>> age = input("How old are you? ")
    How old are you? 12
    >>> age
    '12'
    >>> age = int(age)
    >>> age
    12

3. while语句

3.1 使用while循环处理列表和字典

  • for循环可以遍历列表,但在for循环中不应修改列表,否则将导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环
  • >>> a = ['alice', 'brian', 'candace']
    >>> b = []
    >>> while a:
        name = a.pop(0)
        print(name)
        b.append(name)
    
        
    alice
    brian
    candace
    >>> b
    ['alice', 'brian', 'candace']
  • 利用while和remove()函数来删除列表中所有包含特定值的元素
  • >>> pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    >>> while 'cat' in pets:
        pets.remove('cat')
    
        
    >>> pets
    ['dog', 'dog', 'goldfish', 'rabbit']