python笔记及作业

1.python与其他语言的比较

- c, c++, java, php, javascript, vb, c#...

- 任何的编程语言都是为了让计算机干活,

  eg:下载音乐,电影,编辑一文档... 而cpu只认识机器指令

- 不同的编程语言,实现同一功能,编写代码量,差距很大

   C >> python

- 代码少的代价是运行速度慢

 

2.python能做什么?

- 日常任务,小工具,eg:备份mp3,系统管理员需要的脚本任务

- 做网站,eg:YouTube,国内的豆瓣,Google,Yahoo

- 网络游戏的后台

- 爬虫

 

3.python环境

 

linux:

yum install python -y

python

 

vim,gedit

 

windows:

 

4.ipython的应用

 

输出:print

In [15]: print '100+100=',100+100

100+100= 200

 

In [16]: print '100+100='100+100

  File "<ipython-input-16-6f9764806dca>", line 1

    print '100+100='100+100

                      ^

SyntaxError: invalid syntax

 

 

In [17]: print '100+100=',100+100

100+100= 200

 

 

输入:raw_input()

 

第一个程序:

#!/usr/bin/python

 

#coding:utf-8

#coding=utf-8

#encoding:utf-8

#encoding=utf-8

#-*-coding:utf-8-*-                                 ##编码格式

 

a=raw_input("please input a:")

b=raw_input("please input b:")

 

print 'a+b=',int(a)+int(b)

 

 

a= 1                    

 

###当使用raw_input时,默认输入的是字符串类型,直接赋值时则固定是什么类型就是什么类型

 

5.类型

 

complex 复数

 

a = 2j+3

 

6.序列

v1:三個雙引號的作用,自動添加分隔符,換行等。

In [87]: mail = """FTT:

   ....:           hello

   ....:           l hate you

   ....: """

 

In [88]: print mail

FTT:

   hello

   l hate you

 

 

In [89]: mail

Out[89]: 'FTT:\n\t   hello\n\t   l hate you\n'

 

 

v2:切片

a = "abcde"                        ##編號時是從靈开始

a[1:5:2]                           ##第一個到第四個,且每隔一個一切

a[:5:2]

a[1:5]

a[-1]

a[-4:-1]

a[-1:-4]

a[-2:-4}

a[-2:-4]

a[-2:-4:1]

a[-2:-4:-1]

 

v3:%s,%d,%f,%x

%s

v4:cmp

In [111]: str1 = 123

 

In [112]: str2 = 456

 

In [113]: cmp(str1,str2)

Out[113]: -1

 

In [114]: cmp(str2,str1)

Out[114]: 1

 

v5:包含与不包含关系

in 后字符串包含前字符串

not in 前字符串不在后字符串中

 

v6:元组

In [116]: t = (1)

 

In [117]: type(t)

Out[117]: int

 

In [118]: user1 = ("fentiao",4,"male")

 

In [119]: user2 = ("wanglang",5,"famale")

 

In [120]: user1[0]

Out[120]: 'fentiao'

 

In [121]: user2[0]

Out[121]: 'wanglang'

 

##快速赋值##

 

In [128]: user1

Out[128]: ('ftt', 5, 'famale', 'hate')

 

In [132]: name,age,gender,kind = user1

 

In [133]: print name,age,gender,kind

ftt 5 famale hate

 

v7:列表 list

In [136]: user1 = ["ftt","i","miss","you"]

In [137]: user1.reverse()                      ##反转输出

 

In [138]: user1

Out[138]: ['you', 'miss', 'i', 'ftt']

 

In [155]: user1.extend(["just","so","so"])            ##可以添加多个列表

 

In [156]: user1

Out[156]: ['ftt', 'i', 'miss', 'you', 'just', 'so', 'so']

 

In [151]: user1

Out[151]: ['ftt', 'i', 'miss', 'you', 1, 2, 3]

In [154]: user1.remove(3)                            ##删除想要删除的元素

 

###字符串編碼的歷程##        ASCII -> GB2312 -> Unicode -> utf-8

 

v8:集合

 

In [13]: s1 = {1,2,3,4}

 

In [14]: s2 = {2,3}

 

a.差集

In [15]: s1.difference(s2)

Out[15]: {1, 4}

 

In [16]: s1.difference_update(s2)

 

In [17]: s1

Out[17]: {1, 4}

 

b.交集

In [22]: s1.intersection(s2)

Out[22]: {2, 3}

 

In [23]: s1.inte

s1.intersection         s1.intersection_update  

 

In [23]: s1.intersection_update(s2)

 

In [24]: s1

Out[24]: {2, 3}

 

c.并集

In [27]: s1.union(s2)

Out[27]: {1, 2, 3, 4}

 

d.update 可以添加一个列表

e.isdisjoint 有交集则输出false

f.remove和discard的区别 remove 删除没有的元素会产生错误,discard删除没有的元素不会产生错误

g.issubset 真子集 issuperset 子集

 

 

####元组、列表、集和之间的转化####

list()

 

  1 #!/usr/bin/python

  2 #coding:utf-8

  3 import getpass

  4 for i in range(1,4):

  5         user = raw_input("please input your username:")

  6         password = getpass.getpass("please input your passwd:")

  7

  8         if ((user == "fentiao") & (password == "westos")):

  9                 print "登陆成功"

 10                 break

 11         elif i<4:

 12                 print "请重新输入:"

 13                 i+=1

 14         else:

 15                 print "冻结"

 

 

#######迭代#########

适用于集合,列表,元组

 

集合中,按顺序输出一次

 

