美文网首页
python2入门教程

python2入门教程

作者: Eylen | 来源:发表于2018-06-30 21:02 被阅读0次
  • 循环
    • ex1
n = input("Num of line: ")

for i in range(1,n+1):
    print("*"*i)

print('-----------')

for i in range(0,n):
    print("*"*(n-i))
结果:
  • 数组
    • ex2
a = [10,20,100,10,3,3,0,2,3,10]
print a
print u"第0个元素:",a[0]
print u"由a的第0个到第(2-1)个元素组成的数组:",a[0:2]
print u"由a第2*n个元素组成的数组:",a[0::2]
print u"数组a的长度:",len(a)
print u"数组a里面最小的元素:",min(a)
print u"数组a里面最大的元素:",max(a)
print u"数组a索引为10的元素:",a.index(10)
print u"数组a出现3的次数:",a.count(3)
结果:
  • ex3
#求每个学生的平均分并加到该学生数组的最后一个元素
import json
student = [["张三",60,90,80],["李四",90,91,92],["王五",80,70,70],["王菲",90,30,50]]
for stu in student:
  stu.append((stu[1]+stu[2]+stu[3])/3)
student = json.dumps(student, encoding='UTF-8', ensure_ascii=False)
print(student)
  • 字符串
    • ex4
s = 'hello john'
print s[1],s[2],s[1:2],s[:5],s[1:],s[:]
print 3*s
print len(s)
print str.upper(s)
print s.split() #默认空格切
print"hello, my dear".split()
print"hello, my dear".split(',')
结果:
  • ex5
s = '你好'
print(s)
print type(s)
s = u'你好'
print(s)
print type(s)
结果:
  • 字典
    • ex6
dic = {}
# 基本操作
dic['001'] = 2
dic['002'] = 1
print dic
print dic['002']
print dic.get('001')
print dic.keys()
print dic.values()
print dic.items()

# 遍历
for (key, value) in dic.items():
    print key,value

for (key, value) in dic.iteritems():
    print key,value

# 排序
print sorted(dic.iteritems(), key = lambda x:x[0], reverse = False)
print sorted(dic.iteritems(), key = lambda x:x[1], reverse = False)
结果:
  • 读取文件
    • ex7
infile = open('text.txt','r')
print infile.read() #读取全部,以字符存储
print type(infile.readline())#str
print infile.readline() #读取光标所在的行
lines=infile.readlines() #读取所有行,以行在存储
print type(infile.readlines()) #list
for line in lines:
   print line
infile.close()
  • 读取中文文件
    • ex8
import codecs
file = codecs.open('text.txt','r','utf-8')
lines = file.readlines()
file.close()
for line in lines:
  print line
  • 写入文件、随机数
    • ex9
import random
f = open('write_test.txt','w')
i = 0;
avg = 0;
while i < 100:
    n = random.random() #0-1
    avg += n
    f.write(str(n) + '\n')
    i += 1
avg /= 100
f.write("平均值:" + str(avg) + '\n')
f.close()
print u"平均值",avg
  • 函数
    • ex10
def Sum(n):
    sum = 0
    for i in range(n+1):
        sum += i
    return sum


def main():
    n = input('please input n: ')
    print '1 + 2 + ... + n =',Sum(n)

main()
  • ex11 递归
# n!
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)

print fact(3)
  • ex12 lambda
# def f(x,y,z):
#     return x+y+z

f = lambda x,y,z:x+y+z
print f(1,2,3)
    • ex13
class Person:
    def __init__(self, name, age, interesting): #构造函数
        self.name = name
        self.age = age
        self.interesting = interesting

    def GetName(self): #方法
        return self.name

p = Person('jay',10,'ball') #实例化一个Person
print p.GetName() #jay
  • 继承
class Student:
    def __init__(self,name,ch,math,en):
        self.name = name
        self.ch = ch
        self.math = math
        self.en = en

    def getName(self):
        return self.name
    def getAvgScore(self):
        return (self.ch + self.math + self.en)/3.0
    def getMath(self):
        return self.math

# 继承
class S(Student):
    def work(self):
        return 'work'
ss = S('xx',10,10,10)
print ss.work(),ss.getAvgScore()

相关文章

网友评论

      本文标题:python2入门教程

      本文链接:https://www.haomeiwen.com/subject/gclxuftx.html