Python 小型项目大全 16~20

这篇具有很好参考价值的文章主要介绍了Python 小型项目大全 16~20。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

#16 钻石

原文:http://inventwithpython.com/bigbookpython/project16.html

Python 小型项目大全 16~20

这个程序的特点是一个小算法,用于绘制各种尺寸的 ASCII 艺术画钻石。它包含绘制轮廓或你指定大小的填充式菱形的功能。这些功能对于初学者来说是很好的练习;试着理解钻石图背后的图案,因为它们的尺寸越来越大。

运行示例

当您运行diamonds.py时,输出将如下所示:

Diamonds, by Al Sweigart email@protected

/\
\/

/\
\/

 /\
/  \
\  /
 \/

 /\
//\\
\\//
 \/

  /\
 /  \
/    \
\    /
 \  /
  \/

  /\
 //\\
///\\\
\\\///
 \\//
  \/
`--snip--`

工作原理

自己创建这个程序的一个有用的方法是首先在你的编辑器中“画”几个大小的钻石,然后随着钻石变大,找出它们遵循的模式。这项技术将帮助您认识到菱形轮廓的每一行都有四个部分:前导空格数、外部正斜杠、内部空格数和外部反斜杠。实心钻石有几个内部正斜线和反斜线,而不是内部空间。破解这个模式就是我写diamonds.py的方法。

r"""Diamonds, by Al Sweigart email@protected
Draws diamonds of various sizes.
View this code at https://nostarch.com/big-book-small-python-projects
                          /\       /\
                         /  \     //\\
           /\     /\    /    \   ///\\\
          /  \   //\\  /      \ \\\\
/\   /\  /    \ ///\\\ \      / \\\\
/  \ //\\ \    / \\\///  \    /   \\\///
\  / \\//  \  /   \\//    \  /     \\//
 \/   \/    \/     \/      \/       \/
Tags: tiny, beginner, artistic"""

def main():
    print('Diamonds, by Al Sweigart email@protected')

    # Display diamonds of sizes 0 through 6:
    for diamondSize in range(0, 6):
        displayOutlineDiamond(diamondSize)
        print()  # Print a newline.
        displayFilledDiamond(diamondSize)
        print()  # Print a newline.


def displayOutlineDiamond(size):
    # Display the top half of the diamond:
    for i in range(size):
        print(' ' * (size - i - 1), end='')  # Left side space.
        print('/', end='')  # Left side of diamond.
        print(' ' * (i * 2), end='')  # Interior of diamond.
        print('\\')  # Right side of diamond.

    # Display the bottom half of the diamond:
    for i in range(size):
        print(' ' * i, end='')  # Left side space.
        print('\\', end='')  # Left side of diamond.
        print(' ' * ((size - i - 1) * 2), end='')  # Interior of diamond.
        print('/')  # Right side of diamond.


def displayFilledDiamond(size):
    # Display the top half of the diamond:
    for i in range(size):
        print(' ' * (size - i - 1), end='')  # Left side space.
        print('/' * (i + 1), end='')  # Left half of diamond.
        print('\\' * (i + 1))  # Right half of diamond.

    # Display the bottom half of the diamond:
    for i in range(size):
        print(' ' * i, end='')  # Left side space.
        print('\\' * (size - i), end='')  # Left side of diamond.
        print('/' * (size - i))  # Right side of diamond.


# If this program was run (instead of imported), run the game:
if __name__ == '__main__':
    main() 

在输入源代码并运行几次之后,尝试对其进行实验性的修改。你也可以自己想办法做到以下几点:

  • 创建其他形状:三角形,矩形和菱形。
  • 将形状输出到文本文件,而不是屏幕。

探索程序

