11 - 初步了解Python

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

初步了解Python

参考资料:
菜鸟教程:Python3基础语法
PEP 8:Style Guide for Python Code
Python Docs:Source Code Encoding
菜鸟教程:Python 3 命令行参数
Python Docs:Executable Python Scripts
知乎:#!/usr/bin/env python 有什么用?


编程规范:PEP 8

在没有额外编程规范的前提下,建议翻阅并遵守PEP 8 - Style Guide for Python Code

编码

默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 可以在源码文件上方指定不同的编码:

# -*- coding: cp-1252 -*-

上述定义允许在源文件中使用 Windows-1252 字符集中的字符编码,对应适合语言为保加利亚语、白俄罗斯语、马其顿语、俄语、塞尔维亚语。


标识符

标识符(变量名)命名规则:

  • 第一个字符必须是字母表中字母或下划线 _

  • 其他的字符由字母、数字和下划线组成。

  • 大小写敏感

  • 不能用Python内置的关键字(keywork)

关键字即保留字,它们不能用作标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

>>>import keyword
>>>print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • Python naming convention (命名惯例):

    • Modules should have short, all-lowercase names.

      模组名全小写

    • Class names should normally use the CapWords (CamelCase) convention.

      类名用驼峰命名法

    • Function and variables names should be lowercase, with words separated by underscores as necessary to improve readability.

      函数与变量名全小写,可用下划线增加可读性

    • Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

      常熟全大写,可用下划线增加可读性

  • Common name conventions:

    • _single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.

    • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. : tkinter.Toplevel(master, class_='ClassName')

    • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo).

    • __double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.


注释

Python中单行注释以 # 开头,实例如下:

#!/usr/bin/env python3

# 第一个注释 
print ("Hello, Python!") # 第二个注释

执行以上代码,输出结果为:

Hello, Python!

多行注释可以用多个 # 号,还有 '''"""

#!/usr/bin/env python3  

# 第一个注释
# 第二个注释

''' 第三注释
第四注释
'''

"""
第五注释
第六注释
"""

print ("Hello, Python!")

执行以上代码,输出结果为:

Hello, Python!

行与缩进

python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。

PEP 8: Indentation 与 PEP 8: Tabs or Spaces? 对Python缩进提出额外的要求,包括尽量使用四个空格作为缩进、尽量使用tabs而不是空格。

缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:

if True:    
    print ("True") 
else:
    print ("False")

以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:

if True:
   print("Answer")
   print("True")
else:
   print("Answer")
  print("False")   # 缩进不一致,会导致运行错误

以上程序由于缩进不一致,执行后会出现类似以下错误:

SyntaxError: unindent does not match any outer indentation level

多行语句

Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句,例如:

# 仅作展示使用,不符合PEP 8规范
total = item_one + \
        item_two + \
        item_three

[], {}, 或 () 中的多行语句,不需要使用反斜杠 \,例如:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

total = (item_one
         + item_two
         + item_three)

PEP 8: Maximum Line Length 和 PEP 8: Line Break Before or After Operator? 包含了对于多行语句的编程规范。

空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。详见PEP 8: Blank Lines

空行也是程序代码的一部分。


同一行显示多条语句

Python 可以在同一行中使用多条语句,语句之间使用分号 ; 分割,以下是一个简单的实例:

#!/usr/bin/env python3

x = 'abcd'; print(x)

使用脚本执行以上代码,输出结果为:

abcd

多个语句构成代码组

缩进相同的一组语句构成一个代码块,称之代码组。

像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

首行及后面的代码组被称为一个子句(clause)。

如下实例:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""

#!/usr/bin/env python3  

x="a" 
y="b" 
# 换行输出 
print( x ) 
print( y )  

print('---------') 
# 不换行输出 
print( x, end="" ) 
print( y, end="" ) 
print()

以上实例执行结果为:

a
b
---------
ab 

善用 help() 方法

通过命令 help("print") 我们知道这个方法里第三个为缺省参数 sep=' '

这里表示我们使用分隔符为一个空格。

>>> help("print")
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    
    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.

所以在打印 dict 类的使用, 可以这样写:

>>> def getPairs(dict):
...     for k,v in dict.items() :
...             print(k,v,sep=':')
...

测试代码:

>>> getPairs({ x : x ** 3 for x in range(1,5)})
1:1
2:8
3:27
4:64

import 与 from...import

在 python 用 import 或者 from...import 来导入相应的模块。

将整个模块(somemodule)导入,格式为: import somemodule

从某个模块中导入某个函数,格式为: from somemodule import somefunction

从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为: from somemodule import *

time 模块举例:

  1. 将整个模块导入,例如:import time,在引用时格式为:time.sleep(1)。

  2. 将整个模块中全部函数导入,例如:from time import *,在引用时格式为:sleep(1)。

  3. 将模块中特定函数导入,例如:from time import sleep,在引用时格式为:sleep(1)。

  4. 将模块换个别名,例如:import time as abc,在引用时格式为:abc.sleep(1)。

命令行参数

很多程序可以执行一些操作来查看一些基本信息,Python可以使用-h参数查看各参数帮助信息:

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser (also PYTHONDEBUG=x)
-E     : ignore environment variables (such as PYTHONPATH)
-h     : print this help message and exit

[ etc. ]

在使用脚本形式执行 Python 时,可以接收命令行输入的参数,具体使用可以参照 Python 3 命令行参数。

可直接运行的 Python 脚本

