您的位置:首页 > 编程语言 > Python开发

python入门教程

2015-11-21 12:59 696 查看
0参考网站

          http://www.liaoxuefeng.com/wi0014316089557264a6b348958f449949df42a6d3a2e542c000
1 输入和输出

value1=raw_input() python2可以,但是python3是 input()

print(“hello”)不要分号;单引号也可以

print(value1)

格式化输出

name='wtt';age=23;print 
'your name is %s and your age is %d' %(name,age)

2 字符串的连接

print(”hello”+”world”)

3 数值运算

print(100+200)出来的是300

4 变量

由于不用事先申明变量,所以给他赋值是什么就是什么类型的。命名规则和c一样

5 常量

全部大写的字母组成 例如 PI

6 字符和数字的相互转换

print ord('A')
print chr(65)

7 list tuple 

   []  ()  

classmates=['st1','stu2','stu3','stu4']
print classmates[0]
classmates.append('stu5')
print classmates[4]
print classmates.insert(2,'StuInsert')
print classmates
print len(classmates)

  tuple主要用于值不改变的数组。唯一的好处就是安全

8 dict set

    dict

    dic1 = {'stu1':90,'stu2':80,'stu3':70,'stu4':60,'stu5':50}
print dic1['stu1']

dic1['stu1']=100
print dic1['stu1']

dic1['stu6']=40
print dic1['stu6']

dic1.pop('stu6')
print len(dic1)
if 'stu7' in dic1 :

    print dic1['stu7']
else:

    print 'no index stu7 in dic1 for in'
if dic1.get('stu5'):

    print dic1['stu5']
else:

    print 'no index stu5 in dic1 for get'

     set

set其实就是数学中的集合,无序,不可重复。

s = set ([1,2,3])
print s

s.add(4)
print s

s.remove(4)
print s

s1 = set ([1,2,4])
s2 = set
([1,2,3])
print s1 |
s2
print s1 &
s2

9 判断

sex = 'male'
if sex == 'male':

    print 'you are male'

    print 'right?'
else:

    print 'you are female'

    print 'right?'

age = 23
if age > 60 :

    print 'you are old man'
elif age > 20:

    print 'you are strong man'
else:

    print 'your are not old enough'

year = input()
if year > 1992 :

    print 'you are elder than me'
else:

    print 'l am elder than you’;

10 循环

只有两种 for in 和 while

age = 100
_sum =0
while age > 0:

    _sum = _sum + age

    age = age -1
print _sum

classmates = ['st1','st2','st3','st4']
for stu in
classmates :

    print stu

11 函数和编码以及pass

官网

https://docs.python.org/2/library/functions.html#abs

#!/usr/bin/env python

# -*- coding: utf-8 -*-
print '请输入x'
x = input()
def my_abs ( x ) :

 if x >= 0:

  return x

 else:

  return -x

x_form_my_fun = my_abs(x)
print x_form_my_fun

定义一个空操作的函数

def pop():

    pass;

如果想直接退出函数体,可以直接写 return

检查参数 在log中提示错误

def my_abs(x):

    if not isinstance(x, (int, float)):

        raise TypeError('wrong type le')

        return

    if
x >= 0:

        return x

    else:

        return -x

y = raw_input()
print my_abs(y)

返回多个值以及变量类型强制转换

(其实返回的一个tuple)

def muti_valus_return (x,y):

    x_int = int(x)

    y_int = int (y)

    x_int = x_int +1

    y_int = y_int +1

    return x_int,y_int

x=raw_input()
y=raw_input()

x1,y1=muti_valus_return (x,y)
print x1
print y1
print muti_valus_return (x,y)

默认参数

def defualt_para (x,y=2):

    x_int = int(x)

    y_int = int (y)

    s=1

    while y_int > 0
:

        s = s * x_int

        y_int = y_int - 1

    return s

x=raw_input()

y=raw_input()

x1= defualt_para(x,y)
x2= defualt_para(x)
print x1
print x2