试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。文章来源地址https://www.toymoban.com/news/detail-411694.html

  1. 把第 31 行的print('\\')改成print('@')会怎么样?
  2. 把第 30 行的print(' ' * (i * 2), end='')改成print('@' * (i * 2), end='')会怎么样?
  3. 把第 18 行的range(0, 6)改成range(0, 30)会怎么样?
  4. 在第 34 行或第 49 行删除或注释掉for i in range(size):会发生什么?

#17 骰子数学

原文:http://inventwithpython.com/bigbookpython/project17.html

Python 小型项目大全 16~20

这个数学测验程序掷出两到六个骰子,你必须尽快把它们的边加起来。但是这个程序不仅仅是自动的闪存卡;它将骰子的正面画到屏幕上随机的地方。当你练习算术时,ASCII 艺术画方面增加了一个有趣的转折。

运行示例

当您运行dicemath.py时,输出如下:

Dice Math, by Al Sweigart email@protected

Add up the sides of all the dice displayed on the screen. You have
30 seconds to answer as many as possible. You get 4 points for each
correct answer and lose 1 point for each incorrect answer.

Press Enter to begin...
                                     +-------+
                                     | O   O |
                                     |   O   |
                                     | O   O |
                                     +-------+

                                  +-------+
            +-------+             | O   O |  +-------+
            |     O |             |       |  | O     |
            |       |             | O   O |  |       |
            | O     |             +-------+  |     O |
            +-------+                        +-------+
Enter the sum: 13
`--snip--`

工作原理

屏幕上的骰子由存储在canvas变量中的字典表示。在 Python 中,元组类似于列表,但是它们的内容不能改变。该字典的关键字是标记骰子左上角位置的(x, y)元组,而值是ALL_DICE中的“骰子元组”之一。您可以在第 28 到 80 行中看到,每个骰子元组包含一个字符串列表,它以图形方式表示一个可能的骰子面,以及骰子面上有多少点数的整数。该程序使用这些信息来显示骰子并计算它们的总和。

第 174 到 177 行将canvas字典中的数据呈现在屏幕上,其方式类似于项目 13“康威的生命游戏”在屏幕上呈现单元格的方式。

"""Dice Math, by Al Sweigart email@protected
A flash card addition game where you sum the total on random dice rolls.
View this code at https://nostarch.com/big-book-small-python-projects
Tags: large, artistic, game, math"""

import random, time

# Set up the constants:
DICE_WIDTH = 9
DICE_HEIGHT = 5
CANVAS_WIDTH = 79
CANVAS_HEIGHT = 24 - 3  # -3 for room to enter the sum at the bottom.

# The duration is in seconds:
QUIZ_DURATION = 30  # (!) Try changing this to 10 or 60.
MIN_DICE = 2  # (!) Try changing this to 1 or 5.
MAX_DICE = 6  # (!) Try changing this to 14.

# (!) Try changing these to different numbers:
REWARD = 4  # (!) Points awarded for correct answers.
PENALTY = 1  # (!) Points removed for incorrect answers.
# (!) Try setting PENALTY to a negative number to give points for
# wrong answers!

# The program hangs if all of the dice can't fit on the screen:
assert MAX_DICE <= 14

D1 = (['+-------+',
      '|       |',
      '|   O   |',
      '|       |',
      '+-------+'], 1)

D2a = (['+-------+',
       '| O     |',
       '|       |',
       '|     O |',
       '+-------+'], 2)

D2b = (['+-------+',
       '|     O |',
       '|       |',
       '| O     |',
       '+-------+'], 2)

D3a = (['+-------+',
       '| O     |',
       '|   O   |',
       '|     O |',
       '+-------+'], 3)

D3b = (['+-------+',
       '|     O |',
       '|   O   |',
       '| O     |',
       '+-------+'], 3)

D4 = (['+-------+',
      '| O   O |',
      '|       |',
      '| O   O |',
      '+-------+'], 4)

D5 = (['+-------+',
      '| O   O |',
      '|   O   |',
      '| O   O |',
      '+-------+'], 5)