In [2]: it = iter((1,2,3,4))

 

 

In [4]: it.next()

Out[4]: 1

 

In [5]: it.next()

Out[5]: 2

 

In [6]: it.next()

Out[6]: 3

 

In [7]: it.next()

Out[7]: 4

 

In [8]: it.next()

---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-8-54f0920595b2> in <module>()

----> 1 it.next()

 

StopIteration:                   ##抛出异常

 

########字典##########

In [17]: dic = {'name':'ftt','age':20,'sex':'famale'}

 

In [18]: dic.

dic.clear       dic.items       dic.pop         dic.viewitems

dic.copy        dic.iteritems   dic.popitem     dic.viewkeys

dic.fromkeys    dic.iterkeys    dic.setdefault  dic.viewvalues

dic.get         dic.itervalues  dic.update      

dic.has_key     dic.keys        dic.values      

 

In [18]: dic.keys()

Out[18]: ['age', 'name', 'sex']

 

In [19]: dic.items()

Out[19]: [('age', 20), ('name', 'ftt'), ('sex', 'famale')]

 

In [20]: a,b=(1,2)

 

In [21]: for k,v in dic.ite

dic.items       dic.iteritems   dic.iterkeys    dic.itervalues

 

In [21]: for k,v in dic.items

dic.items

 

In [21]: for k,v in dic.items():

   ....:     print k,v

   ....:     

age 20

name ftt

sex famale

3.删除

del dic || del dic["name"或者"value"] || dic.pop("name")||dic.clear()

 

v1:

In [35]: dic = {'name':'ftt','age':20,'sex':'famale'}

 

In [36]: del dic["name"]

 

In [37]: dic

Out[37]: {'age': 20, 'sex': 'famale'}

 

v2:

In [41]: dic.pop('age')

Out[41]: 20

 

In [42]: dic

Out[42]: {'sex': 'famale'}

 

 

 

####Pycharm Community #########

 

#!/usr/bin/env python

#coding:utf-8

 

while 1:

        a = raw_input("q or c:")

        if a == "q":

            break

        elif a == "c":

            continue

        elif a == "n":

            pass

        else:

    print "Error "

 

for i in range(1,4):

    a = raw_input("num:")

    if a == "q":

        break

    elif a == "c":

        continue

    elif a == "n":

        pass

    else:

        print("Error")

##如果for循环正常退出的话,则输出else body

else:

    print("else body")

 

from __future__ import division

函数  

 

abs(num)

                      功能

返回 num 的绝对值

coerce(num1, num2) 将num1和num2转换为同一类型,然后以一个  元组的形式

返回。

divmod(num1, num2) 除法-取余运算的结合。返回一个元组(num1/num2,num1 %

num2)。对浮点数和复数的商进行下舍入(复数仅取实    

数部分的商)

pow(num1, num2, mod=1) 取 num1 的 num2 次方,如果提供 mod 参数,则计算结果

再对 mod 进行取余运算  

round(flt, ndig=0) 接受一个浮点数  flt  并对其四舍五入,保存  ndig位小数。

若不提供ndig  参数,则默认小数点后0位。

 

#########函数###################

def myadd(x,y):

    """

 

    :rtype : object

    """

    if isinstance(x,(int,float,long)) and isinstance(y,(int,float,long)):

        print x + y

    else:

        print "error type"

 

 

myadd(1,2)

myadd(1,"hello")

 

def func1():

    a = 2

    #global b

    b = 3

    print a

 

 

func1()

print b

 

 

 

 

 

#!/usr/bin/env python

# coding:utf-8

 

count = input("Enter total number of names:")

li = []

 

for i in range(1, count + 1):

    yname = raw_input("please enter name %d:"

    %i)

    if "," in yname :

        li.append(yname)

    else:

        print("please again enter!")

        for j in range(0,2):

            yname = raw_input("please enter name %d:"

            %i)

            if "," in yname:

                li.append(yname)

                break

            elif j in range(0,1):

                print("please again enter!")

            else:

                print "机会用完"

                break

else:

        print("the result of sort:%s" %sorted(li))

 

 

 

##############################作业####################################

#!/usr/bin/env python

#coding:utf-8

 

from time import time,ctime

db = {}

def Newuser():

     name = raw_input('请输入用户名:')

     if name in db:

passwd1 = raw_input('请输入密码:')

        if passwd1 == db.get(name)[0]:

  print '欢迎回来',name

print '你已经登陆过在:',ctime(db[name][1])

now = time()

timediff = now - db[name][1]

if timediff <= 14400:

print '你在四小时之内已经登录过了!'

else:

logintime = time()

db[name][1] = logintime

     else:

a = raw_input('该用户不存在,是否需要建立(y/n):')

if a == 'y':

while True:

name = raw_input('请输入用户名:')

if db.has_key(name):

name1 = raw_input('该用户已经存在,重新输入:')

continue

else:

break

passwd = raw_input('请输入密码:')

  logintime = time()

       db[name] = [passwd,logintime]

print '建立用户成功'

else:

Newuser()

     showmenu()

def Deluser():

print db

name = raw_input('请输入你要删除的用户:')

del db[name]

showmenu()

def showmenu():

     print """

     1.用户登录

     2.用户删除

     3.显示清单

     4.退出"""

     a=raw_input("请输入你的选择:")

     if a == '1':

Newuser()

     elif a == '2':

Deluser()

     elif a == '3':

print db

showmenu()

     elif a == '4':

quit

     else:

print 'Input Error'

pass

 

 

showmenu()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值