海山闲谈

千里易见,跬步难积

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

参考书目:《python编程:从入门到实践》 埃里克·玛瑟斯 人民邮电出版社

参考视频:python零基础入门教程 李立超 尚硅谷

一、环境配置

1.1 python安装

1.1.1 Windows环境

  • 下载python软件,安装过程中,勾选Add Pythonxx toPATH
  • 完成安装后,在cmd窗口输入python检查安装是否成功。

1.1.2 linux环境

在终端页面输入python查看系统中python版本号。

若环境中同时安装了python2和python3,python表示查询python2的版本信息,python3表示查询python3的版本信息。

1.2 文本编辑器安装

Windows中使用微软的VS code进行配置,具体参考VS code配置python环境

linux中可以使用Vim等经典工具。

1.3 在终端运行python

无论在哪种环境,在py文件所在的目录,通过python或者python3命令即可运行该脚本。

二、变量和简单的数据类型

2.1 变量的命名规则

  1. 变量名只能包含字母、数字和下划线,并且不能以数字开头;
  2. 变量名不能包含空格,所有空格使用_代替;
  3. 不能将python的关键字和函数名称作为变量名;
  4. 变量名应该在具有描述性的前提下尽量简短;
  5. 减少小写字母l和大写字母O的使用。

2.2 字符串

字符串被引号包围,可以单引号,也可以双引号,不过需要注意前后对应。

2.2.1 修改大小写

变量.title():将每个单词首字母大写

变量.upper():将每个字母大写

变量.lower():将每个字母小写

name = 'this is a name'
print(name.title())
print(name.upper())
print(name.lower())

#结果
This Is A Name
THIS IS A NAME
this is a name

2.2.2 拼接

可以使用+将多个字符串变量进行合并拼接。

first_name = 'xu'
last_name = 'peace'
full_name = first_name+' '+last_name
print('hello, '+full_name.title())

#结果
hello, Xu Peace

2.2.3 添加空白

\t:制表符,强制缩进4字符

\n:换行符,强制换行

print("code languages includs: \n\tpython\n\tC\n\tJava\n\tC#")

#结果
code languages includs: 
        python
        C
        Java
        C#

2.2.4 删除空白

变量.rstrip():删除右侧空白

变量.lstrip():删除左侧空白

变量.strip():删除左右侧空白

A = '123   '
B = '   234'
C = '  3 4 5  '
print(A.rstrip())
print(A)
print(B.lstrip())
print(B)
print(C.strip())
print(C)

# 结果
123
123
234
   234
3 4 5
  3 4 5

2.3 数字

2.3.1 整数

空格不影响计算结果,主要是为了方便阅读

乘方计算通过**表示,如2^4在程序中可以使用2 ** 4表示。

2.3.2 浮点数

可能会出现浮点数计算不准确的问题——是由于计算机内部进制转换导致。

2.3.3 类函数

在将数字当作字符使用时,需要加上字符的类函数str()

age = str(23)
print("happy " + age + "rd birthday")

# 结果
happy 23rd birthday

2.4 python之禅

在一个py文件中,输入import this会出现龟叔提倡的python之禅

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!

要求:

  1. 语言优美
  2. 表述明确
  3. 代码简洁
  4. 结构清晰
  5. 减少嵌套
  6. 间隔合理
  7. 注重代码可读性
  8. 尽量明确表明error类型和原因
  9. 为问题提供规范的唯一解
  10. 编程前考虑好整体方案
  11. 整体方案需要易于他人理解
  12. 多使用命名空间
posted on 2021-11-19 00:18  不山  阅读(121)  评论(0编辑  收藏  举报