Python实验 —— 图形化编程入门案例

2023-12-16 16:43:47

实验目的

(1)熟悉 PYTHON 的语法格式
(2)熟练使用集成开发环境 SPYDER 或者 PyCharm
(3)熟练 PYTHON 基本数据类型
(4)学会 Python 图形编程与库编程

实验内容

(1)蟒蛇绘制程序。
(2)计算 Pi 值。
(3)树的绘制
(4)词频统计
(5)绘制艺术图

实验结果

蟒蛇绘制程序

import turtle

def draw_curvy_snake():
    # 创建窗口
    window = turtle.Screen()
    window.bgcolor("white")

    # 创建一个乌龟对象,并设置形状、颜色、速度
    snake = turtle.Turtle()
    snake.shape("square")
    snake.color("green")
    snake.speed(2)

    # 设置每个身体部分的长度和旋转角度
    body_length = 20
    curve_angle = 30  # 角度

    # 循环绘制10个身体部分
    for _ in range(10):
        snake.forward(body_length)  # 向前移动
        snake.right(curve_angle)    # 右旋转一定角度

    # 当单击窗口时退出程序
    window.exitonclick()

if __name__ == "__main__":
    draw_curvy_snake()

这是一个使用Python的Turtle库绘制一个弯曲形状的蛇的简单程序。这个程序使用Turtle库创建了一个窗口,并在窗口中绘制了一个由10个身体部分组成的弯曲形状的绿色蛇。每个身体部分的长度是20,而每次移动后,乌龟对象向右旋转30度,从而形成弯曲的效果。程序在绘制完成后等待用户单击窗口来退出。

计算Pi值

from math import sqrt
from tqdm import tqdm
from random import random
import time

DARTS = 10000

def calculate_pi():
    hits = 0.0
    t = time.perf_counter()
    
    for i in tqdm(range(1, DARTS + 1)):
        # 在单位正方形内随机生成点的坐标
        x, y = random(), random()
        
        # 计算点到原点的距离
        dist = sqrt(x ** 2 + y ** 2)
        
        # 判断点是否在圆内
        if dist <= 1.0:
            hits += 1
        
        # 用于显示进度的信息
        a = '*' * i
        b = '.' * (DARTS + 1 - i)
        c = (i / DARTS) * 100
        t -= time.perf_counter()
        time.sleep(0.00001)

    # 根据蒙特卡洛方法估算π值
    pi = 4 * (hits / DARTS)
    
    # 打印结果和运行时间信息
    print("估算的Pi值是{}.".format(pi))
    print("\t{:^3.0f}%[{}->{}]{:.2f}s".format(c, a, b, -t), end='')
    print("运行时间是:{:.5f}s".format(time.perf_counter()))

if __name__ == '__main__':
    calculate_pi()

这是一个用蒙特卡洛方法估算π值的简单程序,同时使用了tqdm库来显示进度条。该程序通过在单位正方形内生成随机点,然后判断这些点是否落在半径为1的圆内,从而使用蒙特卡洛方法估算π值。tqdm库用于显示循环进度条,而time库用于测量运行时间。

树的绘制

import json
import os
from pyecharts import options as opts
from pyecharts.charts import Page, Tree