16.1.2. Executable Python Scripts

On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line

#!/usr/bin/env python3.5

(assuming that the interpreter is on the user’s PATH) at the beginning of the script and giving the file an executable mode. The #! must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ('\n'), not a Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a comment in Python.

The script can be given an executable mode, or permission, using the chmod command.

chmod +x myscript.py

On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.文章来源地址https://www.toymoban.com/news/detail-825044.html


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

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

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

相关文章

  • 【Python SMTP/POP3/IMAP】零基础也能轻松掌握的学习路线与参考资料

    Python是一种高级编程语言,广泛应用于Web开发、人工智能、数据科学、自动化等领域。SMTP/POP3/IMAP是与邮件相关的三个协议,分别用于发送邮件、接收邮件和访问邮件。使用Python可以轻松实现这些功能,本文将介绍Python SMTP/POP3/IMAP的学习路线,并给出参考资料和优秀实践。 一

    2024年02月07日
    浏览(35)
  • 基于python健身房和器械点评系统设计与实现:开题报告、成品参考、毕设辅导资料

     博主介绍: 《Vue.js入门与商城开发实战》《微信小程序商城开发》图书作者,CSDN博客专家,在线教育专家,CSDN钻石讲师;专注大学生毕业设计教育和辅导。 所有项目都配有从入门到精通的基础知识视频课程,免费 项目配有对应开发文档、开题报告、任务书、PPT、论文模版

    2024年02月05日
    浏览(30)
  • Flutter参考资料

    Flutter 官网 : https://flutter.dev/ Flutter 插件下载地址 : https://pub.dev/packages Flutter 开发文档 : https://flutter.cn/docs ( 强烈推荐 ) 官方 GitHub 地址 : https://github.com/flutter Flutter 中文社区 : https://flutter.cn/ Flutter 实用教程 : https://flutter.cn/docs/cookbook Flutter CodeLab : https://codelabs.flutter-io.cn/ Dart 中

    2024年02月13日
    浏览(30)
  • 网络参考资料汇总(1)

    将这段时间参考的各路大佬的资料加以汇总分类: (1)FFmpeg: 基于FFmpeg进行rtsp推流及拉流(详细教程) Linux 编译安装 FFmpeg 步骤(带ffplay) Jetson 环境安装(三):jetson nano配置ffmpeg和nginx(亲测) Linux编译FFmpeg libx264 libx265 libfdk-aac libmp3lame libvpx libopus等 ffmpeg推流时报错 Unknown encod

    2024年02月07日
    浏览(32)
  • webgis开发参考资料

    http://zhihu.geoscene.cn/article/1038 2、arcgis server 紧促(bundle)格式缓存文件的读取 https://blog.csdn.net/abc553226713/article/details/8668839 3、ArcGIS 10.0紧凑型切片读写方法 https://www.cnblogs.com/yuantf/p/3320876.html 4、发布地图服务时导入已有的tpk切片包作为缓存 https://blog.csdn.net/hellfire2007/article/de

    2024年02月08日
    浏览(37)
  • 79、基于STM32单片机DHT11温湿度无线蓝牙手机APP监控报警系统(程序+原理图+PCB图+设计资料+参考论文+开题报告+元器件清单等)

    摘 要 温湿度控制已成为当今社会研究的热门项目。是工农业生产过程中必须考虑的因素。作为最常见的被控参数。温度和湿度已经不再是相互独立的物理量,而应在系统中综合考虑。广泛应用于实验室、大棚、花圃、粮仓乃至土壤等各个领域。而传统的温湿度控制则利用湿

    2024年02月11日
    浏览(54)
  • STM32重要参考资料

    stm32f103c8t6 (有时候不小心短接VCC和GND,芯片会锁住,可以BOOT0拉高试试(用跳线帽接)) 可用于PCB设计 1.RCC开启时钟错误,例如    RCC_ APB2 PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); 写成    RCC_ APB1 PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); 这个函数是有说明的,可以看看vscode显示的函

    2024年04月11日
    浏览(30)
  • 资料与参考

    资料: 本书(《Python神经网络编程》)的资料是使用Jupyter notebooks写的,本人并不擅长使用Jupyter,所以用传统py重写了一遍,并附加了新功能(即多数字识别),现将Jupyter版和py版连带本书pdf一并上传至gitee,地址:python-neuralNetwork-coding: 《Python神经网络编程》pdf和随书源码,

    2024年02月11日
    浏览(41)
  • Fast Planner——代码解读参考资料整理

    参数解读 主要函数解读 概率栅格地图,概率更新过程的公式推导过程 全概率公式、贝叶斯公式 一. kinodynamic a_star(前端hybrid A_star动力学路径搜索) 1.1启发函数的计算 1.2 Compute shot Traj 1.3 节点扩张 1.4 节点剪枝 1.5 返回kinopath与 getsamples 二、B样条曲线设置 2.1 均匀B样条设置

    2024年02月05日
    浏览(76)
  • [渝粤教育] 中国人民警察大学 工业企业防火 参考 资料

    教育 -工业企业防火-章节资料考试资料-中国人民警察大学【】 随堂测验 1、【判断题】工业企业的火灾特点是涉及行业种类繁多,涉及到社会生活的方方面面。 A、正确 B、错误 参考资料【 】 2、【判断题】工业企业的火灾特点是物资集中,存在各种形式的点火源,发生火灾

    2024年02月02日
    浏览(49)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包