D6a = (['+-------+',
       '| O   O |',
       '| O   O |',
       '| O   O |',
       '+-------+'], 6)

D6b = (['+-------+',
       '| O O O |',
       '|       |',
       '| O O O |',
       '+-------+'], 6)

ALL_DICE = [D1, D2a, D2b, D3a, D3b, D4, D5, D6a, D6b]

print('''Dice Math, by Al Sweigart email@protected

Add up the sides of all the dice displayed on the screen. You have
{} seconds to answer as many as possible. You get {} points for each
correct answer and lose {} point for each incorrect answer.
'''.format(QUIZ_DURATION, REWARD, PENALTY))
input('Press Enter to begin...')

# Keep track of how many answers were correct and incorrect:
correctAnswers = 0
incorrectAnswers = 0
startTime = time.time()
while time.time() < startTime + QUIZ_DURATION:  # Main game loop.
   # Come up with the dice to display:
   sumAnswer = 0
   diceFaces = []
    for i in range(random.randint(MIN_DICE, MAX_DICE)):
        die = random.choice(ALL_DICE)
        # die[0] contains the list of strings of the die face:
        diceFaces.append(die[0])
        # die[1] contains the integer number of pips on the face:
        sumAnswer += die[1]

    # Contains (x, y) tuples of the top-left corner of each die.
    topLeftDiceCorners = []

    # Figure out where dice should go:
    for i in range(len(diceFaces)):
        while True:
            # Find a random place on the canvas to put the die:
            left = random.randint(0, CANVAS_WIDTH  - 1 - DICE_WIDTH)
            top  = random.randint(0, CANVAS_HEIGHT - 1 - DICE_HEIGHT)

            # Get the x, y coordinates for all four corners:
            #      left
            #      v
            #top > +-------+ ^
            #      | O     | |
            #      |   O   | DICE_HEIGHT (5)
            #      |     O | |
            #      +-------+ v
            #      <------->
            #      DICE_WIDTH (9)
            topLeftX = left
            topLeftY = top
            topRightX = left + DICE_WIDTH
            topRightY = top
            bottomLeftX = left
            bottomLeftY = top + DICE_HEIGHT
            bottomRightX = left + DICE_WIDTH
            bottomRightY = top + DICE_HEIGHT

            # Check if this die overlaps with previous dice.
            overlaps = False
            for prevDieLeft, prevDieTop in topLeftDiceCorners:
                prevDieRight = prevDieLeft + DICE_WIDTH
                prevDieBottom = prevDieTop + DICE_HEIGHT
                # Check each corner of this die to see if it is inside
                # of the area the previous die:
                for cornerX, cornerY in ((topLeftX, topLeftY),
                                         (topRightX, topRightY),
                                         (bottomLeftX, bottomLeftY),
                                         (bottomRightX, bottomRightY)):
                    if (prevDieLeft <= cornerX < prevDieRight
                        and prevDieTop <= cornerY < prevDieBottom):
                            overlaps = True
            if not overlaps:
                # It doesn't overlap, so we can put it here:
                topLeftDiceCorners.append((left, top))
                break

    # Draw the dice on the canvas:

    # Keys are (x, y) tuples of ints, values the character at that
    # position on the canvas:
    canvas = {}
    # Loop over each die:
    for i, (dieLeft, dieTop) in enumerate(topLeftDiceCorners):
        # Loop over each character in the die's face:
        dieFace = diceFaces[i]
        for dx in range(DICE_WIDTH):
            for dy in range(DICE_HEIGHT):
                # Copy this character to the correct place on the canvas:
                canvasX = dieLeft + dx
                canvasY = dieTop + dy
                # Note that in dieFace, a list of strings, the x and y
                # are swapped:
                canvas[(canvasX, canvasY)] = dieFace[dy][dx]

    # Display the canvas on the screen:
    for cy in range(CANVAS_HEIGHT):
        for cx in range(CANVAS_WIDTH):
            print(canvas.get((cx, cy), ' '), end='')
        print()  # Print a newline.

    # Let the player enter their answer:
    response = input('Enter the sum: ').strip()
    if response.isdecimal() and int(response) == sumAnswer:
        correctAnswers += 1
    else:
        print('Incorrect, the answer is', sumAnswer)
        time.sleep(2)
        incorrectAnswers += 1

