三、顺序 选择 循环

选择

  1. 真值/假值

    假(7种):False(标准真值)、None、0、[](空列表)、()(空元组)、‘’(或"",空字符串)、{}(空集合或空字典)

    真(无数种):其他所有(包括True(标准真值))

    >>>bool('I think, therefore I am')
    True
    >>>bool(42)
    True
    >>>bool('')
    False
    >>>bool(0)
    False
    
  2. if else

    num = int(input('Enter a number: '))
    if num > 0:
        print('This number is positive')
    elif num < 0:
        print('This number is negative')
    else:
        print('This number is zero')
    
  3. 条件运算符(相当于:?)

    status = "friend" if name.endswith("Gumby") else "stranger"
    
  4. 比较运算符

    表达式描述
    x is yx和y是同一个对象
    x is not yx和y是不同的对象
    x in yx是容器(如序列)y的成员
    x not in yx不是容器(如序列)y的成员

    链式比较

    >>>if 0 < key < 2:
    ...    print('0 < key < 2')    
    0 < key < 2
    

    列表比较

    >>>[1, 2] < [2, 1]
    True
    >>>[2, [1, 4]] < [2, [1, 5]]
    True
    

循环

  1. for循环

    >>>words = ['this', 'is', 'an', 'ex', 'parrot']
    >>>for word in words:
    ...    print(word)
    
    >>>for number in range(1, 101):
        print(number)
        
    >>>d = {'x':1, 'y':2, 'z':3}
    >>>for key in d:
    ...    print(key, 'corresponds to', d[key])
    ...    
    x corresponds to 1
    y corresponds to 2
    z corresponds to 3
    
    # 序列解包
    >>>for key, value in d.items():
    ...    print(key, 'corresponds to', value)
    ...    
    x corresponds to 1
    y corresponds to 2
    z corresponds to 3
    
    # 使用zip
    >>>list(zip(names, ages))
    [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
    >>>for name, age in zip(names, ages):
    ...    print(name, 'is', age, 'years old')
    ...    
    anne is 12 years old
    beth is 45 years old
    george is 32 years old
    damon is 102 years old
    
    # 使用enumerate
    for index, string in enumerate(strings):
        if 'xxx' in string:
            strings[index] = '[censored]'
    
  2. while循环

    >>>x = 1
    >>>while x <= 100:
    ...    print(x)
    ...    x += 1
    
    name = ''
    while not name:
        name = input('Please enter your name: ')
    print('Hello, {}!'.format(name))
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MallocLu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值