def create_tree():
    # 定义树状图的数据结构
    data = [
        {
            "children": [
                {"name": "B"},
                {
                    "children": [
                        {"children": [{"name": "I"}], "name": "E"},
                        {"name": "F"},
                    ],
                    "name": "C",
                },
                {
                    "children": [
                        {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                        {"name": "H"},
                    ],
                    "name": "D",
                },
            ],
            "name": "A",
        }
    ]

    # 创建树状图对象并添加数据
    tree = (
        Tree()
            .add("", data)
            .set_global_opts(title_opts=opts.TitleOpts(title="Tree-基本示例"))
    )

    # 将树状图保存为HTML文件
    tree.render()

if __name__ == '__main__':
    create_tree()

这是一个使用pyecharts库创建树状图(Tree Chart)的简单程序。这个程序使用pyecharts库中的Tree类创建了一个树状图,其中data变量定义了树的结构。根据数据结构,树的根节点是"A",有三个子节点"B"、“C"和"D”,而"C"节点又有两个子节点"E"和"F",“D"节点有两个子节点"G"和"H”。程序最后将树状图保存为HTML文件,并在浏览器中打开以查看结果。

词频统计

# -*- coding: utf-8 -*-


import time
from collections import defaultdict, Counter
from functools import wraps


text = """My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you've bestowed, mindful of the sacrifices borne by our ancestors.
I thank President Bush for his service to our nation -- (applause) -- as well as the generosity and cooperation he has shown throughout this transition.
Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often, the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because we, the people, have remained faithful to the ideals of our forebears and true to our founding documents.
So it has been; so it must be with this generation of Americans.
That we are in the midst of crisis is now well+++ understood. Our nation is at war against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost, jobs shed, businesses shuttered. Our health care is too costly, our schools fail too many -- and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet.
These are the indicators of crisis, subject to data and statistics. Less measurable, but no less profound, is a sapping of confidence across our land; a nagging fear that America's decline is inevitable, that the next generation must lower its sights.
Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this America: They will be met. (Applause.)
On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn-out dogmas that for far too long have strangled our politics. We remain a young nation. But in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. (Applause.)
In reaffirming the greatness of our nation we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted, for those that prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things -- some celebrated, but more often men and women obscure in their labor -- who have carried us up the long rugged path towards prosperity and freedom.
For us, they packed up their few worldly possessions and traveled across oceans in search of a new life. For us, they toiled in sweatshops, and settled the West, endured the lash of the whip, and plowed the hard earth. For us, they fought and died in places like Concord and Gettysburg, Normandy and Khe Sahn.
Time and again these men and women struggled and sacrificed and worked till their hands were raw so that we might live a better life. They saw America as bigger than the sum of our individual ambitions, greater than all the differences of birth or wealth or faction.
This is the journey we continue today. We remain the most prosperous, powerful nation on Earth. Our workers are no less productive than when this crisis began. Our minds are no less inventive, our goods and services no less needed than they were last week, or last month, or last year. Our capacity remains undiminished. But our time of standing pat, of protecting narrow interests and putting off unpleasant decisions -- that time has surely passed. Starting today, we must pick ourselves up, dust ourselves off, and begin again the work of remaking America. (Applause.)
For everywhere we look, there is work to be done. The state of our economy calls for action, bold and swift. And we will act, not only to create new jobs, but to lay a new foundation for growth. We will build the roads and bridges, the electric grids and digital lines that feed our commerce and bind us together. We'll restore science to its rightful place, and wield technology's wonders to raise health care's quality and lower its cost. We will harness the sun and the winds and the soil to fuel our cars and run our factories. And we will transform our schools and colleges and universities to meet the demands of a new age. All this we can do. All this we will do.
Now, there are some who question the scale of our ambitions, who suggest that our system cannot tolerate too many big plans. Their memories are short, for they have forgotten what this country has already done, what free men and women can achieve when imagination is joined to common purpose, and necessity to courage. What the cynics fail to understand is that the ground has shifted beneath them, that the stale political arguments that have consumed us for so long no longer apply.
The question we ask today is not whether our government is too big or too small, but whether it works -- whether it helps families find jobs at a decent wage, care they can afford, a retirement that is dignified. Where the answer is yes, we intend to move forward. Where the answer is no, programs will end. And those of us who manage the public's dollars will be held to account, to spend wisely, reform bad habits, and do our business in the light of day, because only then can we restore the vital trust between a people and their government.
Nor is the question before us whether the market is a force for good or ill. Its power to generate wealth and expand freedom is unmatched. But this crisis has reminded us that without a watchful eye, the market can spin out of control. The nation cannot prosper long when it favors only the prosperous. The success of our economy has always depended not just on the size of our gross domestic product, but on the reach of our prosperity, on the ability to extend opportunity to every willing heart -- not out of charity, but because it is the surest route to our common good. (Applause.)
As for our common defense, we reject as false the choice between our safety and our ideals. Our Founding Fathers -- (applause) -- our Founding Fathers, faced with perils that we can scarcely imagine, drafted a charter to assure the rule of law and the rights of man -- a charter expanded by the blood of generations. Those ideals still light the world, and we will not give them up for expedience sake. (Applause.)
And so, to all the other peoples and governments who are watching today, from the grandest capitals to the small village where my father was born, know that America is a friend of each nation, and every man, woman and child who seeks a future of peace and dignity. And we are ready to lead once more. (Applause.)
Recall that earlier generations faced down fascism and communism not just with missiles and tanks, but with the sturdy alliances and enduring convictions. They understood that our power alone cannot protect us, nor does it entitle us to do as we please. Instead they knew that our power grows through its prudent use; our security emanates from the justness of our cause, the force of our example, the tempering qualities of humility and restraint.
We are the keepers of this legacy. Guided by these principles once more we can meet those new threats that demand even greater effort, even greater cooperation and understanding between nations. We will begin to responsibly leave Iraq to its people and forge a hard-earned peace in Afghanistan. With old friends and former foes, we'll work tirelessly to lessen the nuclear threat, and roll back the specter of a warming planet.
We will not apologize for our way of life, nor will we waver in its defense. And for those who seek to advance their aims by inducing terror and slaughtering innocents, we say to you now that our spirit is stronger and cannot be broken -- you cannot outlast us, and we will defeat you. (Applause.)
For we know that our patchwork heritage is a strength, not a weakness. We are a nation of Christians and Muslims, Jews and Hindus, and non-believers. We are shaped by every language and culture, drawn from every end of this Earth; and because we have tasted the bitter swill of civil war and segregation, and emerged from that dark chapter stronger and more united, we cannot help but believe that the old hatreds shall someday pass; that the lines of tribe shall soon dissolve; that as the world grows smaller, our common humanity shall reveal itself; and that America must play its role in ushering in a new era of peace.
To the Muslim world, we seek a new way forward, based on mutual interest and mutual respect. To those leaders around the globe who seek to sow conflict, or blame their society's ills on the West, know that your people will judge you on what you can build, not what you destroy. (Applause.)
To those who cling to power through corruption and deceit and the silencing of dissent, know that you are on the wrong side of history, but that we will extend a hand if you are willing to unclench your fist. (Applause.)
To the people of poor nations, we pledge to work alongside you to make your farms flourish and let clean waters flow; to nourish starved bodies and feed hungry minds. And to those nations like ours that enjoy relative plenty, we say we can no longer afford indifference to the suffering outside our borders, nor can we consume the world's resources without regard to effect. For the world has changed, and we must change with it.
As we consider the role that unfolds before us, we remember with humble gratitude those brave Americans who at this very hour patrol far-off deserts and distant mountains. They have something to tell us, just as the fallen heroes who lie in Arlington whisper through the ages.
We honor them not only because they are the guardians of our liberty, but because they embody the spirit of service -- a willingness to find meaning in something greater than themselves.
And yet at this moment, a moment that will define a generation, it is precisely this spirit that must inhabit us all. For as much as government can do, and must do, it is ultimately the faith and determination of the American people upon which this nation relies. It is the kindness to take in a stranger when the levees break, the selflessness of workers who would rather cut their hours than see a friend lose their job which sees us through our darkest hours. It is the firefighter's courage to storm a stairway filled with smoke, but also a parent's willingness to nurture a child that finally decides our fate.
Our challenges may be new. The instruments with which we meet them may be new. But those values upon which our success depends -- honesty and hard work, courage and fair play, tolerance and curiosity, loyalty and patriotism -- these things are old. These things are true. They have been the quiet force of progress throughout our history.
What is demanded, then, is a return to these truths. What is required of us now is a new era of responsibility -- a recognition on the part of every American that we have duties to ourselves, our nation and the world; duties that we do not grudgingly accept, but rather seize gladly, firm in the knowledge that there is nothing so satisfying to the spirit, so defining of our character than giving our all to a difficult task.
This is the price and the promise of citizenship. This is the source of our confidence -- the knowledge that God calls on us to shape an uncertain destiny. This is the meaning of our liberty and our creed, why men and women and children of every race and every faith can join in celebration across this magnificent mall; and why a man whose father less than 60 years ago might not have been served in a local restaurant can now stand before you to take a most sacred oath. (Applause.)
So let us mark this day with remembrance of who we are and how far we have traveled. In the year of America's birth, in the coldest of months, a small band of patriots huddled by dying campfires on the shores of an icy river. The capital was abandoned. The enemy was advancing. The snow was stained with blood. At the moment when the outcome of our revolution was most in doubt, the father of our nation ordered these words to be read to the people:
"Let it be told to the future world...that in the depth of winter, when nothing but hope and virtue could survive... that the city and the country, alarmed at one common danger, came forth to meet [it]."
America: In the face of our common dangers, in this winter of our hardship, let us remember these timeless words. With hope and virtue, let us brave once more the icy currents, and endure what storms may come. Let it be said by our children's children that when we were tested we refused to let this journey end, that we did not turn back nor did we falter; and with eyes fixed on the horizon and God's grace upon us, we carried forth that great gift of freedom and delivered it safely to future generations.
Thank you. God bless you. And God bless the United States of America. (Applause.)"""


# 装饰器,用于测量函数执行时间
def timeit(func):
    @wraps(func)
    def wrap(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(func.__name__, time.time() - start)
        return result

    return wrap

# 统计单词出现次数的函数
@timeit
def func_counter(word_list):
    count_result = Counter(word_list)
    return count_result

# 生成数据,将文本转换成小写并分割成单词列表
def gen_data():
    return text.lower().split()

if __name__ == '__main__':
    word_list = gen_data()
    result = func_counter(word_list)
    print(result)

这是一个简单的Python程序,它通过装饰器和Counter类来统计给定文本中单词的出现次数,并测量了执行时间。程序中的gen_data函数将文本转换为小写并拆分为单词列表,然后使用Counter类在func_counter函数中对单词列表进行统计。通过@timeit装饰器,程序能够输出每个函数执行的时间。在__main__部分,它生成数据,调用func_counter函数进行统计,并打印结果和执行时间。

绘制艺术图

from turtle import *
from random import *
from math import *


class Tree:

    def __init__(self):
        setup(1000, 500)
        bgcolor(1, 1, 1)  # 背景色
        # ht()  # 隐藏turtle
        speed(10)  # 速度 1-10渐进,0 最快
        # tracer(1, 100)    # 设置绘图屏幕刷新频率,参数1设置在正常刷新频次的第参数1次刷新,参数2设置每次刷新的时延
        tracer(0, 0)
        pu()  # 抬笔
        backward(100)
        # 保证笔触箭头方向始终不向下,此处使其左转90度,而不是右转
        left(90)  # 左转90度
        backward(300)  # 后退300

    def tree(self, n, l):
        pd()  # 下笔
        # 阴影效果
        t = cos(radians(heading() + 45)) / 8 + 0.25
        pencolor(t, t, t)
        pensize(n / 1.2)
        forward(l)  # 画树枝

        if n > 0:
            b = random() * 15 + 10  # 右分支偏转角度
            c = random() * 15 + 10  # 左分支偏转角度
            d = l * (random() * 0.25 + 0.7)  # 下一个分支的长度
            # 右转一定角度,画右分支
            right(b)
            self.tree(n - 1, d)
            # 左转一定角度,画左分支
            left(b + c)
            self.tree(n - 1, d)
            # 转回来
            right(c)
        else:
            # 画叶子
            right(90)
            n = cos(radians(heading() - 45)) / 4 + 0.5
            pencolor(n, n * 0.8, n * 0.8)
            fillcolor(n, n * 0.8, n * 0.8)
            begin_fill()
            circle(3)
            left(90)
            end_fill()

            # 添加0.3倍的飘落叶子
            if random() > 0.7:
                pu()
                # 飘落
                t = heading()
                an = -40 + random() * 40
                setheading(an)
                dis = int(800 * random() * 0.5 + 400 * random() * 0.3 + 200 * random() * 0.2)
                forward(dis)
                setheading(t)
                # 画叶子
                pd()
                right(90)
                n = cos(radians(heading() - 45)) / 4 + 0.5
                pencolor(n * 0.5 + 0.5, 0.4 + n * 0.4, 0.4 + n * 0.4)
                fillcolor(n, n * 0.8, n * 0.8)
                begin_fill()
                circle(2)
                left(90)
                end_fill()
                pu()
                # 返回
                t = heading()
                setheading(an)
                backward(dis)
                setheading(t)
            # pass
        pu()
        backward(l)  # 退回


def main():
    tree = Tree()
    tree.tree(12, 100)  # 递归7层
    done()


if __name__ == '__main__':
    main()

这是一个使用Turtle库绘制分形树的简单程序。这个程序使用Turtle库绘制了一个递归的分形树,树的枝干和叶子的形状在一定的随机性基础上变化。程序中的Tree类的__init__方法用于初始化Turtle窗口,而tree方法实现了递归绘制树的功能。最后,在main函数中创建了Tree对象并调用tree方法,绘制了递归12层的分形树。

文章来源:https://blog.csdn.net/weixin_57367513/article/details/135032821
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。