Python|Python简介|安装Python解释器|运行|开发工具|Python之禅|turtle绘制五星红旗|绘制方块|绘制小猪佩奇|语言100课:学习(1)

源项目地址

Python - 100天从新手到大师

原作者:骆昊

说明:从项目上线到获得8w+星标以来,一直收到反馈说基础部分(前15天的内容)对新手来说是比较困难的,建议有配套视频进行讲解。最近把基础部分的内容重新制作了一个名为“Python-Core-50-Courses”的项目,用更为简单通俗的方式重写了这部分内容并附带了视频讲解,初学者可以关注下这个新项目。
如果需要Python基础视频,可以在“B站”搜索《Python零基础快速上手》,这套视频是我讲课的时候录制的随堂视频,画质尚可、音质一般,但是对初学者应该会有些帮助,欢迎大家留言、评论、发弹幕。学习之后觉得有收获的小伙伴可以“一键三连”来支持UP主(千锋Python)。国内用户如果访问GitHub比较慢的话,可以关注我的知乎号Python-Jack,上面的“从零开始学Python”专栏比较适合初学者,其他的专栏也在持续创作和更新中,欢迎大家关注并点赞评论。

创作不易,感谢大家的打赏支持,这些钱不会用于个人消费(例如:购买咖啡),而是通过腾讯公益、美团公益、水滴筹等平台捐赠给需要帮助的人(点击了解捐赠情况)。需要加入QQ学习群的可以扫描下面的二维码,三个群加一个即可,不要重复进群。学习群会为大家提供学习资源问题解答,如果有Python体验课行业公开课会提前在群里通知大家,欢迎大家加入。

项目“Day80~90”部分目前仍在创作中,因为作者平时也挤不出太多时间来写文档,因此更新的速度比较缓慢,感谢大家的理解。

简介中提到的“Python-Core-50-Courses”项目,该部分已自学完成,相关学习记录可参考专栏
Python语言基础50课学习记录

初识Python

Python简介

Python的历史
  1. 1989年圣诞节:Guido von Rossum开始写Python语言的编译器。
  2. 1991年2月:第一个Python编译器(同时也是解释器)诞生,它是用C语言实现的(后面),可以调用C语言的库函数。在最早的版本中,Python已经提供了对“类”,“函数”,“异常处理”等构造块的支持,还有对列表、字典等核心数据类型,同时支持以模块为基础来构造应用程序。
  3. 1994年1月:Python 1.0正式发布。
  4. 2000年10月16日:Python 2.0发布,增加了完整的垃圾回收,提供了对Unicode的支持。与此同时,Python的整个开发过程更加透明,社区对开发进度的影响逐渐扩大,生态圈开始慢慢形成。
  5. 2008年12月3日:Python 3.0发布,它并不完全兼容之前的Python代码,不过因为目前还有不少公司在项目和运维中使用Python 2.x版本,所以Python 3.x的很多新特性后来也被移植到Python 2.6/2.7版本中。

目前我使用的Python 3.7.x的版本是在2018年发布的,Python的版本号分为三段,形如A.B.C。其中A表示大版本号,一般当整体重写,或出现不向后兼容的改变时,增加A;B表示功能更新,出现新功能时增加B;C表示小的改动(例如:修复了某个Bug),只要有修改就增加C。如果对Python的历史感兴趣,可以阅读名为《Python简史》的网络文章。
在这里插入图片描述

Python的优缺点

Python的优点很多,简单的可以总结为以下几点。

  1. 简单明了,学习曲线低,比很多编程语言都容易上手。
  2. 开放源代码,拥有强大的社区和生态圈,尤其是在数据分析和机器学习领域。
  3. 解释型语言,天生具有平台可移植性,代码可以工作于不同的操作系统。
  4. 对两种主流的编程范式(面向对象编程和函数式编程)都提供了支持。
  5. 代码规范程度高,可读性强,适合有代码洁癖和强迫症的人群。

