Python Learning Notes

Source: Internet
Author: User

InstallationLinux

Linux has come with Python, and my Centos7 comes with Python2.7.4, and I have updated the version by installing it from the source.

<!--lang: sh-->#!/bin/bash#源码安装wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgztar -zxvf Python-2.7.9.tgzcd Python-2.7.9#编译安装./configuremakemake install
Install PIP (recommended installation, not required)

Pip is a package manager that is easy to install after installation using the framework and dependent packages. Recommended installation.

<!--lang: sh-->#!/bin/bashwget https://bootstrap.pypa.io/get-pip.pypython get-pip.py
Hello World
>>> print ‘hello, world‘hello, world>>> exit()
Editor

It is recommended to use notepad++ under Vim,windows.

hello_world.py
#!/usr/bin/env python# -*- coding:utf8-*-# 第一行用于在Linux下被识别从而直接运行#第二行用于定义此文件的字符编码是utf8,防止乱码,这是一个好习惯#print可以使用以下两种形式来输出字符到控制台,推荐第二种,可以兼容Python3print ‘Hello World‘print(‘Hello World‘)#可以用逗号分隔每个字符串,打印出来遇到逗号会输出一个空格print ‘Hello‘,‘World‘#读取用户输入的字符并赋予name变量name = raw_input()
Run
<!--lang: sh-->python hello_world.py
Basis
    • #Start with a comment
    • :End is code block, code block indentation recommended four spaces
Data typeDigital
    • Integers: For example 1 100 , 16 is the 0x beginning of the binary, for example0xff00
    • Floating-point numbers: For example 3.14 , scientific notation replaces 10 with E, and the 9-1.23x10 is 1.23e9 or 12.3e8
      Note: integer operations are always accurate, and floating-point numbers may be rounded
String
    • ‘‘ "" any text in or enclosed, escaped, used to \ escape single quotes, double quotes, and special characters (such as line breaks)
    • r‘‘Represents the original string and does not need to be escaped
    • ‘‘‘我是内容‘‘‘These three quotes (single and double lines) expand to indicate the text that can be wrapped
    • r‘‘‘我是内容‘‘‘Represents multiple lines of raw string and does not need to be escaped
    • u‘‘Represents a Unicode string
    • String Formatting ' Hello,%s '% ' world '
Boolean value
    • True
    • False
      Boolean values can be used and , or and not operations
Null value

None

Variable

The type of the variable depends on the type of the first assignment.

a = 1
Constant

In Python, the variable in all capitals is constant (the value can still be changed).

PI = 3.14
Type judgments and Conversions
a = ‘123‘# 判断类型type(a)# 转换为int,其他类型同理int(a)## 转换函数表int(x [,base ])                #将x转换为一个整数long(x [,base ])             # 将x转换为一个长整数float(x )                        #将x转换到一个浮点数complex(real [,imag ])  #创建一个复数str(x )                           #将对象 x 转换为字符串repr(x )                        #将对象 x 转换为表达式字符串eval(str )                      #用来计算在字符串中的有效Python表达式,并返回一个对象tuple(s )                       #将序列 s 转换为一个元组list(s )                           #将序列 s 转换为一个列表chr(x )                          #将一个整数转换为一个字符unichr(x )                     #将一个整数转换为Unicode字符ord(x )                          #将一个字符转换为它的整数值hex(x )                          #将一个整数转换为一个十六进制字符串oct(x )                           #将一个整数转换为一个八进制字符串
SequenceList (lists)
classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]#list中元素个数(得到3)len(classmates)#最小元素(得到‘Bob‘)min(classmates)#最大元素(得到‘Tracy‘)max(classmates)# 访问元素(得到‘Michael‘)classmates[0]# 倒数第一个元素(得到‘Tracy‘)classmates[-1]# 追加元素classmates.append(‘Adam‘)# 位置1插入元素,后面元素会依次后推 classmates.insert(1, ‘Jack‘)# 删除末尾元素classmates.pop()# 删除位置 1 的元素classmates.pop(1)del classmates[1]# 删除片段del classmates[i: j]# 替换元素classmates[1] = ‘Sarah‘#切片(选取第一个到第二个元素组成新列表)classmates[1: 2]#切片(选取第一个到第三个元素组成新列表,每隔两个,按照原始list,得到‘Bob‘)classmates[1: 3: 2]# 不同类型元素L = [‘Apple‘, 123, True]# list嵌套(list做为list的一个元素)s = [‘python‘, ‘java‘, [‘asp‘, ‘php‘], ‘scheme‘]#取得‘php‘(相当于二维数组)print(s[2][2])#序列连接(两个列表组成新列表)classmates  + [‘lucy‘, ‘joe‘]#序列中的元素重复三次classmates * 3#元素在列表中是否存在isHave = ‘Bob‘ in classmates#转为序列(得到[‘P‘, ‘y‘, ‘t‘, ‘h‘, ‘o‘, ‘n‘])list(‘Python‘)
Tuple (tuple)

Once the definition is immutable. Gets the same element as the list, if there is only one element in the tuple, a comma must be used to differentiate it from the operator.

classmates = (‘Michael‘, ‘Bob‘, ‘Tracy‘)# 单元素元组classmates = (‘Michael‘,)
Dict and setDict
d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}#取值(不存在报错)d[‘Michael‘]#取值,不存在返回`None` d.get(‘Thomas‘)#取值,不存在返回自定义值`-1` d.get(‘Thomas‘, -1)#定义值d[‘Adam‘] = 67#删除键值对d.pop(‘Bob‘)del (d[‘Bob‘])#键列表dict.keys()#值列表dict.values()#键值对元组列表dict.items()#遍历for (k, v) in dict.items():    print ‘dict[%s] =‘ % k, v
Set

Collection of elements that are not duplicated

#定义,需要将list转化为set,自动过滤重复s = set([1, 2, 3])#添加s.add(4)#删除s.remove(4)#交集set([1, 2, 3]) & set([2, 3, 4])#并集set([1, 2, 3]) | set([2, 3, 4])
Conditional Judgment and circulationConditions

Both elif and else can be omitted. Conditions non-0 value, non-empty string, not empty list, etc., is judged True , otherwise False .

if <条件判断1>:    <执行1>elif <条件判断2>:    <执行2>elif <条件判断3>:    <执行3>else:    <执行4>
Cycle
#遍历列表names = [‘Michael‘, ‘Bob‘, ‘Tracy‘]for name in names:    print name# 便利列表2for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:    print x# 遍历列表3,等效2for x in range(101):    print x# while循环(按条件循环)n = 99while n > 0:    print n    n = n - 2

Python Learning Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.