1、python的安装

官网下载.exe文件直接安装即可,在安装过程中选择加入环境变量,就不用在安装后再去增添环境变量了。
本文选择的是python3.6版本,没有选择2.7版本。

2、启动python解释器和运行.py文件

安装过程中选择创建桌面图标连接,在安装过后可以直接点击图标即可,或者在cmd下输入python即可。
我们可以看到如下图所示内容:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 

在python解释器中>>>是主提示符,...是次要提示符。

>>> str = '''python
...is cool!'''
>>> print(str)
python
is cool!

python程序文件是以.py结尾,运行该文件可以在cmd中转到代码目录,然后使用以下命令即可:

> python filename.py

也可以使用各种编辑器如pycharm,可以在编辑器中直接执行。

3、print语句和“Hello World!”

在python3.6 版本中,print语句采用print()的形式。

#!/usr/bin/env python
# _*_coding:utf-8_*_
# name:'first.py'
print('Hello World!')

执行first.py

> python first.py
Hello World!

也可以直接打开python解释器直接输入:

>>> print('Hello World!')
Hello World!

在解释器中“_”有着特别的意义:表示最后一个表达式的值,是表达式而不是普通语句。

>>> _
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> str = 'Hello World!'
>>> str
'Hello World!'
>>> _
'Hello World!'

print语句的标准化输出

采用的是类似于C语言的printf()类似的写法:

>>> print('I want to say %s' % (str))
I want to say Hello World!

此外,在了解到stdout:

>>> import sys
>>> sys.stdout.write('Hello World!')
Hello World!>>>

这里的sys.stdout.write()不会在句尾自动回车。

疑问

在学习到标准化输出时,了解到重定向,采用的是linux中的>>符号:
运行下一段代码时出现错误:

#!/usr/bin/env python
import sys
logfile = open('log.txt', 'w+')
ser = sys.stderr
print >> logfile, 'Hello World!'
print >> ser, 'stderr'
logfile.close()

输出错误:

Hello World!
Traceback (most recent call last):File "G:/Code/python/fan.py", line 6, in <module>print >> logfile, 'Hello World!'
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?Process finished with exit code 1

怀疑是平台的问题,之后再linux上测试了一下,没有问题:

$ python fan.py
stderr
$ cat log.txt
Hello World!

至于具体原因还不知,望哪位大神告知!

输入与input()内建函数

python使用input()函数进行程序输入,它读取标准输入,并将读取到的数据复制给指定的变量。在这之中你可以使用int()内建函数将用户输入的字符串转换为整型。

>>> name = input('Please input your name:')
Please input your name:yt
>>> num = input('Please input your num:')
Please input your num:22
>>> print('Your name is %s' % (name))
Your name is yt
>>> print('Your age is %d' % (num))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> print('Your age is %d' % (int(num)))
Your age is 22
>>> print('Your age is %s' % (num))
Your age is 22

可见input()得到的标准化输入为字符串,当需要整型数值是需要使用int()内建函数。可以使用help(input)查看帮助信息:

>>> help(input)
Help on built-in function input in module builtins:input(prompt=None, /)Read a string from standard input.  The trailing newline is stripped.The prompt string, if given, is printed to standard output without atrailing newline before reading input.If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.On *nix systems, readline is used if available.

在python2中使用的是raw_input()函数,查看帮助信息会发现其标准化输入为字符串,输出也为字符串:

Help on built-in function raw_input in module __builtin__:raw_input(...)raw_input([prompt]) -> string  Read a string from standard input.  The trailing newline is stripped.If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.On Unix, GNU readline is used if enabled.  The prompt string, if given,is printed without a trailing newline before reading.
(END)

注释

python使用的和其他的unix-shell脚本的注释一样都是:#.

# Author:yt
# 标注作者

此外,在函数中的注释使用的是双引号;

#!/usr/bin/env pythondef test(x):"This is a test function"print('The result is %d' % (x+x))
test(1)
$ python3 fan.py
The result is 2

需要注意最好在脚本开始加上这两句代码:

#!/usr/bin/env python 指定代码执行程序
# _*_coding:utf-8_*_ 指定编码格式

操作符

主要包括算术操作符、比较操作符和逻辑操作符。
算术操作符:

+   加
-   减
/   算术除
*   乘
//  相除取整
%   取余
**  乘方
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5%3
2
>>> 5**3
125

比较操作符:
< > == <= >= != <>
python目前支持两种不等于比较操作符,但是对于2和3支持却不相同:

$ python
Python 2.7.13 (default, Mar 13 2017, 20:56:15)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 5!=1
True
>>> 5<>1
True
----------------------------------------------------------
$ python3
Python 3.6.1 (default, Mar 21 2017, 21:49:16)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 5!=1
True
>>> 5<>1File "<stdin>", line 15<>1^
SyntaxError: invalid syntax

逻辑操作符:
and or not
有一个特殊的现象:
>>> 3<4<5 True >>> 3<4 and 4<5 True

变量与赋值

python的变量名是大小敏感的,其命名是以字母开头,大小写皆可,在加上数字和下划线。
python是动态语言,不需要预先声明变量的类型,其类型和值在被赋值的那一刻就已经被初始化了。
python支持增量赋值,即:

>>> n = 10
>>> n += 10
>>> n
20

但是并不支持自增与自减。

数字

主要包括:有符号整型、长整型、布尔值、浮点值和复数
eg:
long 27879898L -7867L
complex 6.23+1.5j 0+1j 1+0j

其中长整型在3.6版本应该发生了变化:

$ python3、
Python 3.6.1 (default, Mar 21 2017, 21:49:16)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> nj = 1231321LFile "<stdin>", line 1nj = 1231321L^
SyntaxError: invalid syntax
-----------------------------------------------------------
$ python
Python 2.7.13 (default, Mar 13 2017, 20:56:15)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> nj = 182391283L
>>>

更具体的需要去查询文档。

此外还包括第六种数字类型:decimal用于十进制浮点数,python2.4之后已经增加了。

>>> import decimal
>>> decimal.Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> print(decimal.Decimal('1.1'))
1.1

字符串

Python中的字符串被定义为引号之间的字符集合。python支持使用成队的单引号或者双引号,三引号可以用来包含特殊字符。使用索引和切片可以得到子字符串。字符索引从0开始,最后一个字符索引为-1.

#!/usr/bin/env python
# _*_coding:utf-8_*_
str1 = "python"
str2 = "cpython"print(str1)
print(str2)
print(str1[::-1])for i in range(len(str1)):print(str1[i])for i in range(len(str2)):print(str2[:i+1])

输出:

C:\Users\yanta\AppData\Local\Programs\Python\Python36\python.exe G:/Code/python/1.py
python
cpython
nohtyp
p
y
t
h
o
n
c
cp
cpy
cpyt
cpyth
cpytho
cpythonProcess finished with exit code 0

列表和元组

列表和元组可以当成普通的“数组”,能够保存任意数量的任意类型的Python对象。和数组一样,可通过数字索引访问元素,且索引从0开始。依然可以切片运算。

区别:list用中括号[]包裹,元素个数和值可以改变。tuple是使用小括号()包裹,不可改变,可以看成只读的列表。

list = [1, 2, 3, 4]
tuple = ('a', 'b', 'c', 'd')print(list[::-1])
print(tuple[::-1])for i in range(len(list)):print(list[i])for i in range(len(tuple)):print(tuple[i])for i in range(len(list)):print(list[:i+1])for i in range(len(tuple)):print(tuple[:i+1])

输出结果:

[4, 3, 2, 1]
('d', 'c', 'b', 'a')
1
2
3
4
a
b
c
d
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
('a',)
('a', 'b')
('a', 'b', 'c')
('a', 'b', 'c', 'd')

字典

字典是python的映射数据类型,有键值对构成。值可以为任意类型的python对象,字典元素用大括号({ })包裹。

# 字典
dict = {'name': 'yt', 'age': '17'}print(dict.keys())dict['name'] = 'boy'
print(dict)
for key in dict:print(dict[key])

输出结果:

dict_keys(['name', 'age'])
{'name': 'boy', 'age': '17'}
boy
17

这里的dict.keys()在2.7和3.6版本中有所变化:
$ python2 Python 2.7.13 (default, Mar 13 2017, 20:56:15) [GCC 5.4.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'name': 'yt', 'age': '17'} >>> dict.keys() ['age', 'name'] ----------------------------------------- $ python3 Python 3.6.1 (default, Mar 21 2017, 21:49:16) [GCC 5.4.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'name': 'yt', 'age': '17'} >>> dict.keys() dict_keys(['name', 'age'])

代码块缩进对齐

python的代码块书写时不要靠小括号(())和花括号({ })来区分代码块区域的,而是直接使用缩进的方式,通用的缩进距离是4。
在解释器中输入代码也要注意缩进:

>>> for i in range(3):
... print(i) #无缩进File "<stdin>", line 2print(i)^
IndentationError: expected an indented block
>>> for i in range(3):
...     print(i)  #有缩进
...
0
1
2

语句

if语句

语法如下:

if expression:pass

特别注意缩进和if语句后的:.

if expression1:pass1
elif expression2:pass2
else:pass3

while循环

语法如下:

while expression:pass

for循环

python中的for循环与传统的for循环不一样,更像shell脚本中的foreach迭代。每次选取迭代对象中的一个。

>>> for i in [1, 2, 3, 4]:
...     print(i)
...
1
2
3
4

此外,for循环经常与range()内建函数一起使用:

list = ['a', 'b', 'c', 'd']for i in range(3):print(i)for i in range(len(list)):print(list[i])

输出结果:

0
1
2
a
b
c
d

列表解析

就是你可以在这一行中使用一个for循环将所有的值放到一个列表中;

>>> [x**2 for x in range(4)]
[0, 1, 4, 9]

还可以加入过滤条件:

>>> [x**2 for x in range(4) if not x%2]
[0, 4]
>>> [x**2 for x in range(4) if  x%2]
[1, 9]

文件与内建函数open()

python可以进行文件访问:
open()函数可以打开文件,并且可以指定使用什么方式:

myfile = open('filename', 'r,w,a,b,[+]')

其中‘+’表示读写,‘b’表示二进制,默认为‘r’。如果执行成功,一个文件对象句柄会被返回。后续文件操作必须通过此文件句柄进行。

文件对象有一些方法,如readlines()和close(),通过句点标识法访问。

logfile = open('log.txt', 'r')
for eachline in logfile:print(eachline)
logfile.close()

执行结果:

$ python3Python 3.6.1 (default, Mar 21 2017, 21:49:16)[GCC 5.4.0] on cygwinType "help", "copyright", "credits" or "license" for more information.

错误与异常

主要就是将代码封装进入try-except语句中就可以了。try之后是你打算管理的代码,expect之后则是处理错误的代码。

# python3.6
try:logfile = open('log.txt', 'r')for eachline in logfile:print(eachline)logfile.close()
except IOError:print('file open error')
# python2.7
try:logfile = open('log.txt', 'r')for eachline in logfile:print(eachline)logfile.close()
except IOError, e:print('file open error:', e)

从商可以看到两个版本中还是有多不同的,也可以使用as来达到同样的效果:

try:logfile = open('log.txt', 'r')for eachline in logfile:print(eachline)logfile.close()
except IOError as e:print('file open error', e)

当删除log.txt后可以看到异常:

file open error [Errno 2] No such file or directory: 'log.txt'

此外在还可以增加else语句,else语句表示当没有异常,try后代码语句执行成功后,执行else后的语句;而且在执行异常处理expect语句后可以执行再finaily语句。

try:logfile = open('log.txt', 'r')for eachline in logfile:print(eachline)logfile.close()
except IOError as e:print('file open error', e)
else:print('Open log.txt sucessful!')
finally:print('IOError ...')

输出结果:

$ python3Python 3.6.1 (default, Mar 21 2017, 21:49:16)[GCC 5.4.0] on cygwinType "help", "copyright", "credits" or "license" for more information.Open log.txt sucessful!

函数

定义函数语法:

def functionName([arguments]):"说明语句"pass

调用函数:

functionName(arg)

此外,参数可以设置默认值

def test(name = 'yt'):print(name)test('hehe')
test()

测试结果:

hehe
yt

定义类语法:

class ClassName(base_class[es]):         "optional documentation string"          static_member_declarations          method_declarations 

eg:

class test(object):name = 'yt'def __init__(self, num = 17):self.age = numprint('age is ', num)def show(self): print(self.name, ' is ', self.age, 'years old!')print(self.__class__.__name__)foo = test() #定义类后需要创建实例
foo.show()  #再调用方法

输出:

age is  17
yt  is  17 years old!
test

模块

模块实际上就是一个python程序文件,包括可执行代码、函数和类或者其他的东西组合。

当你创建一个python源文件,模块的名字就是不带.py后缀的文件名。

模块的导入方法:

import module
from module improt method

eg:

>>> import sys
>>> sys.stdout.write('Hello World!')
>>> Hello World!

补充

dir([obj]):描述对象的属性,如果没有提供参数,则会显示全局变量的名字

>>> dir(3)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'dict', 'i']

转载于:https://www.cnblogs.com/iskylite/p/7739589.html