Python的缺点主要集中在以下几点。

  1. 执行效率稍低,对执行效率要求高的部分可以由其他语言(如:C、C++)编写。
  2. 代码无法加密,但是现在很多公司都不销售卖软件而是销售服务,这个问题会被弱化。
  3. 在开发时可以选择的框架太多(如Web框架就有100多个),有选择的地方就有错误。
Python的应用领域

目前Python在Web应用后端开发、云基础设施建设、DevOps、网络数据采集(爬虫)、自动化测试、数据分析、机器学习等领域都有着广泛的应用。

安装Python解释器

Python|Git remote|hosts|PyCharm常用快捷键|变量转换|命名|类型|运算符|分支|调整tab|循环|语言基础50课:学习记录(1)-项目简介及变量、条件及循环

运行Python程序

确认Python的版本

可以Windows的命令行提示符中键入下面的命令。

python --version

在Linux或macOS系统的终端中键入下面的命令。

python3 --version

当然也可以先输入pythonpython3进入交互式环境,再执行以下的代码检查Python的版本。

import sys

print(sys.version_info)
print(sys.version)
编写Python源代码

可以用文本编辑工具(推荐使用SublimeVisual Studio Code等高级文本编辑工具)编写Python源代码并用py作为后缀名保存该文件,代码内容如下所示。

print('hello, world!')
运行程序

切换到源代码所在的目录并执行下面的命令,看看屏幕上是否输出了"hello, world!"。

python hello.py

python3 hello.py
代码中的注释

注释是编程语言的一个重要组成部分,用于在源代码中解释代码的作用从而增强程序的可读性和可维护性,当然也可以将源代码中不需要参与运行的代码段通过注释来去掉,这一点在调试程序的时候经常用到。注释在随源代码进入预处理器或编译时会被移除,不会在目标代码中保留也不会影响程序的执行结果。

  1. 单行注释 - 以#和空格开头的部分
  2. 多行注释 - 三个引号开头,三个引号结尾
"""
第一个Python程序 - hello, world!
向伟大的Dennis M. Ritchie先生致敬

Version: 0.1
Author: 骆昊
"""
请将该文件命名为hello.py

使用Windows的小伙伴可以在命令行提示下通过下面的命令运行该程序
python hello.py

