AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第2章:FLOW CONTROL

在流程图中,开始和结束圆角矩形表示,菱形表示流控分支,矩形表示实际操作。

布尔值

布尔值包括两个常数,即TrueFalse
布尔的命名来源于数学家George Boole。

比较操作符

包括==, >, <, <=, >=, !=。不要混淆===

布尔操作符

与或非分别用and, ornot表示。

将布尔值和比较操作符组合使用

>>> (2 > 1) and ( 1 < 3)
True
>>> (2 > 1) and ( 1 < 0)
False
>>> (2 > 1) or ( 1 < 0)
True
>>> not (2 < 1)
True

有一种特殊的情形,就是0,0.0和空串’'均被认为是False。

>>> emptyString = ''
>>> not emptyString
True
>>> zero = 0
>>> not zero
True
>>> if emptyString:
...     print('OK!')
... 
>>> if not zero:
...     print('OK!')
... 
OK!

流控的元素

包括条件和代码块。
代码块的规则:

  • 代码块开始于缩进增加一级。
  • 代码块可包含其它代码块。
  • 代码块结束于缩进为0或缩进减少一级。

例如以下代码,第一个print到最后是一个代码块。余下两个print是单独的代码块。

name = 'Mary'
password = 'swordfish'
if name == 'Mary':
    print('Hello Mary')
    if password == 'swordfish':
        print('Access granted.')
    else:
        print('Wrong password.')

程序执行

从最顶端开始逐行执行,根据条件判断执行哪些代码块。

流控语句

if…elif…else

第一组是if, elifelse的组合, 这几个关键字所在的行末必须加:

if condition:
	code block
elif confition:
	code block
else:
	code block

elif可出现0到多次,else可出现0到1次。

while

第二组是while语句:

while condition:
	code block

while还可以和contiburebreak组合。

for…in…

>>> for i in (1,2,3):
...     print(i)
... 
1
2
3

>>> for i in range(1,4):
...     print(i)
... 
1
2
3

for语句也可以与和contiburebreak组合。
range的语法如下:

class range(stop)
class range(start, stop[, step])

for...in后面可接List,Set和Dictionary等,以下是Dictionary的例子:

>>> months={('1','Jan'), ('2', 'Feb')}
>>> for k,v in months:
...     print(f"Month {k} is {v}")
... 
Month 1 is Jan
Month 2 is Feb

引进模块

除内置函数外,Python中还可以引进(import)标准库(standard library),以使用其中的一系列函数。
例如:

>>> import random
>>> for i in range(5):
...     print(random.randint(1, 10))
... 
2
2
6
7
10

import的帮助见这里
主要有两种用法:

  • import module [as identifier]
  • from modele import identifier

因此,用户自己写的模块名和函数名应避免与标准库重名。

使用SYS.EXIT() 函数退出程序

import sys
if condition:
	sys.exit()

小程序: 猜数

源代码见这里

# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
    print('Take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break    # This condition is the correct guess!

if guess == secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

小程序: 石头剪刀布

以下是我重构过的程序:

import random, sys

print('ROCK, PAPER, SCISSORS')

# These variables keep track of the number of wins, losses, and ties.
wins = 0
losses = 0
ties = 0

gestures = {'r':'ROCK', 'p':'PAPER', 's':'SCISSORS'}
wincases=['rs', 'sp', 'pr']

while True: # The main game loop.
    print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
    while True: # The player input loop.
        print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
        playerMove = input()
        if playerMove == 'q':
            sys.exit() # Quit the program.
        if playerMove in gestures.keys():
            break # Break out of the player input loop.
        print('Type one of r, p, s, or q.')

    # Display what the player chose:
    print(f'{gestures.get(playerMove)} versus...')

    # Display what the computer chose:
    computerMove = random.choice(['r', 'p', 's'])
    print(f'{gestures.get(computerMove)}')

    # Display and record the win/loss/tie:
    if playerMove == computerMove:
        print('It is a tie!')
        ties = ties + 1
    elif (playerMove + computerMove) in wincases:
        print('You win!')
        wins = wins + 1
    else:
        print('You lose!')

单词

errand - 差事,差使
tie - 平局,也有用draw的

发布了370 篇原创文章 · 获赞 43 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/stevensxiao/article/details/104086547
今日推荐