python语法简单入门

之前一直没时间去了解python,今天看了下python的语法,敲了下很简单的代码,记录下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time    : 17/10/10 下午2:52
# @Author  : lijie
# @File    : myfirstpy.py

#############################################注释#########################################

'''
多行注释
'''

"""
多行注释
"""

#
#  注释
#
#

##########################################################################################

#############################################if else######################################
print "---------------if else"

a = 1
b = 2.0
if a == b:
    print "a=b"
elif a > b:
    print "a>b"
else:
    print "a<b"

print "---------------if else"
#############################################赋值######################################
print "---------------赋值"
a = 1
b = 1.1
c = "lijie"
d = e = f = 123
g, h, i = 7, 8, "9"
print "---------------赋值"
##########################################删除引用#########################################
print "---------------删除引用"
aa = 1
bb = "bb"
del aa, bb
print "---------------删除引用"
#########################################字符串##########################################
print "---------------字符串"
s = "abcdefghi"
print s
print s[0]
print s[2:5]
print s[2:]
print s * 2
print s + "xxxxx"
print "---------------字符串"
########################################list############################################
print "---------------list"
list = ["hello", 123, 1.23, "world"]

print list
# print list[8]  # IndexError: list index out of range
print list[0]
print list[1:3]
print list[2:]
print list * 2
print list + list
print len(list)
list.append("append")
print list
print list.insert(0, "head")
print list
list.reverse()
print list
print list.pop()
list.remove(123)
print list
list.sort()
print list

print "---------------list"
#######################################元组#############################################
print "---------------元组"
tuple = ("aa", "bb", "cc", 123, 1.23)
print tuple  #
print tuple[0]  # 输出元组的第一个元素
print tuple[1:3]  # 输出第二个至第三个的元素
print tuple[2:]  # 输出从第三个开始至列表末尾的所有元素
print tuple * 2  # 输出元组两次
print tuple + tuple  # 打印组合的元组

tp01 = (1, 2, 3)
tp02 = (4, 5)
tp03 = tp01 + tp02
print tp03

del tuple  # 删除元组

print "---------------元组"
########################################字典##############################################
print "---------------字典"
dict = {}
dict["one"] = 1
dict["two"] = 2
dict["three"] = "3"

print dict['one']  # 输出键为 "one" 的值
print dict["two"]  # 输出键为 "two" 的值
print dict.get("haha", "none")  # 输出键为 "two" 的值
print dict.has_key("one")  # 是否有该key
dict.setdefault("heihei", 666)  # 如果存在heihei的key就修改值,如果不存在就添加

tinydict = {"aa": "11", "bb": "22", "cc": 33, "dd": 44}
print tinydict  # 输出完整的字典
print tinydict.keys()  # 输出所有键
print tinydict.values()  # 输出所有值

del tinydict["aa"]  # 删除aa
tinydict.clear()  # 清空
del tinydict  # 删除词典

print "---------------字典"
########################################运算符##############################################
print "---------------运算符"

a = 11
b = 5
c = 2

print a + b
print a - b
print a * b
print a / b
print a % b
print a ** c
print a // b

print "---------------运算符"
########################################比较运算符#############################################
print "---------------比较运算符"

a = 1
b = 2

if (a == b):
    print "a=b"

if (a > b):
    print "a>b"

if (a < b):
    print "a<b"

if (a <> b):
    print "a<>b"

if (a <= b):
    print "a<=b"

if (a >= b):
    print "a>=b"

if (a != b):
    print "a!=b"

print "---------------比较运算符"
########################################赋值运算符#############################################
print "---------------赋值运算符"
a = 1
b = 2

a += b  # a = a + b
a -= b  # a = a - b
a *= b  # a = a * b
a /= b  # a = a / b
a %= b  # a = a % b
a **= b  # a = a ** b
a //= b  # a = a // b

print "---------------赋值运算符"
#######################################位运算符############################################
print "---------------位运算符"

a = 12  # 1100
b = 5  # 0101

print a & b  # 0100 = 4
print a | b  # 1101 = 13
print a ^ b  # 1001
print ~a
print a << 2  # 0011 0000
print a >> 2  # 0011

print "---------------位运算符"
#######################################逻辑符和成员运算#############################################
print "---------------逻辑符和成员运算"

if (1 == 1 and 0 == 0):
    print "逻辑符和成员运算1"
if (1 == 1 or 1 == 0):
    print "逻辑符和成员运算2"
if (not 1 == 0):
    print "逻辑符和成员运算3"

list = [1, 2, 3, "4", 5]

if (1 in list):
    print "1 in"
if ("4" in list):
    print "字符串4 in"
if (4 not in list):
    print "4 in"

print "---------------逻辑符和成员运算"
#####################################身份运算符##############################################
print "---------------身份运算符"

a = "10"
b = "101"

if (a == b):
    print "a==b"
if (a is b):
    print "a is b"
if (a is not b):
    print "a is not b"
# if (id(a) == id(b)):
#    print "id(a)=" + id(a) + ",id(b)=" + id(b)
#    print "id a is b"
# if (id(a) != id(b)):
#    print "id(a)=" + id(a) + ",id(b)=" + id(b)
#    print "id a is not b"

print "---------------身份运算符"
######################################循环################################################
print "---------------循环"

a = 10

while a > 0:
    a -= 1
    print a
    if (a == 5):
        break

a = 10
while a > 0:
    a -= 1
    if (a > 5):
        print a
else:  # while else 组合循环完成后 执行else 当有break else 不会执行
    print "aaaa"

