python基础知识教学_python教学----001 python基础知识

在经历了那么多之后,还是想把珍藏的一些东西分享出来,因为我知道最有价值的东西都是免费的,分享也是历练的一部分。下面进入正题。

本节内容

Python 2 or 3?

安装

Hello World程序

变量

用户输入

表达式if ...else语句

表达式for 循环

break and continue

表达式while 循环

一、Python 2 or 3?

作为初学者,这是一个严肃的问题,到底是学习python2还是python3?下面看一下官方的介绍:

In summary : Python 2.x is legacy, Python 3.x is the present and future of the language

Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012,3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.

Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, withless regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.

Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, "range()" returns a memory efficient iterable, not a list as in 2.x).

py2与3的详细区别

PRINT IS A FUNCTION

The statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old statement (PEP 3105). Examples:

You can also customize the separator between items, e.g.:

1

print("There are possibilities!", sep="")

ALL IS UNICODE NOW

从此不再为讨厌的字符编码而烦恼

还可以这样玩:(A,*REST,B)=RANGE(5)

1

2

3

4

>>> a,*rest,b = range(5)

>>> a,rest,b

(0, [1, 2, 3], 4)

某些库改名了

Old Name

New Name

_winreg

winreg

ConfigParser

configparser

copy_reg

copyreg

Queue

queue

SocketServer

socketserver

markupbase

_markupbase

repr

reprlib

test.test_support

test.support

还有谁不支持PYTHON3?

One popular module that don't yet support Python 3 is Twisted (for networking and other applications). Most

actively maintained libraries have people working on 3.x support. For some libraries, it's more of a priority than

others: Twisted, for example, is mostly focused on production servers, where supporting older versions of