对于使用Linux或macOS的小伙伴可以打开终端并键入下面的命令来运行程序
python3 hello.py
"""

print('hello, world!')
# print("你好,世界!")
print('你好', '世界')
print('hello', 'world', sep=', ', end='!')
print('goodbye, world', end='!\n')

Python开发工具

IDLE - 自带的集成开发工具

IDLE是安装Python环境时自带的集成开发工具,如下图所示。但是由于IDLE的用户体验并不是那么好所以很少在实际开发中被采用。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dRQTTdXq-1680851318748)(./res/python-idle.png)]

IPython - 更好的交互式编程工具

IPython是一种基于Python的交互式解释器。相较于原生的Python交互式环境,IPython提供了更为强大的编辑和交互功能。可以通过Python的包管理工具pip安装IPython,具体的操作如下所示。

pip install ipython

pip3 install ipython

安装成功后,可以通过下面的ipython命令启动IPython,如下图所示。

在这里插入图片描述

Sublime Text - 高级文本编辑器

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qrYv4RdW-1680851318750)(./res/python-sublime.png)]

  • 首先可以通过官方网站下载安装程序安装Sublime Text 3或Sublime Text 2。

  • 安装包管理工具。

    1. 通过快捷键Ctrl+`或者在View菜单中选择Show Console打开控制台,输入下面的代码。
    • Sublime 3
    import  urllib.request,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib.request.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())
    
    • Sublime 2
    import  urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp)ifnotos.path.exists(ipp)elseNone;urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read());print('Please restart Sublime Text to finish installation')
    
    1. 在浏览器中输入 https://sublime.wbond.net/Package%20Control.sublime-package 下载包管理工具的安装包,并找到安装Sublime目录下名为"Installed Packages"的目录,把刚才下载的文件放到这个文件加下,然后重启Sublime Text就搞定了。
  • 安装插件。通过Preference菜单的Package Control或快捷键Ctrl+Shift+P打开命令面板,在面板中输入Install Package就可以找到安装插件的工具,然后再查找需要的插件。我们推荐大家安装以下几个插件:

    • SublimeCodeIntel - 代码自动补全工具插件。
    • Emmet - 前端开发代码模板插件。
    • Git - 版本控制工具插件。
    • Python PEP8 Autoformat - PEP8规范自动格式化插件。
    • ConvertToUTF8 - 将本地编码转换为UTF-8。

说明:事实上Visual Studio Code可能是更好的选择,它不用花钱并提供了更为完整和强大的功能,有兴趣的读者可以自行研究。
可参考:VS Code超详细Python配置指南,看这一篇就够了

PyCharm - Python开发神器

PyCharm的安装、配置和使用在《玩转PyCharm》进行了介绍,有兴趣的读者可以选择阅读。
在这里插入图片描述

练习

1.Python之禅

在Python交互式环境中输入下面的代码并查看结果,请尝试将看到的内容翻译成中文。

```Python
import this
```

> **说明**:输入上面的代码,在Python的交互式环境中可以看到Tim Peter撰写的[“Python之禅”],里面讲述的道理不仅仅适用于Python,也适用于其他编程语言。

在这里插入图片描述

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
参考译文:
《Python的禅》,蒂姆·彼得斯著
美丽胜于丑陋。
显式比隐式好。
简单总比复杂好。
复杂总比隐晦好
扁平比嵌套好。
稀疏胜于密集。
可读性很重要。
特殊情况不足以打破规则。
尽管实用胜过纯粹。
错误永远不应该悄无声息地过去。
除非明确沉默。
面对歧义,拒绝猜测的诱惑。
应该有一种——最好只有一种——显而易见的方法来做到这一点。
尽管这种方式一开始可能并不明显,除非你是荷兰人。
现在总比没有好。
尽管从来没有比现在更好的了。
如果实现很难解释,那就是个坏主意。
如果实现很容易解释,那么这可能是个好主意。
命名空间是一个非常棒的想法——让我们做更多这样的事情吧!

2. 学习使用turtle在屏幕上绘制图形(闭合方块)

> **说明**:turtle是Python内置的一个非常有趣的模块,特别适合对计算机程序设计进行初体验的小伙伴,它最早是Logo语言的一部分,Logo语言是Wally Feurzig和Seymour Papert在1966发明的编程语言。

```Python
import turtle

turtle.pensize(4)
turtle.pencolor('red')

turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)

turtle.mainloop()
```

> **提示**:本章提供的代码中还有画国旗和画小猪佩奇的代码,有兴趣的读者请自行研究。

3. turtle绘制五星红旗

用Python的turtle模块绘制五星红旗
在这里插入图片描述

    import turtle


    def draw_rectangle(x, y, width, height):
        """绘制矩形"""
        turtle.goto(x, y)
        turtle.pencolor('red')
        turtle.fillcolor('red')
        turtle.begin_fill()
        for i in range(2):
            turtle.forward(width)
            turtle.left(90)
            turtle.forward(height)
            turtle.left(90)
        turtle.end_fill()


    def draw_star(x, y, radius):
        """绘制五角星"""
        turtle.setpos(x, y)
        pos1 = turtle.pos()
        turtle.circle(-radius, 72)
        pos2 = turtle.pos()
        turtle.circle(-radius, 72)
        pos3 = turtle.pos()
        turtle.circle(-radius, 72)
        pos4 = turtle.pos()
        turtle.circle(-radius, 72)
        pos5 = turtle.pos()
        turtle.color('yellow', 'yellow')
        turtle.begin_fill()
        turtle.goto(pos3)
        turtle.goto(pos1)
        turtle.goto(pos4)
        turtle.goto(pos2)
        turtle.goto(pos5)
        turtle.end_fill()


    def main():
        """主程序"""
        turtle.speed(12)
        turtle.penup()
        x, y = -270, -180
        # 画国旗主体
        width, height = 540, 360
        draw_rectangle(x, y, width, height)
        # 画大星星
        pice = 22
        center_x, center_y = x + 5 * pice, y + height - pice * 5
        turtle.goto(center_x, center_y)
        turtle.left(90)
        turtle.forward(pice * 3)
        turtle.right(90)
        draw_star(turtle.xcor(), turtle.ycor(), pice * 3)
        x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9]
        # 画小星星
        for x_pos, y_pos in zip(x_poses, y_poses):
            turtle.goto(x + x_pos * pice, y + height - y_pos * pice)
            turtle.left(turtle.towards(center_x, center_y) - turtle.heading())
            turtle.forward(pice)
            turtle.right(90)
            draw_star(turtle.xcor(), turtle.ycor(), pice)
        # 隐藏海龟
        turtle.ht()
        # 显示绘图窗口
        turtle.mainloop()


    if __name__ == '__main__':
        main()

4.绘制小猪佩奇的头部(函数法)

在这里插入图片描述

"""
绘制小猪佩奇
"""
from turtle import *


def nose(x,y):
    """画鼻子"""
    penup()
    # 将海龟移动到指定的坐标
    goto(x,y)
    pendown()
    # 设置海龟的方向(0-东、90-北、180-西、270-南)
    setheading(-30)
    begin_fill()
    a = 0.4
    for i in range(120):
        if 0 <= i < 30 or 60 <= i <90:
            a = a + 0.08
            # 向左转3度
            left(3)
            # 向前走
            forward(a)
        else:
            a = a - 0.08
            left(3)
            forward(a)
    end_fill()
    penup()
    setheading(90)
    forward(25)
    setheading(0)
    forward(10)
    pendown()
    # 设置画笔的颜色(红, 绿, 蓝)
    pencolor(255, 155, 192)
    setheading(10)
    begin_fill()
    circle(5)
    color(160, 82, 45)
    end_fill()
    penup()
    setheading(0)
    forward(20)
    pendown()
    pencolor(255, 155, 192)
    setheading(10)
    begin_fill()
    circle(5)
    color(160, 82, 45)
    end_fill()


def head(x, y):
    """画头"""
    color((255, 155, 192), "pink")
    penup()
    goto(x,y)
    setheading(0)
    pendown()
    begin_fill()
    setheading(180)
    circle(300, -30)
    circle(100, -60)
    circle(80, -100)
    circle(150, -20)
    circle(60, -95)
    setheading(161)
    circle(-300, 15)
    penup()
    goto(-100, 100)
    pendown()
    setheading(-30)
    a = 0.4
    for i in range(60):
        if 0<= i < 30 or 60 <= i < 90:
            a = a + 0.08
            lt(3) #向左转3度
            fd(a) #向前走a的步长
        else:
            a = a - 0.08
            lt(3)
            fd(a)
    end_fill()


def ears(x,y):
    """画耳朵"""
    color((255, 155, 192), "pink")
    penup()
    goto(x, y)
    pendown()
    begin_fill()
    setheading(100)
    circle(-50, 50)
    circle(-10, 120)
    circle(-50, 54)
    end_fill()
    penup()
    setheading(90)
    forward(-12)
    setheading(0)
    forward(30)
    pendown()
    begin_fill()
    setheading(100)
    circle(-50, 50)
    circle(-10, 120)
    circle(-50, 56)
    end_fill()


def eyes(x,y):
    """画眼睛"""
    color((255, 155, 192), "white")
    penup()
    setheading(90)
    forward(-20)
    setheading(0)
    forward(-95)
    pendown()
    begin_fill()
    circle(15)
    end_fill()
    color("black")
    penup()
    setheading(90)
    forward(12)
    setheading(0)
    forward(-3)
    pendown()
    begin_fill()
    circle(3)
    end_fill()
    color((255, 155, 192), "white")
    penup()
    seth(90)
    forward(-25)
    seth(0)
    forward(40)
    pendown()
    begin_fill()
    circle(15)
    end_fill()
    color("black")
    penup()
    setheading(90)
    forward(12)
    setheading(0)
    forward(-3)
    pendown()
    begin_fill()
    circle(3)
    end_fill()


def cheek(x,y):
    """画脸颊"""
    color((255, 155, 192))
    penup()
    goto(x,y)
    pendown()
    setheading(0)
    begin_fill()
    circle(30)
    end_fill()


def mouth(x,y):
    """画嘴巴"""
    color(239, 69, 19)
    penup()
    goto(x, y)
    pendown()
    setheading(-80)
    circle(30, 40)
    circle(40, 80)


def setting():
    """设置参数"""
    pensize(4)
    # 隐藏海龟
    hideturtle()
    colormode(255)
    color((255, 155, 192), "pink")
    setup(840, 500)
    speed(10)


def main():
    """主函数"""
    setting()
    nose(-100, 100)
    head(-69, 167)
    ears(0, 160)
    eyes(0, 140)
    cheek(80, 10)
    mouth(-20, 30)
    done()


if __name__ == '__main__':
    main()

5.绘制小猪佩奇(完整版)

引自:turtle作图:用turtle画一个小猪佩奇(详解!)
在这里插入图片描述

import  turtle  as  t
t.pensize(4)
t.hideturtle()
t.colormode(255)#设置画笔大小为0-255
t.color((255,155,192),"pink")
t.setheading(-30)
t.pu()
t.goto(-100,100)
t.begin_fill()
t.pd()
a=0.4
for  i  in  range(120):
    if  0<=i<30  or  60<=i<90:
        a=a+0.08
        t.lt(3)
        t.fd(a)
    else:
        a=a-0.08
        t.lt(3)
        t.fd(a)
t.end_fill()
t.pu()
t.seth(90)
t.fd(25)
t.setheading(0)
t.fd(10)
t.begin_fill()
t.pd()
t.circle(5)
t.color(160,82,45)
t.end_fill()
t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255,155,192)
t.begin_fill()
t.circle(5)
t.color(160,82,45)
t.end_fill()
#头
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.pd()
t.begin_fill()
t.seth(0)
t.circle(-300,30)
t.circle(-100,60)
t.circle(-80,100)
t.circle(-150,20)
t.circle(-60,95)
t.seth(161)
t.circle(-300,15)
t.pu()
t.goto(-100,100)
t.pd()
t.seth(-30)
a=0.4
for  i  in  range(60):
    if  0<=i<30:
        a=a+0.08
        t.lt(3)
        t.fd(a)
    else:
        a=a-0.08
        t.lt(3)
        t.fd(a)
t.end_fill()
#耳机
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,54)
t.end_fill()
t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,56)
t.end_fill()
#眼睛
t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
#腮
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()
#嘴
t.color(239,69,19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30,40)
t.circle(40,80)
#身体
t.color("red",(255,99,71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100,10)
t.circle(300,30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300,30)
t.circle(100,3)
t.color((255,155,192),(255,100,100))
t.seth(-135)
t.circle(-80,63)
t.circle(-150,24)
t.end_fill()
#手
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300,15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20,90)
t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300,15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20,90)
#脚
t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
#尾巴
t.pensize(4)
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70,20)
t.circle(10,330)
t.circle(70,30)
t.mainloop()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

打酱油的工程师

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

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

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

打赏作者

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

抵扣说明:

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

余额充值