# Display the final score:
score = (correctAnswers * REWARD) - (incorrectAnswers * PENALTY)
print('Correct:  ', correctAnswers)
print('Incorrect:', incorrectAnswers)
print('Score:    ', score) 

在输入源代码并运行几次之后,尝试对其进行实验性的修改。标有(!)的注释对你可以做的小改变有建议。你也可以自己想办法做到以下几点:

  • 重新设计 ASCII 艺术画骰子面。
  • 添加七点、八点或九点的骰子点数。

探索程序

试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。

  1. 如果把 82 行改成ALL_DICE = [D1]会怎么样?
  2. 如果把 176 行的get((cx, cy), ' ')改成get((cx, cy), '.')会怎么样?
  3. 如果把 182 行的correctAnswers += 1改成correctAnswers += 0会怎么样?
  4. 如果删除或注释掉第 93 行的correctAnswers = 0,会得到什么错误信息?

十八、滚动骰子

原文:http://inventwithpython.com/bigbookpython/project18.html

Python 小型项目大全 16~20

地下城&龙和其他桌面角色扮演游戏使用特殊的骰子,可以有 4、8、10、12 甚至 20 面。这些游戏也有一个特定的符号来指示掷哪个骰子。例如,3d6是指掷出三个六面骰子,而1d10+2是指掷出一个十面骰子,并在掷骰子时增加两点奖励。这个程序模拟掷骰子,以防你忘记带自己的。它还可以模拟物理上不存在的滚动骰子,如 38 面骰子。

运行示例

当您运行diceroller.py时,输出将如下所示:

Dice Roller, by Al Sweigart email@protected
`--snip--`
> 3d6
7 (3, 2, 2)
> 1d10+2
9 (7, +2)
> 2d38-1
32 (20, 13, -1)
> 100d6
364 (3, 3, 2, 4, 2, 1, 4, 2, 4, 6, 4, 5, 4, 3, 3, 3, 2, 5, 1, 5, 6, 6, 6, 4, 5, 5, 1, 5, 2, 2, 2, 5, 1, 1, 2, 1, 4, 5, 6, 2, 4, 3, 4, 3, 5, 2, 2, 1, 1, 5, 1, 3, 6, 6, 6, 6, 5, 2, 6, 5, 4, 4, 5, 1, 6, 6, 6, 4, 2, 6, 2, 6, 2, 2, 4, 3, 6, 4, 6, 4, 2, 4, 3, 3, 1, 6, 3, 3, 4, 4, 5, 5, 5, 6, 2, 3, 6, 1, 1, 1)
`--snip--`

工作原理

这个程序中的大部分代码都致力于确保用户输入的内容格式正确。实际的随机掷骰子本身是对random.randint()的简单调用。这个函数没有偏见:传递给它的范围内的每个整数都有可能被返回。这使得random.randint()非常适合模拟掷骰子。

"""Dice Roller, by Al Sweigart email@protected
Simulates dice rolls using the Dungeons & Dragons dice roll notation.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: short, simulation"""

import random, sys

print('''Dice Roller, by Al Sweigart email@protected

Enter what kind and how many dice to roll. The format is the number of
dice, followed by "d", followed by the number of sides the dice have.
You can also add a plus or minus adjustment.

Examples:
  3d6 rolls three 6-sided dice
  1d10+2 rolls one 10-sided die, and adds 2
  2d38-1 rolls two 38-sided die, and subtracts 1
  QUIT quits the program
''')