Python is important, let alone supporting a new version that includes major changes to the language. (Twisted is

a prime example of a major package where porting to 3.x is far from trivial

二、Python安装

windows

1

2

3

4

5

6

7

1、下载安装包

https://www.python.org/downloads/

2、安装

默认安装路径:C:\python27

3、配置环境变量

【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】

如:原来的值;C:\python27,切记前面有分号(新的3.6.4的版本可以在安装的首页勾选添加到环境变量路径中的选项)

linux、Mac

1、更新yum源:yum –y install epel-release

wget -q -O - http://www.atomicorp.com/installers/atomic | sh

2、安装编译工具和必要的软件

yum install -y gcc wget

yum groupinstall "Development tools"

yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel

3、下载python3

4、解压&安装python3.6.4

tar –xvf Python-3.6.4.tgz

cd Python-3.6.4

./configure --prefix=/usr/local/python3

make && make install

ln -s /usr/local/python3/bin/python3 /usr/bin/python3

python3 –V #验证安装版本

5、增加环境变量到/etc/profile中

export PATH="/usr/local/python3/bin:$PATH"

source /etc/profile

6、安装pip

python3 get-pip.py

查看pip版本信息

python3 -m pip -V

pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

查看pip版本信息

# pip3 -V

pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

至此,python3.6.4安装完毕

三、Hello World程序

在linux 下创建一个文件叫hello.py,并输入

1

print("Hello World!")

然后执行命令:python hello.py ,输出

1

2

3

localhost:~ jieli$ vim hello.py

localhost:~ jieli$ python hello.py

Hello World!

指定解释器

上一步中执行 python hello.py 时,明确的指出 hello.py 脚本由 python 解释器来执行。

如果想要类似于执行shell脚本一样执行python脚本,例: ./hello.py,那么就需要在 hello.py 文件的头部指定解释器,如下:

1

2

3

#!/usr/bin/env python3

print("hello,world")

如此一来,执行: ./hello.py 即可。

ps:执行前需给予 hello.py 执行权限,chmod 755 hello.py

在交互器中执行

除了把程序写在文件里,还可以直接调用python自带的交互器运行代码,

1

2

3

4

5

6

[root@python ~]# python3

Python 3.6.4 (default, Jan  4 2018, 19:16:36)

[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> print("Hello World!")

Hello World!

四、变量\字符编码

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

声明变量

1

2

3

#_*_coding:utf-8_*_

name = "ysuking"

上述代码声明了一个变量,变量名为: name,变量name的值为:"ysuking"

变量定义的规则:

变量名只能是 字母、数字或下划线的任意组合

变量名的第一个字符不能是数字

以下关键字不能声明为变量名

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',

'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',

'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',

'while', 'with', 'yield']

变量的赋值

1

2

3

4

5

6

7

8

name = "ysuking"

name2 = name

print(name,name2)

name = "Jack"

print("What

is the value of name2 now?",name2)

结果:

ysuking ysuking

What is the value of name2 now?ysuking

常量:(全大写)

PIE=XXX

字符编码

python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill)

ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位(1bit)来表示(一个字节Byte),即:2**8 = 256-1,所以,ASCII码最多只能表示 255 个符号。

关于中文

为了处理汉字,程序员设计了用于简体中文的GB2312和用于繁体中文的big5。

GB2312(1980年)一共收录了7445个字符,包括6763个汉字和682个其它符号。汉字区的内码范围高字节从B0-F7,低字节从A1-FE,占用的码位是72*94=6768。其中有5个空位是D7FA-D7FE。

GB2312 支持的汉字太少。1995年的汉字扩展规范GBK1.0收录了21886个符号,它分为汉字区和图形符号区。汉字区包括21003个字符。2000年的 GB18030是取代GBK1.0的正式国家标准。该标准收录了27484个汉字,同时还收录了藏文、蒙文、维吾尔文等主要的少数民族文字。现在的PC平台必须支持GB18030,对嵌入式产品暂不作要求。所以手机、MP3一般只支持GB2312。

从ASCII、GB2312、GBK 到GB18030,这些编码方法是向下兼容的,即同一个字符在这些方案中总是有相同的编码,后面的标准支持更多的字符。在这些编码中,英文和中文可以统一地处理。区分中文编码的方法是高字节的最高位不为0。按照程序员的称呼,GB2312、GBK到GB18030都属于双字节字符集 (DBCS)。

有的中文Windows的缺省内码还是GBK,可以通过GB18030升级包升级到GB18030。不过GB18030相对GBK增加的字符,普通人是很难用到的,通常我们还是用GBK指代中文Windows内码。

显然ASCII码无法将世界上的各种文字和符号全部表示,所以,就需要新出一种可以代表所有字符和符号的编码,即:Unicode

Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536,

注:此处说的的是最少2个字节,可能更多

UTF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存...

所以,python解释器在加载.py文件中的代码时,会对内容进行编码(默认ascill),如果是如下代码的话:

报错:ascii码无法表示中文(在python3中已经修正)

1

2

3

#!/usr/bin/env

python

print "你好,世界"

改正:应该显示的告诉python解释器,用什么编码来执行源代码,即:

1

2

3

4

#!/usr/bin/env

python

#

-*- coding: utf-8 -*-

# 告诉python解释器 编码集

print "你好,世界"

注释

当行注视:# 被注释内容

多行注释:""" 被注释内容 """

’’’ 被注释内容 ’’’

五、用户输入

1

2

3

4

5

6

7

#!/usr/bin/env python

#_*_coding:utf-8_*_

#name = raw_input("What is your name?") #only on python 2.x

name = input("What is your name?")

print("Hello " + name )

输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:

在pycharm中getpass不好使,会卡住,推荐使用python或者ipython进行测试。

1

2

3

4

5

6

7

8

9

10

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import getpass

#将用户输入的内容赋值给 name 变量

pwd = getpass.getpass("请输入密码:")

#打印输入的内容

print(pwd)

字符拼接

1.“+号”拼接(尽量不用,多占用内存空间)

name = input("name:")

age = input("age:")

job = input("job:")

salary = input("salary:")

#print(username,password)info = '''

--------info of ------

Name:'''+ name + '''

Age:'''+ age + '''

Job:'''+ job +'''

Salary:'''+ salary

print(info)

2.标准化输出%

name = input("name:")

age = input("age:")

job = input("job:")

salary = input("salary:")

#print(username,password)info = '''

--------info of %s------

Name:%s

Age:%s

Job:%s

Salary:%s

'''%(name,name,age,job,salary)

print(info)

%s  = String 字符串

%d = Digital 整数

%f   =Float 浮点数

name = input("name:")

age = int(input("age:"))  #强制类型转换成int

print(type(age))

job = input("job:")

salary = input("salary:")

#print(username,password)info = '''

--------info of %s------

Name:%s

Age:%d

Job:%s

Salary:%s

'''%(name,name,age,job,salary)

print(info)

int() 强制转为int

str() 强制转为string

python 2.X  raw_input

=input python3.x

python 2.X (最好别用)input,输入是什么格式就认为是什么格式,如果不加” ” ‘ ’ 就认为是变量。

3.{}.format(对应)

info2 = '''

--------info of {_name}------

Name:{_name}

Age:{_age}

Job:{_job}

Salary:{_salary}

'''.format(_name=name,

_age=age,

_job=job,

_salary=salary)

print(info2)

4. {}.format(对应标号)

info3 = '''

--------info of {0}------

Name:{0}

Age:{1}

Job:{2}

Salary:{3}

'''.format(name,age,job,salary)

print(info3)

六、表达式if ... else

场景一、用户登陆验证

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#提示输入用户名和密码

#验证用户名和密码

#如果错误,则输出用户名或密码错误

#如果成功,则输出 欢迎,XXX!

#!/usr/bin/env python

# -*- coding: encoding -*-

import getpass

name = input('请输入用户名:')

pwd = getpass.getpass('请输入密码:')

if name == "ysuking" and pwd == "cmd":

print("欢迎,ysuking!")

else:

print("用户名和密码错误")

缩进四个空格;

场景二、猜年龄游戏

在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#!/usr/bin/env python

# -*- coding: utf-8 -*-

my_age = 28

user_input = int(input("input your guess num:"))

if user_input == my_age:

print("Congratulations, you got it !")

elif user_input < my_age:

print("Oops,think bigger!")

else:

print("think smaller!")

外层变量,可以被内层代码使用

内层变量,不应被外层代码使用

七、表达式for loop

最简单的循环10次

1

2

3

4

5

6

#_*_coding:utf-8_*_

for i in range(10):

print("loop:", i )

输出:

1

2

3

4

5

6

7

8

9

10

loop: 0

loop: 1

loop: 2

loop: 3

loop: 4

loop: 5

loop: 6

loop: 7

loop: 8

loop: 9

猜年龄变式(猜三次):

age_of_oldboy = 56

for i in range(3):

guess_age = int(input("guess

age:"))

if guess_age == age_of_oldboy:

print("yes, you got

it.")

break    elif guess_age >

age_of_oldboy:

print("too big!try again")

else:

print("too small!try

again")

else:    print("You have tried too

many times..fuck off!")

for中的else;当for循环正常走完的时候,就走else的语句;如果走了break或者exit(),就不走else;

打印奇偶数

打印偶数

fori inrange(0,10,2):

#(0,10,2)0-10(不包含10),步长为2,隔一个打印一个

print("loop",i)

八、continue和break

需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环

1

2

3

4

for i in range(10):

if i<5:

continue#不往下走了,直接进入下一次loop

print("loop:", i )

continue跳出本次循环,进入下次循环。

需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出

1

2

3

4

for i in range(10):

if i>5:

break#不往下走了,直接跳出整个loop

print("loop:", i )

break是跳出全部循环

九、while loop

回到上面for循环的例子,如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序。

猜三次

age = 56

count = 0

whilecount < 3:

guess_age = int(input("guess

age:"))

ifguess_age == age_of_oldboy:

print("yes, you got

it.")

break

elifguess_age >

age_of_oldboy:

print("too big!try again")

else:

print("too small!try

again")

count = count + 1 #count += 1else:

print("You have tried too

many times..fuck off!")

while中的else,当不满足while循环的条件时,就走else;当遇到break或者exit时就不走else;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值