Python学习笔记【一】

喜欢Python的简洁 语言就应该注重实现的功能而不拘于冗余的语法结构

Python基本语法

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

if __name__ == "__main__":
    
print "hello world"

 

Python文件类型

  *.py 源文件

  *.pyc字节码文件,可在多个操作系统下执行

变量、模块命名规则:

变量、模块名的命名规则

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 变量、模块名的命名规则
# Filename: ruleModule.py

_rule = "rule information"

#面向对象中的命名规则
class Student:                      # 类名大写
    __name = ""                     # 私有实例变量前必须有两个下划线
    def __init__(self, name):
: #000000; font-size: 12pt">        self.__name = name          # self相当于Java中的this
    def getName(self):              # 方法名首字母小写,其后每个单词的首字母大写
        return self.__name

if __name__ == "__main__":
    student = Student("borphi")     # 对象名小写
    print student.getName()
# 函数中的命名规则
import random

def compareNum(num1, num2):
    
if(num1 > num2):
        
return 1
    
elif(num1 == num2):
        
return 0
    
else:
        
return -1
num1 = random.randrange(192)
num2 = random.randrange(192)
print "num1 =", num1
print "num2 =", num2
print compareNum(num1, num2)
  
# 不规范的变量命名
sum = 0
= 2000
= 1200
sum = i + 12 * j
# 规范的变量命名
sumPay = 0
bonusOfYear = 2000
monthPay = 
1200
sumPay = bonusOfYear + 12 * monthPay

 

 


 

 

模块导入方式:

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

#规范导入方式
import sys

print sys.path
print sys.argv

#不规范导入方式
from sys import path
from sys import argv

print path
print argv

 

 


分隔语句的使用:

 

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

# 下面两条语句是等价的
print "hello world!"
print "hello world!";
# 使用分号分隔语句
= 1; y = 1; z = 1
# 一条语句写在多行
print \
"hello world!"
# 字符串的换行
# 写法一
sql = "select id,name \
from dept \
where name = 'A'"
print sql
# 写法二
sql = "select id,name " \
      
"from dept " \
      
"where name = 'A'"
print sql

 

 


 

变量命名:

= 1
print id(i)
= 2
print id(i)

 

打印出来的两个变量的id是不一样的,说明不是同一个对象。

 


多个变量赋值:

#多个变量的赋值
= (123)
(x, y, z) = a

 


三引号用法:

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

# 单引号和双引号的使用是等价
str = "hello world!"
print str
str = 'hello world!'
print str

# 三引号的用法
str = '''he say "hello world!"'''
print str
# 三引号制作doc文档
class Hello:
    
'''hello class'''
    
def printHello():
        
'''print hello world'''
        
print "hello world!"
print Hello.__doc__
print Hello.printHello.__doc__

# 转义字符
str = 'he say:\'hello world!\''
print str
# 直接输出特殊字符
str = "he say:'hello world!'"
print str
str = '''he say:'hello world!' '''
print str
    

 


 

 

输入: 

= input("x:")
print x
= raw_input("x:")#输入字符串 可以用x=int(x)进行类型转换
print x
###############运行结果############
#     x:1+2
#     3
#     x:1+2
#     1+2

 


 实现switch功能:

 

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

#方法一: 使用字典实现switch语句
from __future__ import division
= 1
= 2
operator = "/"
result = {
    
"+" : x + y,
    
"-" : x - y,
    
"*" : x * y,
    
"/" : x / y 
}
print result.get(operator)   
######################################################################################
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#方法二:利用类实现

class switch(object):
    
def __init__(self, value):      # 初始化需要匹配的值value
        self.value = value
        self.fall = False           # 如果匹配到的case语句中没有break,则fall为true。

    
def __iter__(self):
        
yield self.match            # 调用match方法 返回一个生成器
        raise StopIteration         # StopIteration 异常来判断for循环是否结束

    
def match(self, *args):         # 模拟case子句的方法
        if self.fall or not args:   # 如果fall为true,则继续执行下面的case子句
                                    # 或case子句没有匹配项,则流转到默认分支。
            return True
        
elif self.value in args:    # 匹配成功
            self.fall = True
            
return True
        
else:                       # 匹配失败
            return False

operator = "+"
= 1
= 2
for case in switch(operator):        # switch只能用于for in循环中
    if case('+'):
        
print x + y
        
break
    
if case('-'):
        
print x - y
        
break
    
if case('*'):
        
print x * y
        
break
    
if case('/'):
        
print x / y
        
break
    
if case():                      # 默认分支
        print ""

operator = "+"
= 1
= 2
for case in switch(operator):        # switch只能用于for in循环中
    if case('+'):
        
print x + y
    
if case('-'):
        
print x - y
    
if case('*'):
        
print x * y
        
break
    
if case('/'):
        
print x / y
    
    break
    
if case():                      # 默认分支
        print ""

 

 

 


 

while循环的使用:

 

while
#!/usr/bin/python
# -*- coding: UTF-8 -*-
= 1
while i > 0:
    i = i + 1
    
print i
    
# while循环
numbers = raw_input("输入几个数字,用逗号分隔:").split(",")
print numbers
= 0
while x < len(numbers):                   
    
print numbers[x]
    x += 1

# 带else子句的while循环
= input("输入x的值:")
= 0
while(x <> 0):   
    
if(x > 0):
        x -= 1
    
else:
        x += 1
    i = i + 1
    
print "第%d次循环:" %i, x
else:
    
print "x等于0:", x

 


 

 

posted on 2009-12-12 14:43    阅读(468)  评论(2编辑  收藏  举报

导航