while True:  # Main program loop:
    try:
        diceStr = input('> ')  # The prompt to enter the dice string.
        if diceStr.upper() == 'QUIT':
            print('Thanks for playing!')
            sys.exit()

        # Clean up the dice string:
        diceStr = diceStr.lower().replace(' ', '')

        # Find the "d" in the dice string input:
        dIndex = diceStr.find('d')
        if dIndex == -1:
            raise Exception('Missing the "d" character.')

        # Get the number of dice. (The "3" in "3d6+1"):
        numberOfDice = diceStr[:dIndex]
        if not numberOfDice.isdecimal():
            raise Exception('Missing the number of dice.')
        numberOfDice = int(numberOfDice)

        # Find if there is a plus or minus sign for a modifier:
        modIndex = diceStr.find('+')
        if modIndex == -1:
            modIndex = diceStr.find('-')

        # Find the number of sides. (The "6" in "3d6+1"):
        if modIndex == -1:
            numberOfSides = diceStr[dIndex + 1 :]
        else:
            numberOfSides = diceStr[dIndex + 1 : modIndex]
        if not numberOfSides.isdecimal():
            raise Exception('Missing the number of sides.')
        numberOfSides = int(numberOfSides)

        # Find the modifier amount. (The "1" in "3d6+1"):
        if modIndex == -1:
            modAmount = 0
        else:
            modAmount = int(diceStr[modIndex + 1 :])
            if diceStr[modIndex] == '-':
                # Change the modification amount to negative:
                modAmount = -modAmount

        # Simulate the dice rolls:
        rolls = []
        for i in range(numberOfDice):
            rollResult = random.randint(1, numberOfSides)
            rolls.append(rollResult)

        # Display the total:
        print('Total:', sum(rolls) + modAmount, '(Each die:', end='')

        # Display the individual rolls:
        for i, roll in enumerate(rolls):
            rolls[i] = str(roll)
        print(', '.join(rolls), end='')

        # Display the modifier amount:
        if modAmount != 0:
            modSign = diceStr[modIndex]
            print(', {}{}'.format(modSign, abs(modAmount)), end='')
        print(')')

    except Exception as exc:
        # Catch any exceptions and display the message to the user:
        print('Invalid input. Enter something like "3d6" or "1d10+2".')
        print('Input was invalid because: ' + str(exc))
        continue  # Go back to the dice string prompt. 

在输入源代码并运行几次之后,尝试对其进行实验性的修改。你也可以自己想办法做到以下几点:

  • 添加一个乘法修饰符来补充加法和减法修饰符。
  • 增加自动移除最低模具辊的能力。

探索程序

试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。

  1. 如果删除或注释掉第 69 行的rolls.append(rollResult)会发生什么?
  2. 如果把第 69 行的rolls.append(rollResult)改成rolls.append(-rollResult)会怎么样?
  3. 如果删除或注释掉第 77 行的print(', '.join(rolls), end='')会怎么样?
  4. 如果不掷骰子而什么都不输入会怎么样?

十九、数字时钟

原文:http://inventwithpython.com/bigbookpython/project19.html

Python 小型项目大全 16~20

这个程序显示一个带有当前时间的数字时钟。第六十四个项目的sevseg.py模块“七段显示模块”为每个数字生成图形,而不是直接呈现数字字符。这个项目类似于项目 14,“倒计时”

运行示例

当您运行digitalclock.py时,输出将如下所示:

 __   __       __   __       __   __
|  | |__|  *   __|  __|  *   __| |__
|__|  __|  *   __|  __|  *   __| |__|

Press Ctrl-C to quit.

工作原理

数字时钟程序看起来类似于项目 14,“倒计时。”他们不仅都导入了sevseg.py模块,还必须用splitlines()方法拆分由sevseg.getSevSegStr()返回的多行字符串。这允许我们在时钟的小时、分钟和秒部分的数字之间放置一个由星号组成的冒号。将这段代码与倒计时中的代码进行比较,看看有哪些相似之处,有哪些不同之处。

