月度存档: 11 月 2018 - 第2页

python3基础7-模块

python的模块和函数命名规则推荐用小写字母+下划线

新建一个food.py的模块,里面定义一个make_food函数

#coding:utf-8
#允许汉语注释
#定义函数
def make_food(a="fruit"):
    print(a)

在相同目录下建立making_food.py

导入整个模块

#coding:utf-8
#允许汉语注释
#导入整个模块,引用方法:module_name.function_name()
import food
food.make_food("apple")
food.make_food("rice")

导入特定函数

#from module_name import function_name
from food import make_food
make_food("orange")

使用as 给函数指定别名

from food import make_food as mf
mf('apple')

使用as 给模块指定别名

import food as f
f.make_food('apple')

导入模块中的所有函数(不推荐)

from food import *
make_food('apple')

python3基础6-函数

#coding:utf-8
#允许汉语注释
#定义函数
def greet(a1,a2='t3'):
    print("a1:"+a1+",a2:"+a2)
#位置实参
greet("t1","t2")
#关键字实参
greet(a2='t2',a1='t1')
#使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参
greet('t6')
#返回值
def he(a,b):
    return a+b
print(he(1,2))
#传递任意数量的实参,如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后
def test(*a):
    print(a)
test(1)
test(1,2)
test(1,2,3)

#传递任意数量的键值对
def test2(**user_info):
    for key,value in user_info.items():
        print(key,value)

test2(a="1")
test2(a="1",b="2")
test2(a="1",b="2",c='3')

python3基础5-用户输入和while循环

#coding:utf-8
#允许汉语注释
#输入和while循环
message = input("tell me sth:")
print(message)
#字符串转换成int
height = int(message)
print(height)
while height!=5:
    t=input("guess: ")
    print(t)
    height = int(t)
print("ok")

python3基础4-字典

#coding:utf-8
#允许汉语注释
#添加字典元素
a= {'color': 'green', 'points': 5}
print(a)
a['x']=1
a['y']=2
a['z']=1
print(a)
#删除键—值对
del a['points']
print(a)
#遍历所有的键—值对
for key,value in a.items():
    print(key,value)

for key1,value1 in a.items():
    print(key1,value1)

for key3 in a.keys():
    print(key3)

for v3 in a.values():
    print(str(v3))
print("\n\n")

#删除重复值
print('del multi\n')
for v3 in set(a.values()):
    print(v3)

python3基础3-if操作

#coding:utf-8
#允许汉语注释
#if
test = ['mushrooms', 'mushrooms', 'pineapple']
if test[0]==test[1]:
    print("ok")
else:
    print("no ok")

#检查某个元素是否在list里面
t = 'pineapple' in test
if t==True:
    print("true")

if 'pineapple1' not in test:
    print("true")

#检查list是否为空
if test:
    print("no empty")
else:
    print("empty")

age = 18
if age < 4:#在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格

    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")


python3基础2-列表操作

列表操作

#coding:utf-8
#允许汉语注释
#for
pt=["haha1","hshs3","dertery"]
for item in pt:
    print(item)
    print(item+"ok")
print("for end")

for value in range(1,6):
    print(value)
#使用range()创建数字列表
numbers=list(range(1,6))
print(numbers)
#使用函数range() 时,还可指定步长。例如,下面的代码打印1~10内的偶数
even_numbers = list(range(2,11,2))
print(even_numbers)

#平方数列表
squares = []
for value in range(1,11):
    square = value**2
    squares.append(square)
print(squares)

#平方数列表简化
squares = []
for value in range(1,11):
    squares.append(value**2)
print(squares)

#平方数列表超级简化,挺奇怪的语法
squares = [value**2 for value in range(1,11)]
print(squares)

print(min(squares))
print(max(squares))
print(sum(squares))

#切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) #第一个元素和最后一个元素的索引,与函数range() 一样,Python在到达你指定的第二个索引前面的元素后停止
#如果你没有指定第一个索引,Python将自动从列表开头开始
print(players[:4])
#要让切片终止于列表末尾,也可使用类似的语法
print(players[2:])
#打印最后三名队员的名字
print(players[-3:])

#列表拷贝
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] #new空间
#friend_foods = my_foods #仅仅拷贝了索引
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

#不可变的列表被称为元组
dimensions = (200, 50)#元组看起来犹如列表,但使用圆括号而不是方括号来标识
print(dimensions[0])
print(dimensions[1])
#请访问https://python.org/dev/peps/pep-0008/ ,阅读PEP 8格式设置指南

python3基础1

这系列博文是博主学习’python编程:从入门到实践’这本书的学习笔记

1.python3 ide推荐geany

py注释用’#’

import this显示py编程原则

2.字符串

用title()使得字符串可以首字母大写,upper()全大写,lower()全小写;字符串连接用+;字符串删除空白用strip,删除左空白lstrip,删除右空白rstrip;数字转字符串str(int)

3.列表基础

Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1 ,可让Python返回最后一个列表元素,这种约定也适用于其他负数索引,例如,索引-2 返回倒数第二个列表元素,索引-3 返回倒数第三个列表元素,以此类推。

#coding:utf-8
#允许汉语注释
#define list
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
#append item
bicycles.append("t1")
print(bicycles)
#insert item
bicycles.insert(2,"t2")
print(bicycles)
#del item, you could not find this item anymore
del bicycles[-1]
print(bicycles)
del bicycles[2]
print(bicycles)
#pop item , you can use this item later
pt=["a","b","c","d"]
a=pt.pop() #index_default=-1
print(pt)
print(a)
#remove by value,just remove the first one
pt.remove("b")
print(pt)

#sort by char永久性排序
pt=["a1","cc","bb","ff"]
pt.sort()
print(pt)
#按与字母顺序相反的顺序排列列表元素
pt.sort(reverse=True)
print(pt)
#使用函数sorted() 对列表进行临时排序
pt=["a","c","b"]
print(sorted(pt))
print(sorted(pt,reverse=True))
print(pt)
#方法reverse() 永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可
pt=["a","c","b","hah"]
pt.reverse()
print(pt)
pt.reverse()
print(pt)
#确定列表的长度
print(len(pt))