---
title: "python语法学习整理"
author: "gogole_09"
date: "2011-12-03T22:28:24Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-12-03T22:28:24Z"
id: 1290762
url: "https://gogole.iteye.com/blog/1290762"
---

简单整理一下，Python的语法，细节就不多啰嗦了。

 **while  和 if else if 的使用**

```
while running:
        guess = int(raw_input('Enter an integer :' ))
        if guess == number:
                print 'Congratulations , you guessed it.'
                running = False
        elif guess  > number:
                print 'No,it is a litter higher than that'
        else:
                print 'No it is a litter lower than that'
else:
        print 'The while loop is over.'
```

 

**输入输出：**  
 输入：

```
int(raw_input('xxxx'))
```

 

 **for 循环**

```
for i in range(1,5)
  'it's xxx'
else
  print 'Over'
```

 

**自定义函数：**

```
def fun():
    xxxxxx

调用:
 fun()
```

 

 其中需要使用到的全局变量则按照如下规则： 

 global x 来指定是否为全局变量

```
def func():
    global x

    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x
```

 

 **函数里面可以使用默认参数来指定参数的默认值：**

 def func(name='hellp0',age)  
   xxxxx  
关键参数：  
  def func(a=5,b=3,c=2)  
    xxxx  
 func(1,2,3)  
 关键参数的调用方式： func(c=5,b=222)

 

**python 的 DocStrings**  
  使用它进行字符串的打印， 如下程序：  
   
**python 的模块：**  
     可以类似于Java一样，引入一些包名，比如 import sys  
     每个模块都有一个\_\_name\__  
     比如，main模块则是：

```
if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'
```

 

**创建自己的模块：**  
     简单来说，就是创建一个自己的py后缀的文件，然后将文件放到同一个目录下，  
    再用import 引入文件名即可； 比如：

```
# a.py
def func()
  print 'a.func()'
print 'done'

b.py
import a
print a.func()
```

 

 上面的a就是表示一个模块。

**python的数组和字典**  
  字组就是数组， 比如 （"a","b","C"）  
  字典说白了就是一个kv结构：  a={"a":"1","b":2}

```
ab = {       'Swaroop'   : 'swaroopch@byteofpython.info',
             'Larry'     : 'larry@wall.org',
             'Matsumoto' : 'matz@ruby-lang.org',
             'Spammer'   : 'spammer@hotmail.com'
     }
```