"""Digital Clock, by Al Sweigart email@protected
Displays a digital clock of the current time with a seven-segment
display. Press Ctrl-C to stop.
More info at https://en.wikipedia.org/wiki/Seven-segment_display
Requires sevseg.py to be in the same folder.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, artistic"""

import sys, time
import sevseg  # Imports our sevseg.py program.

try:
    while True:  # Main program loop.
        # Clear the screen by printing several newlines:
        print('\n' * 60)

        # Get the current time from the computer's clock:
        currentTime = time.localtime()
        # % 12 so we use a 12-hour clock, not 24:
        hours = str(currentTime.tm_hour % 12)
        if hours == '0':
            hours = '12'  # 12-hour clocks show 12:00, not 00:00.
        minutes = str(currentTime.tm_min)
        seconds = str(currentTime.tm_sec)

        # Get the digit strings from the sevseg module:
        hDigits = sevseg.getSevSegStr(hours, 2)
        hTopRow, hMiddleRow, hBottomRow = hDigits.splitlines()

        mDigits = sevseg.getSevSegStr(minutes, 2)
        mTopRow, mMiddleRow, mBottomRow = mDigits.splitlines()

        sDigits = sevseg.getSevSegStr(seconds, 2)
        sTopRow, sMiddleRow, sBottomRow = sDigits.splitlines()

        # Display the digits:
        print(hTopRow    + '     ' + mTopRow    + '     ' + sTopRow)
        print(hMiddleRow + '  *  ' + mMiddleRow + '  *  ' + sMiddleRow)
        print(hBottomRow + '  *  ' + mBottomRow + '  *  ' + sBottomRow)
        print()
        print('Press Ctrl-C to quit.')

        # Keep looping until the second changes:
        while True:
            time.sleep(0.01)
            if time.localtime().tm_sec != currentTime.tm_sec:
                break
except KeyboardInterrupt:
    print('Digital Clock, by Al Sweigart email@protected')
    sys.exit()  # When Ctrl-C is pressed, end the program. 

探索程序

试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。

  1. 如果把第 45 行的time.sleep(0.01)改成time.sleep(2)会怎么样?
  2. 如果把第 27、30、33 行的2改成1会怎么样?
  3. 如果删除或注释掉第 15 行的print('\n' * 60)会发生什么?
  4. 如果删除或注释掉第 10 行的import sevseg,会得到什么错误信息?

二十、数字雨

原文:http://inventwithpython.com/bigbookpython/project20.html

Python 小型项目大全 16~20

这个程序模仿了科幻电影《黑客帝国》中的“数字雨”可视化效果。随机的二进制“雨”珠从屏幕底部流上来,创造了一个很酷的、黑客般的可视化效果。(不幸的是,由于文本随着屏幕向下滚动而移动的方式,如果不使用bext这样的模块,就不可能让流向下移动。)

运行示例

当您运行digitalstream.py时,输出将如下所示:

Digital Stream Screensaver, by Al Sweigart email@protected
Press Ctrl-C to quit.
                     0                      0
                     0                      0
   1            0    0    1               1 0                             1
   0            0    0    1         0     0 0        0                    0
   0            1    0    0         0     1 0 0      1               0    1
   0            1    0    0         1     011 1      1               0    1 0
   0            1    0    0         0     000 11     0               0  1 1 0
   1     1      0 1  0    1         1     110 10  1  0               1  0 1 0
         1    101 0       0         1     000 11  1  1               11 1 1 1
         0    100 1       0               11  00  0  1               01     0
      1  1    001 1       1               0   1  10  0               10     0
      0  0    010 0       1                   1  11  11              0      0
`--snip--`

工作原理

