欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python入门小案例

程序员文章站 2022-05-19 13:32:25
...

Python入门小案例:

print('hello')


def test():
    print('Mr zhang')


test()

if __name__ == '__main__':
    print('world')


class Fish:
    hungry = True

    def eat(self, food):
        if food is not None:
            self.hungry = False


class User:
    def __init__(self, name):
        self.name = name


f = Fish()
Fish.eat(f, None)
print(f.hungry)

Fish.eat(f, 'earthworm')
f.eat('eatworm')
print(f.hungry)
u = User('zhangjun')
print(u.name)


def test2():
    count = 0
    count = count + 1
    count += 1
    count -= 1
    count = count * 10
    count *= 10
    name = 'Blob'
    # return name
    x = y = z = 1
    print(x, y, z)
    x, y, z = 1, 2, 'a string'
    print(x, y, z)
    x, y = y, x
    print('%d mile is the same as %f km' % (x, y))


test2()
print('**' * 5)
pystr = 'zhangjun'
print('%s is cool' % (pystr))

# 元组tuple
# 身有残疾的只读列表
aTuple = ('robert', 77, 93, 'try')
print(aTuple[1:3])
print(type(aTuple))
# aTuple[1] = 5
for x in aTuple:
    print(x)

# 列表
# 左闭右开,
# -1表示最后一个元素
aList = [1, 2, 3, 'a string']
print(aList[0])
print(aList[2:])
print(aList[:3])
aList[1] = 5
print(aList)
for x in aList:
    print(x)



字典:

# 字典 key-value 键值对
dict1 = {'name:' : '张君', 'age' : 21, 'interest:' : '唱歌'}
print(dict1)
print(type(dict1))
namekey = 'name'
dict2 = {namekey : '张君'}
print(dict2)
# 1表示一个key
dict3 = {'name:' : '张君', 'age' : 21, 'interest:' :['唱歌', '跳舞' ,'打游戏'], 1 : [100, 200, 300]}
print(dict3)
# TypeError: unhashable type: 'list'  --hash表示哈希算法
# dict1 = {'name:' : '张君', 'age' : 21, 'interest:' : '唱歌',[100, 200, 300] :1}
# print(dict1)

# 访问字典的内容 、 读写 、删键del
# del dist['name']   del dist
# 字典-面向对象的方法 dict.clear()、dict.keys()、dict.values()
dict3 = {'name' : '张君', 'age' : 21, 'interest' :['唱歌', '跳舞' ,'打游戏'], 1 : [100, 200, 300]}
myname = dict3['name']
print(myname)
myage = dict3['age']
print(myage)
myhobby = dict3['interest']
print(myhobby)
myint = dict3[1]
print(myint)
#  str(myint)  str(myage) +
print(myname, myage, myhobby, myint)

Python入门小案例