【375】COMP 9021 相关笔记

1. Python 中的逻辑否定用 not

2. 对于下面的代码直邮输入整数才能运行,无论字符串或者浮点型都会报错

int(input('How many games should I simulate? '))

  可以通过 try 来修改,同时注意 raise 的使用

while True:
    try:
        nb_of_games = int(input('How many games should I simulate? '))
        if nb_of_games <= 0:
            raise ValueError
        print('Ok, will do!')
        break
    except ValueError:
        print('Your input is incorrect, try again.')

3. set 与 dict 都是大括号

# Checking for membership in a list
'y' in ['yes', 'y', 'no', 'n']
'Y' in ['yes', 'y', 'no', 'n']
# Checking for membership in a set
'y' in {'yes', 'y', 'no', 'n'}
'Y' in {'yes', 'y', 'no', 'n'}

'''
Curly braces are used for both literal dictionaries and literal sets. 
There is no potential conflict, except for empty set versus empty dictionary;
{} denotes an empty dictionary, not an empty set: ''' # Singleton dictionary and set, respectively type({'one': 1}) type({'one'}) # Empty dictionary and set, respectively type({}) type(set())

4. random.choice() 可以随机选择列表里面的元素

  random.randrange(),在 0 与 n 之间随机产生一个数

from random import choice
doors = ['A', 'B', 'C']
for i in range(12):
    choice(doors)

5. list.pop() 默认删除最后一个,否则按照索引删除

6. format

  To output information about the game as it is being played, it is convenient to use formatted strings; they are preceded with f and can contain pairs of curly braces that surround expressions meant to be replaced with their values. Also, though strings can be explicitly concatenated with the + operator, they can also be implicitly concatenated when they are separated with nothing but space characters, including possibly new lines:

x = 10
u = 4.5
v = 10
print(f'x is equal to {x}.'
      ' That is not all: '
      f'{u} divided by {v} equals {u / v}.'
     )
x = 123 / 321 
f'{x}'
f'{x:.0f}'
f'{x:.1f}'
f'{x:.2f}'
f'{x:.3f}'
f'{x:.4f}'
f'{x:.30f}'

7. 神奇的 * 号,乘号,可以扩展字符串,可以扩展列表

[1, 2, 3]*3
"abc"*3

猜你喜欢

转载自www.cnblogs.com/alex-bn-lee/p/10442943.html