代码部分已经有很详细的注释了,基本上零基础的多可以看懂,所以这里就不多说了,直接上代码了。有错误或者不足的地方,欢迎下方留言。
认识字典:
# -*- coding: utf-8 -*-
#python字典定义,字典就是存放一些属性的,前面一个属于键,后面一个属于值,中间需要用:隔开,每个属性间用,隔开
alien = {'color': 'green', 'age': 18}
#取出字典里边的数据
print(alien['color'])
#添加键值对
alien['x_pos'] = 0
alien['y_pos'] = 10
print(alien)
#修改字典中的值
alien['color'] = 'red'
print(alien)
#del删除键值对
del alien['color']
print(alien)
#字典遍历, key和value属于变量可以随便写
user = {
'username': 'admin',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user.items():
print("\nkey:"+key)
print("value:"+value)
#遍历字典中的所有的键
for name in user.keys():
print(name.title())
#字典的一个小案例
print("字典和if的一个小案例")
friends = ['first', 'last']
for name in user.keys():
print(name.title())
if name in friends:
print(' key: '+name.title()+" : "+user[name].title())
#sorted()按键值排序
print()
for name in sorted(user.keys()):
print(name)
#遍历字典中所有的值
favorite = {
'jen': 'python',
'sarah': 'c',
'edward': 'python',
}
print()
for language in favorite.values():
print(language.title());
#set()去除重复的元素
print("set()去除重复的元素")
for language in set(favorite.values()):
print(language.title());
运行结果:
字典的基本应用:
# -*- coding: utf-8 -*-
#嵌套列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
#简单的小案例
#创建一个空列表
print("小案例")
aliens = []
#创建30条数据
for alien_number in range(0, 30):
new_alien = {'color': 'green', 'points': 5}
aliens.append(new_alien)
for alien in aliens[0: 3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0: 5]:
print(alien)
#在字典中存储列表
print("在字典中存储列表")
favorite = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'hashell'],
}
#遍历输出
for name, languages in favorite.items():
print(name.title()+"'s favorite languages are:")
for language in languages:
print('\t'+language.title())
#在字典中存储字典
print("在字典中存储字典")
users = {
'aeinstenin': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie':{
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("Username: "+username)
full_name = user_info['first']+" "+user_info['last']
location = user_info['location']
print("\tFull name: "+full_name.title())
print("\tLocation: "+location.title())
input()用户键盘输入函数的基本用法:
# -*- coding: utf-8 -*-
#input()用户键盘输入,input里边是提示语
message = input("请输入:")
print(message)
#int()将字符串数字转为int类型
age = input("请输入年龄:")
if int(age) > 18:
print("成年")
else:
print("未成年")
#%取余运算符,余数
number = input("请输入一个数字:")
if int(number) % 2 == 0:
print(str(number) + "是偶数")
else:
print(str(number)+"是奇数")
运行结果:
while循环的基本用法:
# -*- coding: utf-8 -*-
#while循环,满足while后的条件则执行while里边的代码块
number = 1
while number <= 5:
print(number)
number += 1
#break退出循环
while True:
city = input("请输入地区:")
if city == 'quit':
break;
else:
print(city.title())
#continue结束本次循环
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number)
#while循环删除列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while('cat') in pets:
pets.remove('cat')
print(pets)
#while循环结合字典使用,实现添加字典
responses = {}
while True:
name = input("输入字典名称:")
response = input("输入字典内容:")
responses[name] = response
repeat = input("是否继续输入(yes/no):")
if repeat == 'no':
break
for nema, response in responses.items():
print("字典名称:"+name+", 字典内容:"+response)
运行结果:
函数的定义与使用(很重要):
函数就相当于Java里边的方法,就是把一些代码写在一个函数中,可以通过函数命名重复的去调用,下面来看一些代码吧。
# -*- coding: utf-8 -*-
#函数的定义, def函数名()定义函数,函数可以重复调用
def greet_user():
"""注释"""
print("hello")
greet_user()
#有参数的函数,调用时需要给参数
def greet_user(username):
print("hello, "+username.title())
greet_user("张三")
greet_user("李四")
#关键字实参
def pet(name, age):
print("name:"+name+", type:"+str(age))
#关键字实参,参数顺序可以打乱
#下面两个是等效的
pet(name="张三", age=19)
pet(age = 18, name="李四")
#给函数设置默认值
def describe(name, age=18):
print("name:"+name+", type:"+str(age))
describe(name="张三")
describe("李四")
describe("王五", 16)
describe(name="王五", age=16)
#return返回值, 带返回值函数
def getName(name):
return name
name = getName("张三")
print(name)
#小案例
def get_formatted(first_name, last_name, middle_name=''):
if middle_name:
return first_name+" "+middle_name+" "+last_name
else:
return first_name+" "+last_name
musician = get_formatted('jimi', 'hendrix')
print(musician)
musician = get_formatted('john', 'hooker', 'lee')
print(musician)
运行效果:
函数的使用:
# -*- coding: utf-8 -*-
#函数返回字典
def build_person(first_name, last_name):
person={'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
#结合使用函数和while循环
def get_formatted_name(first_name, last_name):
full_name = first_name+" "+last_name
return full_name.title()
while True:
f_name = input("First name(输入q退出):")
if f_name == 'q':
break;
l_name = input("Last name(输入q退出):")
if l_name == 'q':
break;
name = get_formatted_name(f_name, l_name)
print(name)
#向函数中传递列表
def greet_users(names):
for name in names:
msg = "Hello, "+name.title()+"!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
#传递任意数量的实参,*toppings,*号表示需要传递一个toppings的元组
print("传递任意数量的实参")
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green')
运行结果:
# -*- coding: utf-8 -*-
#结合位置实参和任意数量实参
def make_pizza(size, *toppings):
print("大小:"+str(size))
for topping in toppings:
print(" - "+topping)
make_pizza(10, 'pepperoni')
make_pizza(20, 'mushrooms', 'green')
#使用任意数量的关键字实参,**user_info,**号表示需要传递一个user_info的列表
def build_profile(first, last, **user_info):
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile=build_profile('albert', 'einstein', loaction='princeton', field='physics')
print(user_profile)
运行结果:
导入整个模块:
导入模块,导入之后导入文件中的所有函数都可以被调用,就比如引用一个文件里边的东西一样,首先需要新建一个导入的python文件,里边可以放一些函数,如(里边放了一个make_pizza函数):
# -*- coding: utf-8 -*-
#结合位置实参和任意数量实参
def make_pizza(size, *toppings):
print("大小:"+str(size))
for topping in toppings:
print(" - "+topping)
可以在另一个文件中导入这个python文件,之后就可以调用这个python文件里边的函数了(两个文件必须放在同一个目录中)
# -*- coding: utf-8 -*-
#导入整个模块,hsDemo03导入文件名
import hsDemo03
hsDemo03.make_pizza(12, 'pepperoni')
运行结果:
导入特定的函数:
导入特定函数,只能用导入的那几个函数,如下运行结果和上面的一样
#导入特定的函数,后面可以跟多个函数名用,号隔开
#from 文件名 import 函数名1,函数名2
#form 文件名 import * 表示导入模块中的所有函数
from hsDemo03 import make_pizza
make_pizza(12, 'pepperoni')
as定义别名:
有时候导入模块或者特定函数文件名太长,使用起来不方便,可以在导入时取一个别名进行导入。
格式:模块名或函数名 as 别名
import hsDemo03 as hs
hs.make_pizza(12, 'pepperoni')
from hsDemo03 import make_pizza as m
m(12, 'pepperoni')