Learning Python

来源:互联网 发布:游戏显示器推荐 知乎 编辑:程序博客网 时间:2024/05/18 03:00

Python 流行多年,一直没有机会使用它,现在先了解,学习一下了。

Python 是一种解释型,面向对象,动态数据类型的语言。它也能像Java一样,多平台可用。

中文的有个 Python开发者门户 似乎不错。

官网上有一个教程不错,从它开始学习 -- Python Tutorial

先列举一些需要注意单地方:

  • 备注:单行备注使用 # ,多行备注使用 ‘’‘ (三个单引号)
  • 计算符号: ** 表示 乘方 , // 表示对 除法结果向下取整 
  • if 语法: elif 表示 else if
  • 方法定义:def 方法名:, 例如: def someFunction():  。Python 根据缩进决定方法的内容。方法名后的代码行,有缩进表示 方法的内容。
  • for loop:数字循环比较简单,例如:for i in range (0, 4): ,表示循环4次。for 后面的下一行为 for loop内容,同样根据缩进决定。
  • while loop: 数字的同样简单:
    a = 1while a < 10:  print (a)  a+=1
  • String: substring 的语法为 [begin: end]
  • List:简单方便。例如:定义 someList = [0, 1, 2, 3, 4]  , 遍历 for a in someList:
  • Tuples (元组):Tuple 是不可变的 list ,一旦创建,就不能修改 。使用 () 创建Tuple。 关于 Tuple和list的区别,网上很多解释,可以查查。
  • Directories:这个跟Java中多Map类似,
    myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}for a in myExample:  print (a, myExample[a])  
  • print: print() 一个参数和多个参数的结果有差异,多个的时候,输出结果有 括号
  • Exceptions:try:/except: 来捕捉异常。优雅的捕捉异常的方式见下
    var1 = '1'try:    var2 = var1 + 1 # since var1 is a string, it cannot be added to the number 1except:    var2 = int(var1) + 1print(var2)
  • Read file:打开文件和读取内容,十分简单。切记,记得关闭 ,例子见下
    f = open("test.txt","r") #opens file with name of "test.txt"print(f.read(1))print(f.read())f.close()
  • Write file:写文件依然很简单
    f = open("test.txt","w") #opens file with name of "test.txt" ,第二个参数w表示写,a 表示追加f.write("I am a test file.")f.write("Maybe someday, he will promote me to a real file.")f.write("Man, I long to be a real file")f.write("and hang out with all my new real file friends.\n") # 按行写的话,只需最后加上换行符 \n 即可。
    f.close()
  • 创建类和使用类:语法比较简单,先看了一下例子,日后要深入研究
    #ClassOne.py class Calculator(object):    #define class to simulate a simple calculator    def __init__ (self):        #start with zero        self.current = 0    def add(self, amount):        #add number to current        self.current += amount    def getCurrent(self):        return self.current
    使用类
    from ClassOne import * #get classes from ClassOne filemyBuddy = Calculator() # make myBuddy into a Calculator objectmyBuddy.add(2) #use myBuddy's new add method derived from the Calculator classprint(myBuddy.getCurrent()) #print myBuddy's current instance variable

0 0
原创粉丝点击