12 片段的截取

 python中没有对字符串进行切割的方法,但是提供了切片的方法

list1=['l1','l2','l3','l4','l5']

list2= list1[-3:]

list3= list1[2:5]
print list2
print list3

str1='012345'
str2=str1[2:4]
print str2

13 数组字典等的遍历(迭代)

d = {'a': 1,
'b': 2,
'c': 3}
for my_key in
d:

    print my_key
for my_value in
d.itervalues() :

    print my_value
for key_value
in d.iteritems() :

    print key_value

14 自动生成数字(列表生成式)

L1 = []
L1 = range(1,11)
print L1

L2 = [x * x
for x in range(10)]
print L2

15 map/reduce

map

map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。函数的参数就是序列中的每一个。

def func_map(x):

    return x*x

list1=[1,2,3,4,5]

list2=map(func_map,list1)
print list2

reduce

reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

def func_reduce(x,y):

    return x + y

list1=[1,2,3,4,5]

list2=reduce(func_reduce,list1)
print list2

16 try except

# -*- coding: utf-8 -*-
str1=raw_input()
try:

    print str1+1
except:

    print 'please input int type'

17 模块(其实就是类库)

test_module.py

# -*- coding: utf-8 -*-

'a test module'

__author__ = 'wangtuntun'
import sys

def test():

    args=sys.argv

    if(len(args) == 1):

        print __parivate_1

    elif len(args) == 2 :

        print 'hello,%s' %args[1]

    if len(args) >2:

        print 'too many parameters'
__parivate_1='hello,world'

__public1__='this is a public parameter form test_module.py'
if __name__ == '__main__ :' :

    test()

call_test_module.py

# -*- coding: utf-8 -*-

'test_LXF module'

__author__ = 'wangtuntun'

import test_module

test_module.test()

print test_module.__public1__

两个英文的_  如果前后都有,就是全局的,可供其他文件调用;如果只有前面有,就是局部的,只供本文件调用。

if  __name__ == ‘__main__’ ,是用来在命令行调用 python test_module.py

当调用是,自动将name设置为main 。如果是其他文件调用则实效

 ‘test_lxf module’  文件中的第一个字符串是注释

18 安装第三方模块

在Python中,安装第三方模块,是通过setuptools这个工具完成的。Python有两个封装了setuptools的包管理工具:easy_install和pip。目前官方推荐使用pip。如果你正在使用Mac或Linux,安装pip本身这个步骤就可以跳过了。常用的第三方库还有MySQL的驱动:MySQL-python,用于科学计算的NumPy库:numpy,用于生成文本的模板工具Jinja2,等等。

一般来说,第三方库都会在Python官方的pypi.python.org网站注册,要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,比如Python Imaging Library的名称叫PIL,因此,安装Python Imaging Library的命令就是:pip install PIL

但是我自己在终端安装的时候,提示:-bash: pip: command not found

那就说明你的电脑没有安装pip工具。可以现在终端利用easy_install安装pip

命令:sudo easy_install pip

安装好pip以后,可以安装pandas ,命令 : sudo install pandas

一般还是在前面加上sudo的好,否则下载了半天,安装的时候提示你权限不够

一般在终端安装好了以后,无需在ide中再配置

19 类和对象

class Student(object)表示继承自object类

__name 表示name时类内部的,对象不能访问

如果需要获取,可以调用get方法;如果需要改变值,可以调用set方法。

 __init__(slef,name,score)初始化方法是必须的。self参数也是必须的

class Student(object):

    __name=''

   
__score=''

   
def __init__(self,name,score):

        self.__name=name

        self.__score=score

    def get_name(self):

        return self.__name

    def set_name(self,name):

        self.__name=name

    def get_score(self):

        return self.__score

    def set_score(self,score):

        self.__score=score

xiaoming=Student('xiaoming',100)
print xiaoming.get_name()
print xiaoming.get_score()

xiaoming.set_name('xm')

xiaoming.set_score(10)
print xiaoming.get_name()
print xiaoming.get_score()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息