像项目 15,“深坑”,这个程序使用由print()调用引起的滚动来创建动画。在列列表中,每一列都由一个整数表示:columns[0]是最左边一列的整数,columns[1]是右边一列的整数,依此类推。程序最初将这些整数设置为0,这意味着它打印' '(一个空格字符串)而不是该列中的流。随机地,它将每个整数改变为一个在MIN_STREAM_LENGTHMAX_STREAM_LENGTH之间的值。每打印一行,该整数就减少1。只要一列的整数大于0,程序就会在该列中打印一个随机的10。这会产生您在屏幕上看到的“数字雨”效果。

"""Digital Stream, by Al Sweigart email@protected
A screensaver in the style of The Matrix movie's visuals.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, artistic, beginner, scrolling"""

import random, shutil, sys, time

# Set up the constants:
MIN_STREAM_LENGTH = 6  # (!) Try changing this to 1 or 50.
MAX_STREAM_LENGTH = 14  # (!) Try changing this to 100.
PAUSE = 0.1  # (!) Try changing this to 0.0 or 2.0.
STREAM_CHARS = ['0', '1']  # (!) Try changing this to other characters.

# Density can range from 0.0 to 1.0:
DENSITY = 0.02  # (!) Try changing this to 0.10 or 0.30.

# Get the size of the terminal window:
WIDTH = shutil.get_terminal_size()[0]
# We can't print to the last column on Windows without it adding a
# newline automatically, so reduce the width by one:
WIDTH -= 1

print('Digital Stream, by Al Sweigart email@protected')
print('Press Ctrl-C to quit.')
time.sleep(2)

try:
    # For each column, when the counter is 0, no stream is shown.
    # Otherwise, it acts as a counter for how many times a 1 or 0
    # should be displayed in that column.
    columns = [0] * WIDTH
    while True:
        # Set up the counter for each column:
        for i in range(WIDTH):
            if columns[i] == 0:
                if random.random() <= DENSITY:
                    # Restart a stream on this column.
                    columns[i] = random.randint(MIN_STREAM_LENGTH,
                                                MAX_STREAM_LENGTH)

            # Display an empty space or a 1/0 character.
            if columns[i] > 0:
                print(random.choice(STREAM_CHARS), end='')
                columns[i] -= 1
            else:
                print(' ', end='')
        print()  # Print a newline at the end of the row of columns.
        sys.stdout.flush()  # Make sure text appears on the screen.
        time.sleep(PAUSE)
except KeyboardInterrupt:
    sys.exit()  # When Ctrl-C is pressed, end the program. 

在输入源代码并运行几次之后,尝试对其进行实验性的修改。标有(!)的注释对你可以做的小改变有建议。你也可以自己想办法做到以下几点:

  • 包括除 1 和 0 之外的字符。
  • 包括线以外的形状,包括矩形、三角形和菱形。

探索程序

试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。

  1. 如果把第 46 行的print(' ', end='')改成print('.', end='')会怎么样?
  2. 如果将第 11 行的PAUSE = 0.1改为PAUSE = -0.1,会得到什么错误信息?
  3. 如果把第 42 行的columns[i] > 0改成columns[i] < 0会怎么样?
  4. 如果把第 42 行的columns[i] > 0改成columns[i] <= 0会怎么样?
  5. 如果把第 44 行的columns[i] -= 1改成columns[i] += 1会怎么样?

