自学Python
- 一、简介
C语言要写1000行代码,运行1秒钟,写操作系统,程序是运行前直接编译成CPU能执行的机器码,所以非常快。
编译型的语言,xx.exe
Java只需要写100行,需要2秒
Python可能只要20行,需要10秒,Google
YouTube,在线游戏的后台,ins,yahoo,豆瓣。
运行速度慢,解释型语言,代码不能加密,源码
写手机应用,只能用Swift/Objective-C(针对iPhone)和Java(针对Android);写3D游戏,最好用C或C++。
Sublime text 文本编辑器-语法高亮(不是python代码)
cd-change directory 切换目录
dir-directory 目录
- 二、环境
跨平台,
如果安装了Homebrew,直接通过命令brew install python3安装即可。
Windows会根据一个Path的环境变量设定的路径去查找python.exe
Python代码编写指导原则- python之禅
>>> import this
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!
- 三、小试牛刀
变量名:字母、数字、下划线,不能数字开头,不能包含空格,慎用小写l和0.
>>> name="ada lovelace”#修改字符串大小写
>>> print(name.title())
Ada Lovelace
>>> name="ada lovelace"
>>> print(name.upper())
ADA LOVELACE
>>> print(name.lower())
F-format 设置格式
命令行模式C:\>
Python解释器去执行.py文件。终端运行
Python交互模式>>>
直接输入代码,然后执行,并立刻得到结果,编辑器运行。
制表符\t,换行符\n
>>>a=‘python ’
>>>a.rstrip()
>>>a=a.rstrip()
‘python’
>>>print('Albert Einstein once said, "A person who never made a mistake')
>>>print('never tried anything new."')
Albert Einstein once said, “A person who never made a mistake
never tried anything new.”
剔除字符串开头空白用方法.lstrip() ,两边空白剔除用strip()
exit()
>>> 100+200
300
>>> print('hello, world')
hello, world
用单引号或者双引号括起来的文本在程序中叫字符串。
必须先把当前目录切换到hello.py所在的目录下,才能正常执行。
C:\> cd work
C:\work> python hello.py
Hello, world!
print(100 + 200 + 300)
C:\work>python calc.py
600
如果遇到SyntaxError,表示输入的Python代码有语法错误,最常见的一种语法错误是使用了中文标点,例如使用了中文括号(和)中文引号“和”
Visual Studio Code 跨平台工具
文件名只能是英文字母、数字和下划线的组合
python: can’t open file ‘hello.py’: [Errno 2] No such file or directory
未保存 .py文件
直接运行py文件
#!/usr/bin/env python3
print(‘hello, world’)
$ chmod a+x hello.py
执行权限

>>> print('100 + 200 =', 100 + 200)
100 + 200 = 300
>>> name = input()
Michael
>>> name
‘Michael’ 输入字符串,并存放到一个变量里,name作为一个变量就是一个字符串
>>> print(name)
Michael
name = input()
print(‘hello,’, name)
C:\Workspace> python hello.py
Michael
hello, Michael
name = input('please enter your name: ')
print(‘hello,’, name)
C:\Workspace> python hello.py
please enter your name: Michael
hello, Michael
输入输出统称为Input/Output,或者简写为IO