Python基础学习代码之变量和类型

foo = ‘abc‘
for i in range(len(foo)):
    print "%d , %s" % (i, foo[i])
print [x ** 2 for x in range(5) if not x % 2]
try:
    f = open(‘e:\XIN_370_logic.tx‘, ‘r‘)
    for eachline in f:
        print eachline
    f.close()
except IOError, e:
    print e
def func1(x):
    return x + x
x = [i for i in range(4)]
print func1(x)
def func2(debug=True):
    if debug:
        print ‘true,in debug mode!‘
    print ‘done‘
func2(False)
"""
"""
a = int(raw_input(‘input num1:‘))
b = int(raw_input(‘input num2:‘))
c = int(raw_input(‘input num3:‘))
alist = [a, b, c]
minalist = min(alist)
maxalist = max(alist)
medalist = [x for x in alist if x != minalist and x!= maxalist]
medalist = medalist[0]
print minalist, medalist, maxalist
"""
import os
while True:
    ar = raw_input("read or write file[r/w],enter . to quit>>")
    if ar == ‘w‘:
        ls = os.linesep
        globals(ls)
        while True:
            os.chdir(r"e:\\")
            filename = raw_input(‘input filename:‘)
            if os.path.exists(filename):
                print ‘file %s already exists!‘ % filename
            else:
                break
        all = []
        print "\nenter lines(‘.‘ by is self to quit).\n"
        while True:
            entry = raw_input(‘>>>‘)
            if entry == ‘.‘:
                print ‘quit‘
                break
            else:
                all.append(entry)
        f = open(filename, ‘w‘)
        print all
        for eachline in all:
            f.writelines("%s%s" % (eachline, ls))
        f.close()
    elif ar == ‘r‘:
        filename = raw_input(‘input filename:‘)
        print
        try:
            os.chdir(r"e:\\")
            f = open(filename, ‘r‘)
        except IOError:
            print ‘file %s is not exists!‘ % filename
        else:
            for eachline in f:
                print eachline
            f.close()
    elif ar == ‘.‘:
        break
    else:
        print ‘input error,input again!‘
        continue
时间: 2024-08-03 09:22:42

Python基础学习代码之变量和类型的相关文章

Python基础学习代码之执行环境

class C(object):     def __call__(self, *args, **kwargs):         print "I'm callable! called with args:\n",args c = C() c('a',1) single_code = compile("print 'hello,world!'",'','single') exec(single_code) eval_code = compile('100*3','

Python基础学习代码之数字

# import math # print coerce(1L, 134) # """数据类型转换""" # print coerce(0.4, 123) # print coerce(0j, 234) # print divmod(125, 5) # """除法运算""" # print divmod(4, 3) # print pow(2, 4) # ""&quo

Python基础学习代码之序列

str1 = 'abced' for i in range(-1, -len(str1), -1) + [None]:     print str1[:i] s, t = 'abc', 'def' print zip(s, t) for i, t in enumerate(str1):     print i, t print isinstance('foo', str) import string def checkid():     alphas = string.letters + '_'

Python基础学习代码之映像集合

def func1():     dict1 = {}     dict2 = {'name':'earth','port':80}     return dict1,dict2 def func2():     return dict((['x',1],['y',2])) def func3():     adict = {}.fromkeys(['x','y'],23)     return adict def func4():     alist = {'name':'earth','po

Python基础学习代码之条件和循环

def func1():     alist = ['Cathy','Terry','Joe','Health','Lucy']     for i in  range(-1,-len(alist)-1,-1):         print i,alist[i] def func2():     alist = ['Cathy','Terry','Joe','Health','Lucy']     for i,name in enumerate(alist):         print '%d

Python基础学习代码之文件和输入输出

import os ls = os.linesep def func1():     filename = raw_input('enter file name:')     f = open(filename,'w')     while True:         alline = raw_input("enter a line ('.' to quit):")         if alline != '.':             f.write("%s%s&quo

Python基础学习代码之错误和异常

def func1():     try:         return float('abc')     except ValueError,e:         print e def func2():     try:         astr = 'abc'         float(astr)     except ValueError:         astr = None     return astr def func3():     try:         astr = 

Python基础学习代码之函数和函数式编程

def func1():     print 'hello world' res = func1() print type(res) def func2():     return ['xyz',10000,-98] atuple = func2() x,y,z = func2() print x,y,z def func3():     return 'xyz',1000,-98 x,y,z = func3() print x,y,z def func4():     return ['xyz

Python基础学习代码之面向对象编程

class  AddrBookEntry(object):     'address book entry class'     def __init__(self,nm,ph):         self.name = nm         self.phone = ph         print 'created instance for:',self.name     def updatephone(self,newph):         self.phone = newph