Python automated development, Day2 - Python basics 2

高洛峰
Release: 2017-02-17 11:35:32
Original
1425 people have browsed it

Content of this chapter

  1. holle word

  2. Variable

  3. Character encoding

  4. User input

  5. Module initialization

  6. Data type

  7. Data operations

  8. if...else

  9. for loop

  10. while loop

1. The first program holle word

 #! /usr/bin/env python
 # -*- coding:utf-8 -*-
 #Author:Lyon
 
  print("holle word")
Copy after login

In Python3.5.2 environment Executed below, the execution results are as follows:

Python 3.5.2 (v3.5.2:4def2a2901a5,Jun 25 2016, 22:18:55)  [MSC v.1906 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("holle word")
holle word
>>>
Copy after login

2. Variables

Variables are used to store information that is referenced and manipulated in computer programs. Variables may be explicitly defined as abstractions with storage space that represent mutable state (as in Java and Visual Basic); the sole purpose of variables is to label and store data in memory. This data can be used throughout the program.

Declare variables

 #! usr/bin/eve python
 # -*- coding:utf-8 -*-

 name = "Lyon"
Copy after login

The above code declares a variable, the variable name is: name, the value of the variable name Rules defined for: "Lyon"

variables:

  1. Variable names can only be any combination of letters, numbers, or underscores

  2. The first character of the variable name cannot be a number

  3. The following keywords cannot be declared as variable names:

['and' , 'as' , 'assert' , 'break' , 'class' , 'continue' , 'def' , 'del' , 'eilf' , 'else' , 'except' , 'exec' , 'finally' , ' for' , 'from' , 'global' , 'if' , 'import' , 'in' , 'is' , 'lambda' , 'not' , 'or' , 'pass' , 'print' , 'raise' , 'return' , 'try' , 'while' , 'with' , 'yield' ]

3. Character encoding

When the python interpreter loads the code in the .py file, The content will be encoded (default Ascill)

ASCII (American Standard Code for Information Interchange, American Standard Code for Information Interchange) is a computer coding system based on the Latin alphabet, mainly used to display modern languages ​​and other Western European Language can only be represented by up to 8 bits (one byte), that is: 2**8 = 256-1. Therefore, ASCII code can only represent up to 255 symbols. Python自动化开发,Day2 - Python基础2

About Chinese.

In order to deal with Hanzi, programmers designed GB2132 for Simplified Chinese and big5 for Traditional Chinese.

GB2132 (1980) contains a total of 7445 characters, including 6763 Hanzi and 682 other symbols. The internal code range of the Hanzi area is from B0-F7 in the high byte and A1-FE in the low byte. The occupied code bits are 72*94=6768. There are 5 empty bits D7FA-D7FE.

GB2312 supports too few Chinese characters. The 1995 Chinese character expansion specification GBK1.0 includes 21886 symbols, which is divided into Chinese character area and graphic symbol area. The Chinese character area includes 21003 characters. GB18030 in 2000 is the official national standard version that replaced GBK1.0. This standard includes 27,484 Chinese characters, as well as Tibetan, Mongolian, Uyghur and other major ethnic minority languages. The current PC platform must support GB18030, and there are no requirements for embedded products. Therefore, mobile phones and MP3 generally only support GB2312.

From ASCII, GB2312, GBK to GB18030, these encoding methods are backward compatible, that is, the same character always has the same encoding in these schemes, and later standards support more characters. In these codes, English and Chinese can be processed uniformly. The way to distinguish Chinese encoding is that the highest bit of the high byte is not 0. According to the programmer's name, GB2312, GBK to GB18030 all belong to double-byte character sets (DBCS).

The default internal code of some Chinese Windows is still GBK, which can be upgraded to GB18030 through the GB18030 upgrade package. However, the characters added by GB18030 compared to GBK are difficult for ordinary people to use. Usually we still use GBK to refer to Chinese Windows internal code.

Obviously ASCII code cannot express all the various texts and characters in the world, so a new encoding that can represent all characters and symbols is needed, namely: Unicode

Unicode (Unicode, Unicode, Unicode) is a character encoding used on computers. Unicode was created to solve the limitations of traditional character encoding schemes. It sets a unified and unique binary encoding for each character in each language, stipulating that all characters and symbols must be represented by at least 16 bits (2 bytes), that is: 2**16=65536,

Note: What is mentioned here is at least 2 bytes, maybe more

UTF-8, which is the Unicode encoding For compression and optimization, he no longer uses at least 2 bytes, but classifies all characters and symbols: the content in the ASCII code is saved in one byte, European characters are saved in two bytes, and East Asian characters are saved in two bytes. The characters are saved in 3 bytes...

So, when the python interpreter loads the code in the .py file, it will encode the content (default ascill), if it is the following code:

Error: ascii code cannot represent Chinese

 #!/usr/bin/env python
 
 print("你好,世界")
Copy after login

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

#!/usr/bin/env python
# -*-  coding=utf-8 -*-
 
print("你好,世界")
Copy after login

 

四、用户输入 

#!usr/bin/env python#-*- coding:utf-8 -*-
#name = raw_input("What is your name?") only on python 
xname = input("What is your name?")print("Hello"+name)
Copy after login

 

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

#!usr/bin/env python# -*-  coding:utf-8  -*-import getpass

name = input("username:")
password =getpass.getpass("password:")print(password)
Copy after login

 

五、模块初识

Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,这里先象征性的学2个简单的。

sys

#!/usr/bin/env python
# -*-  coding:utf-8  -*-

import sys

print(sys.argv)

#输出
$ python test.py hello world
['test.py','hello','world']#把执行脚本时传递的参数获取到了
Copy after login

os

#!/usr/bin/env python
# -*-  coding:utf-8  -*-

import os

os.system("df-h")#调用系统命令
Copy after login

结合一下

 import os,sys
 
 os,system(''.join(sys.argv[1:]))#把用户输入的参数当作一条命令交给os.system来执行
Copy after login

 

模块也可以可以来写,但是如果想在系统的任何一个地方都使用的话,就需要把所写的。py文件放到python全局环境变量目录里,基本一般都放在一个叫site-packages目录下,这个目录在不同os里放的位置不一样,用print(sys.path)可以查看python环境变量列表。

六、数据类型

1、数字

2是一个整数的例子。

长整数不过是大一些的整数。

3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3*10-4。

(-5+4j)和(2.3-4.6j)是复数的例子,其中-5,4为实数,j为虚数,数学中表示复数是什么?

 int(整型)

 在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

在64位系统上,整数的位数是64位,取值范围为-2**63-2~2**63-1,即-9223372036854775808~9223372036854775807

long(长整型)

跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。

注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

float(浮点型)

先扫盲 http://www.cnblogs.com/alex3714/articles/5895848.html

浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。

complex(复数)

复数由实数部分和虚数部分组成,一般形式为x+yh,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。

注:Python中存在小数字池:-5~257

2、布尔值

真或假

1或0

3、字符串

字符串拼接:

python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,+号每出现一次就会在内存中重新开辟一块空间。

字符串格式化输出

 name = "Lyon"
 print("i am %s"% name)
 
 #输出:i am Lyon
Copy after login

 

PS:字符串是%s;整数%d;浮点数%f

字符串常用功能:

  • 移除空白

  • 分割

  • 长度

  • 索引

  • 切片

4、列表

创建列表:

name_list = ['Lyon','one','two']
或
name_list =list(['Lyon','one','two'])
Copy after login

 

基本操作:

  • 索引

  • 切片

  • 追加

  • 删除

  • 长度

  • 切片

  • 循环

  • 包含

5、元组(不可变列表)

创建元组:

 ages = (11, 22, 33, 44, 55)
 或
 ages = tuple((11, 22, 33, 44, 55))
Copy after login

 

6、字典(无序)

创建字典:

 person = {"name": "mr.wu", 'age': 18}
 或
 person = dict({"name": "mr.wu", 'age': 18})
Copy after login

 

常用操作:

  • 索引

  • 新增

  • 删除

  • 键值

  • 循环

  • 长度

七、数据运算

算数运算:

Python自动化开发,Day2 - Python基础2

比较运算:

Python自动化开发,Day2 - Python基础2

赋值运算:

Python自动化开发,Day2 - Python基础2

逻辑运算:

Python自动化开发,Day2 - Python基础2

成员运算:

Python自动化开发,Day2 - Python基础2

身份运算:

Python自动化开发,Day2 - Python基础2

 

位运算:

Python自动化开发,Day2 - Python基础2


运算符优先级:

Python自动化开发,Day2 - Python基础2


八、表达式if......else

 场景一:用户登录验证

 #!usr/bin/env python
# -*-  coding:utf-8  -*-
#Author:Lyon

import getpass

name = input("请输入用户名:")
password = getpass.getpass("请输入密码:")

if name =="Lyon" and password =="yang":
    print("欢迎你!")
else:
    print("用户名或密码错误")
Copy after login

 

场景二:猜年龄游戏

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
age =21 
user_input = int(input("input your guess num:"))
 
if user_input == age:
    print("Congratulations, you got it !")
elif user_input < age:
    print("Oops,think bigger!")
else:
    print("think smaller!")
Copy after login

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

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

九、for循环

最简单的循环10次

#_*_coding:utf-8_*_
__author__ = &#39;Alex Li&#39;
 
 
for i in range(10):
    print("loop:", i )
Copy after login

输出:

loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
Copy after login

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

 for i in range(10):
     if i<5:
         continue
     print("loop:"i)
Copy after login

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

 for i in range(10):
     if i>5:
         break
    print("loop:"i)
Copy after login

 

十、while loop

有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。

 count = 0
 while True:
     print("你是风儿我是沙,缠缠绵绵走天涯",count)
     count +=1
Copy after login

更多Python自动化开发,Day2 - Python基础2 相关文章请关注PHP中文网!

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!