到了这里,关于Python 小型项目大全 16~20的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序小型项目案例

    今天我来讲一下一组数据如果对其进行了更改但是页面不跟着进行同步渲染怎么办 其实呢就是一个 新闻列表 ,然后 上面渲染 的有 图片 ,有 文章标题 有 文章内容 ,还有文章 发布时间 ,还有一个 是否收藏按钮 ,一种比较 常见 的形式。 让我们先看一下要实现的效果 下面

    2024年02月08日
    浏览(25)
  • 小型项目中的好帮手,ZeroMQ

    ZeroMQ是一个高性能、异步、消息传递库,它可以在不同的应用程序之间进行快速、可靠的通信。它支持多种消息传递模式,包括请求-响应、发布-订阅和推送-拉取。ZeroMQ还提供了多种语言的API,包括C、C++、Python和Java,Golang 还有 Rust 等。 ZeroMQ的基本概念和原理包括消息传递模

    2024年02月06日
    浏览(39)
  • 中小型项目请求限流设计

    请求限流是一种控制API或其他Web服务的流量的技术。它的目的是限制客户端对服务器发出的请求的数量或速率,以防止服务器过载或响应时间变慢,从而提高系统的可用性和稳定性。 按IP、用户、全局限流 基于不同实现的限流设计(基于Redis或者LRU缓存) 基于注解标注哪些接

    2023年04月10日
    浏览(39)
  • 【Python】WebUI自动化—Selenium的下载和安装、基本用法、项目实战(16)

    Selenium 是一个用于测试 Web 应用程序 的自动化测试工具,它直接运行在 浏览器 中,实现了对浏览器的自动化操作,它支持所有主流的浏览器,包括 IE,Firefox,Safari,Chrome 等。 -支持所有主流平台(如, Windows、Linux、IOS、Android、Edge、Opera 等) 实现了诸多 自动化功能 ,比如

    2024年02月08日
    浏览(31)
  • 精选了20个Python实战项目(附源码),拿走就用!零基础练手不二项目!

    Python是目前最好的编程语言之一。由于其可读性和对初学者的友好性,已被广泛使用。 那么要想学会并掌握Python,可以实战的练习项目是必不可少的。 接下来,我将给大家介绍20个非常实用的Python项目,帮助大家更好的学习Python。 大家也可根据项目的需求,自己构建解决方

    2024年02月13日
    浏览(23)
  • 小型局域网规划及配置(实训项目)

    实训项目说明 :是一个小型的局域网规划,涉及到的知识点有VLAN、STP、DHCP、ACL、NAT、OSPF、静态路由等的配置。这里做了一些修改,增加了LSW2与AR1之间的连线,在LSW1与LSW2之间配置了VRRP。 所有命令第一次出现使用全拼,再次出现的命令都是用简写 以下是原本的拓扑图 以下

    2024年02月11日
    浏览(30)
  • 使用Ensp搭建中小型企业网络项目

    项目总结 项目拓扑如下图: 项目要求1:要求企业网络内部所有设备能够互相通信IP地址规划设计,网络设备配置IP地址;为设备配置路由协议(ospf),让其有能够到达网络的路径; 项目要求2:不同部门之间的用户数据互相隔离,但能够实现通信;创建VLAN并将不同部门的主机划

    2024年02月09日
    浏览(42)
  • 简单的小型C++项目怎么用CMAKE进行管理

    根目录下共有两个文件夹,分别为include、src,有两个文件,分别为CMakeLists.txt和main.cpp 可以看出,include了func.h,且func.h的声明在include文件夹下,定义在src文件夹下的func.cpp中 add_library 表示创建了一个静态库,名字是func,用的是func.cpp这个文件 target_include_directories 表示让 ..

    2023年04月22日
    浏览(38)
  • go脚手架,可快速构建一个go小型项目

    1、项目技术使用 gin+sqlx+redis ,后续会引入需要的技术 2、项目目的 当我们有一个新的 idea 需要马上付出实践,用于构建小型项目,直接上手写接口即可,主要为了大学生可以快速完成作业,不需要搭建环境,本项目暂时完成不了复杂的业务哦~ 3、项目介绍 脚手架架构分为

    2024年02月09日
    浏览(46)
  • 陕西某小型水库雨水情测报及大坝安全监测项目案例

    项目背景       根据《陕西省小型病险水库除险加固项目管理办法》、《陕西省小型水库雨水情测报和大坝安全监测设施建设与运行管理办法》的要求,为保障水库安全运行,对全省小型病险水库除险加固,建设完善雨水情测报、监测预警、防汛道路、通讯设备、管理用房

    2024年02月05日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包