for a in range(1, 5):
    if (a < 3):
        print a
else:  # for else 同while else
    print "hehe"

print "---------------循环"

#############################字符串########################################################
print "---------------字符串"

a = "lijie"

print a[0]
print a[1:3]
print "j" in a

print "把字符串的第一个字符大写", a.capitalize()
print "全大写", a.upper()
print "小写变大写 大写变小写", a.swapcase()
print "填充", a.center(100)
print "返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数", a.count("lijie", 0, len(a))
print "", a.decode(encoding="UTF-8", errors="strict")

str = "a,b,c,d,e,f"
print "切分成数组", str.split(",")
print "返回指定字符位子", str.find("d")
print "替换所有的", str.replace(",", "##")
print "替换第一个", str.replace(",", "##", 1)

str = "   aaabbb   ccc ddd    "
print "去掉左右空格", str.strip()
print "去掉做空格", str.lstrip()
print "去掉右空格", str.rstrip()

print "---------------字符串"
#######################################数字###############################################
print "---------------数字"

import math, random

num1 = 10.4
num2 = 10.5
num3 = -10

print "绝对值", abs(num3)
print "向上取整", math.ceil(num1)
print "向下取整", math.floor(num2)
print "生成随机数", random.choice(range(0, 10))

print "---------------数字"
#####################################时间################################################
print "---------------时间"
import time

print "时间戳:", time.time()

print "元组时间:", time.localtime(time.time())

mytime = time.localtime(time.time())
print "取出年月日", mytime[0], mytime[1], mytime[2]

mytime = time.asctime(time.localtime(time.time()))
print "格式化时间", mytime

print "时间格式化为字符串", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

timeStr = "2010-10-10 12:12:12"
print "字符串格式化成元组时间", time.strptime(timeStr, "%Y-%m-%d %H:%M:%S")
print "字符串格式化成时间戳", time.mktime(time.strptime(timeStr, "%Y-%m-%d %H:%M:%S"))

import calendar

cal = calendar.month(2016, 1)
print "日历打印", cal

print "---------------时间"
####################################h函数#################################################
print "---------------函数"


def printme(str):  # 定义函数
    print str;
    return;


printme("我要调用用户自定义函数!");  # 调用函数
printme("再次调用同一函数");
printme(str="再再次调用同一函数");


def printinfo(name, age, addr="chongqing"):
    print "Name: ", name;
    print "Age ", age;
    print "addr ", addr;


printinfo(age=25, name="lijie", addr="shengzhen");


def printsomething(first, *others):
    print first
    for pri in others:
        print pri,
    return


print printsomething("one")
print printsomething("one", "two", "three")

sumLambda = lambda a, b: a + b

print sumLambda(1, 2)

print "---------------函数"
###################################IO##################################################
print "---------------IO"

print "屏幕输出IO"
# print raw_input("请输入(标准输入读取行):")

# print input("请输入(作为python表达式输入):")

fo = open("test.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace
fo.close

fo = open("test.txt", "wb")
fo.write("hello world!\nword count!\n");
fo.close()

fo = open("test.txt", "r+")
# print fo.read()
print fo.read(5)
print fo.tell()  # 定位上面read的offset位置
fo.seek(0, 0)  # 还原定位
print fo.read(5)  # 上面还原定位了   不然从上面偏移为5开始
fo.close()

import os

#os.rename("test.txt","newtest.txt") #重命名
#os.remove("newtest.txt") #删除文件
#os.mkdir("testdir")    #创建目录
#os.rmdir("testdir")    #删除目录
#os.chdir("./testdir")  #切换目录  同cd一样
#os.mkdir("testdir")    #上面切换目录后再创建目录
print os.getcwd()      #获取当前绝对路径

print "---------------IO"
##########################################################################################
#####################################lambda表达式##################################################
def outFunc(func, x, y):
    print (func(x, y))


outFunc(lambda x, y: x + y, 1, 2)

#####################################时间处理##################################################
###时间函数
import time, datetime

##时间元组
localtime = time.localtime(time.time())
print localtime
print localtime.tm_mday
print localtime[2]

##时间转字符串
print time.strftime("%Y-%m-%d %H:%M:%S")
print datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
print str(datetime.datetime.now())[:19]

##字符串转时间
mytime = "2017-10-10 10:10:10"
mytime1 = datetime.datetime.strptime(mytime,"%Y-%m-%d %H:%M:%S")

##时间转秒
print time.mktime(mytime1.timetuple())

##秒转时间
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

#时间步长,用于时间的加减
oneday=datetime.timedelta(days=1)
today=datetime.date.today()
print today
tomorrow = datetime.date.today() + oneday
print tomorrow
yesterday = datetime.date.today() - oneday
print yesterday
datetime.timedelta(milliseconds=1), #1毫秒
datetime.timedelta(seconds=1), #1秒
datetime.timedelta(minutes=1), #1分钟
datetime.timedelta(hours=1), #1小时
datetime.timedelta(days=1), #1天
datetime.timedelta(weeks=1) #1周



##########################################函数##########################################
def func01():
    print "hello world"

def func02(str):
    print str

def func03(x,y):
    print x+y

def func04(myfunc01,x,y):
    print myfunc01(x,y)

def func05(name,age=25):
    print name,age

def func06(name, *myvar):
    for a in myvar:
        print name,a


func01()
func02("hehe")
func03(1,2)
func04(lambda x,y:x+y,2,5)
func05("lijie")
func05("lijie",100)
func06("lijie","a","b",1,2,3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值