python学习笔记(一)之入门相关推荐

  1. Python学习笔记—低阶入门(已完结)

    目录 前言 注意 该不该学习Python(个人感受,纯属胡言论语) 基础知识:Python 的数据存储机制 第一章 Python基本语法 1.1 Python 数据类型 1.1.1 数值类型 1.1. ...

  2. Python学习笔记 之 从入门到放弃

    笔记目录 9月22日:<基础教程>基础知识 ·模块导入 ·用变量引用函数(或者Python中大多数的对象) ·将数值转换成字符串的方法:str类型.repr函数 9月23日:列表.元组 · ...

  3. Python学习笔记--day10函数入门

    day10 函数入门 初识函数 函数的参数 函数的返回值 1. 初识函数 函数到底是个什么东西? 函数,可以当做是一大堆功能代码的集合. def 函数名():函数内编写代码......函数名() 例如 ...

  4. (二)python学习笔记之列表入门

    1.列表元素的访问 test=[1,2,3,4,5] print(test[1])#列表元素的访问 2.列表的基本操作方法 test=[1,2,3,4,5] test.append(6) # 在列表末 ...

  5. Python学习笔记--10.Django框架快速入门之后台管理admin(书籍管理系统)

    Python学习笔记--10.Django框架快速入门之后台管理 一.Django框架介绍 二.创建第一个Django项目 三.应用的创建和使用 四.项目的数据库模型 ORM对象关系映射 sqlite ...

  6. Python 学习笔记——入门

    文章目录 〇.Python 是什么 一.推荐的教程 二.这篇学习笔记适合什么人 三.环境 1. 操作系统 对于 Windows 对于 Ubuntu 对于其他操作系统 2. Python 对于 Wind ...

  7. Python学习笔记之入门基础

    课程链接:Python入门教程--基础阶段_哔哩哔哩_bilibili Python学习笔记 注释 单行注释: * 多行注释: 1.多行前面加# 2."""注释信息&qu ...

  8. [python教程入门学习]python学习笔记(CMD执行文件并传入参数)

    本文章向大家介绍python学习笔记(CMD执行文件并传入参数),主要包括python学习笔记(CMD执行文件并传入参数)使用实例.应用技巧.基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋 ...

  9. python学习笔记目录

    人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...

  10. Python学习笔记总结

    了解了python语言后,决定以后使用python来进行各项工作,因此一直想要深入学习python.千里之行始于足下,万事开头难. 由于最近在准备写毕业论文,陆陆续续学习了Python的语法知识. P ...

最新文章

  1. spring的jar各包作用
  2. 2星|《约见投资人》:A股上市公司软文集
  3. 过拟合、欠拟合与正则化
  4. vue全家桶+Koa2开发笔记(5)--nuxt
  5. Charles抓取微信小程序数据 以及 其它应用网站数据
  6. AtCoder AGC043D Merge Triplets (DP、组合计数)
  7. linux超级工具,linux运维超级工具--sysdig
  8. 在Windows上,迁移VisualSVN server
  9. 西门子mag6000接线_电磁流量计MAG5000或MAG6000,通过脉冲输出累积流量,脉冲输出如何接线,如何设置参数?...
  10. 圣诞节海报设计还没开始?感受下合适的节日感PSD模板
  11. Oracle树查询(查询所有子节点,父节点等等)_转载
  12. [Python] 学习资料汇总
  13. axis1 c# 接口 调用_C#图形编程GDI+基础
  14. 2018年统计用区划代码和城乡划分代码
  15. 单网卡、单IP、双网关设置内外网同时访问
  16. Android车载蓝牙相关开发4:蓝牙电话操作器BluetoothHeadsetClient
  17. php+生成条形码18位,php实现在线生成条形码示例分享(条形码生成器)
  18. 知云文献翻的一些使用
  19. 【论文笔记】A survey on security and privacy of federated learning(综述)
  20. R语言NBA球员数据挖掘简单实现

热门文章

  1. php 遍历所有的文件
  2. 提高PHP运行速度的小技巧
  3. 同步SQL Server 2000 数据库
  4. SunlightChain 区块链宣言
  5. 为什么要在JavaScript中使用静态类型? (使用Flow进行静态打字的4部分入门)
  6. 物联网技术与应用(第1-2课时)(cont.)
  7. UI设计师面试如何操作才能获得高薪
  8. UI设计师必备技能,看看你都学会了吗?
  9. python和c++的相互调用教程
  10. (转)软件测试的分类软件测试生命周期