Python基础

第一个实例

新建文件test.py vim test.py

//调用 /usr/bin 下的 python 解释器

#!/usr/bin/python  

//#!/usr/bin/env python 到 env 设置里查找 python 的安装路径,再调用对应路径下的解释器程序完成操作

print("Hello, World!")

调用

1)python test.py

2)

$ chmod +x test.py     # 脚本文件添加可执行权限
$ ./test.py 

中文编码

#!/usr/bin/python

# -*- coding: UTF-8 -*-

print( "你好,世界" )

交互式编程

$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>print ("Hello, Python!")

Hello, Python!

标识符

在 Python 里,标识符由字母、数字、下划线组成。不能以数字开头。

以下划线开头的标识符是有特殊意义的。以单下划线开头 _foo 的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import * 而导入。以双下划线开头的 __foo 代表类的私有成员,以双下划线开头和结尾的 __foo__ 代表 Python 里特殊方法专用的标识,如 __init__() 代表类的构造函数。

Python 可以同一行显示多条语句,方法是用分号 ; 分开,如:

>>> print ('hello');print ('runoob');
hello
runoob

保留字符

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

 

行和缩进

在 Python 的代码块中必须使用相同数目的行首缩进空格数。

建议你在每个缩进层次使用 单个制表符 或 两个空格 或 四个空格 , 切记不能混用

多行语句

Python语句中一般以新行作为语句的结束符。

但是我们可以使用斜杠( \)将一行的语句分为多行显示,如下所示:

total = item_one + \
        item_two + \
        item_three

语句中包含 [], {} 或 () 括号就不需要使用多行连接符。

注释

单行:#

多行:三个单引号或三个双引号

等待用户输入

下面的程序执行后就会等待用户输入,按回车键后就会退出:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

raw_input("按下 enter 键退出,其他任意键显示...\n")

print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,

变量类型

五个标准数据类型:

  • Numbers(数字):int(有符号整型)long(长整型[也可以代表八进制和十六进制])float(浮点型)complex(复数)
  • String(字符串)
  • List(列表)
  • Tuple(元组):元组与列表类似,不同之处在于元组的元素不能修改。元组中只包含一个元素时,需要在元素后面添加逗号。
  • Dictionary(字典)

实例:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

counter = 100 # 赋值整型变量

miles = 1000.0 # 浮点型

name = "John" # 字符串

print counter

print miles

print name

a = b = c = 1

a, b, c = 1, 2, "john"

str = 'Hello World!'

print str # 输出完整字符串

print str[0] # 输出字符串中的第一个字符

print str[2:5] # 输出字符串中第三个至第六个之间的字符串

print str[2:] # 输出从第三个字符开始的字符串

print str * 2 # 输出字符串两次

print str + "TEST" # 输出连接的字符串

print str[1:4:2] # 在索引 1 到索引 4 的位置并设置为步长为 2(间隔一个位置)来截取字符串

列表同

#字典

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # 输出键为'one' 的值

print dict[2] # 输出键为 2 的值

print tinydict # 输出完整的字典

print tinydict.keys() # 输出所有键

print tinydict.values() # 输出所有值

运算符

**幂 - 返回x的y次幂a**b 为10的20次方, 输出结果 100000000000000000000
//取整除 - 返回商的整数部分(向下取整
>>> 9//2
4
>>> -9//2
-5

 

for循环

#!/usr/bin/python

# -*- coding: UTF-8 -*-

for letter in 'Python': # 第一个实例

    print '当前字母 :', letter fruits = ['banana', 'apple', 'mango']

for fruit in fruits: # 第二个实例

    print '当前水果 :', fruit

for index in range(len(fruits)):

    print '当前水果 :', fruits[index]

print "Good bye!"

Python continue 语句跳出本次循环,而break跳出整个循环。

日期和时间

函数time.time()用于获取当前时间戳,每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import time

localtime = time.asctime( time.localtime(time.time()) )

print "本地时间为 :", localtime

以上实例输出结果:

本地时间为 : Thu Apr  7 10:05:21 2016

格式化日期

我们可以使用 time 模块的 strftime 方法来格式化日期,:

time.strftime(format[, t])

实例演示:

实例(Python 2.0+)

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import time

# 格式化成2016-03-20 11:45:39形式

print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

# 格式化成Sat Mar 28 22:24:24 2016形式

print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())

# 将格式字符串转换为时间戳

a = "Sat Mar 28 22:24:24 2016"

print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

以上实例输出结果:

2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0

Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import calendar

cal = calendar.month(2016, 1)

print "以下输出2016年1月份的日历:"

print cal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值