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

Python入门简单概念讲解及其小案例

程序员文章站 2022-03-03 10:19:41
...

列表

# 列表取出数据首字母大写(title函数)
# bicycles = ['trek','cannondale','redline','specialized']
# print(bicycles[0].title())

# 列表尾部添加元素(append函数)
# bicycles = ['trek','cannondale','redline','specialized']
# bicycles.append('suzuki')
# print(bicycles)

#列表任意位置添加元素(insert函数)
# bicycles = ['trek','cannondale','redline','specialized']
# bicycles.insert(0,'mazida')
# print(bicycles)

# 删除列表中任意位置元素(del函数,前提是知道索引)
# bicycles = ['trek','cannondale','redline','specialized']
# del bicycles[0]
# print(bicycles)

# pop方式删除列表数据(删除最后一位,类似于栈弹出操作,后进先出,根据传递的下标可以弹出指定位置数据,如果删除并不再使用,用del,删除后还需要的话,用pop)
# motorcycles = ['honda','yamaha','suzuki']
# print(motorcycles)
# poped_motorcycle = motorcycles.pop(0)
# print(motorcycles)
# print(poped_motorcycle)

# 根据值来删除元素(只能删除一次,只删除该值第一次出现的时候,若删除列表中所有的指定值,需要循环来实现)
# motorcycles = ['honda','yamaha','suzuki','honda']
# print(motorcycles)
# motorcycles.remove('honda')
# print(motorcycles)

#sort方法使用后列表修改且不可恢复(反向传递传递reverse=true)
# cars = ['bmw','audi','toyata','subura']
# cars.sort()
# print(cars)
# cars.sort(reverse=True)
# print(cars)

# sorted保留列表元素原来的顺序,同时以特定的方式呈现他们。
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# print('after sorted\n')
# print(sorted(cars))
# print(cars)

# reverse反转列表中的排列顺序,reverse不按字母顺序反转,而是按照列表的顺序反转
#len()确定列表长度
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# cars.reverse()
# print(cars)
# print(len(cars))

#操作列表,缩进展示代码之间的逻辑关系
#for循环遍历列表
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# for car in cars:
#     print(car)
#     print(car.title()+",is so amazing")

# 避免缩进错误
# 1.不要忘记缩进
# 2.忘记缩进额外代码行
# 3.不必要的缩进
# 4.循环后不必要的缩进
# 5.不要遗漏循环后的冒号

# 创建数值列表
# 1.range()函数
# for value in range(1,5):
#     print(value)

# 2.利用range创建数字列表
# numbers = list(range(1,6))
# print(numbers)
# 按照指定步长添加,(2,11,3)表明从2开始,范围是2-11,步长为3
# even_numbers = list(range(2,11,3))
# print(even_numbers)

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

# 4.对数字列表执行简单的统计计算
# min取最小
# max取最大值
# sum对列表数字求和
# digits = [1,2,3,4,5,6,7,8,9,0]
# print(min(digits))
# print(max(digits))
# print(sum(digits))

# 列表解析
# squares = [value**2 for value in range(1,11)]
# print(squares)

# 切片(创建切片需要指定第一个元素和最后一个元素的索引)
# players = ['michael','harden','james','green','durant','duke']
# # print(players[0:3])
# # print(players[1:3])
# # # 倒数后三个元素输出
# # print(players[-3:])
# # 前三个元素输出
# print(players[:3])

# 复制列表
# my_foods = ['pizza','fateal','cake']
# friend_foods = my_foods[:]
# print("My favorite foods are:")
# print(my_foods)
# print("My friens' favorite foods are:")
# print(friend_foods)
#赋值(同一个列表)
# newfriend_foods = my_foods
# newfriend_foods.append('ice cream')
# print(my_foods)

元组(不可变的列表)

# 元组看起来犹如列表,但使用圆括号而不是方括号来标识
#遍历元组
# dimensions = (200,50,300,100)
# print(dimensions[0])
# print(dimensions[1])
# for dimension in dimensions:
#     print(dimension)

#修改元组变量:重新定义元组
# dimensions = (200,50,300,100)
# for dimension in dimensions:
#     print(dimension)
# dimensions = (400,100)
# for dimension in dimensions:
#     print(dimension)

# python编码格式
# 1.缩进:建议每行四个空格
# 2.行长:建议不超过80个字符
# 3.空行:将程序的不同部分分开,区分功能

if语句遍历列表

# cars =['audi','bmw','subaru','toyota']
# for car in cars:
#     if car == 'bmw':
#         print(car.upper())
#     else:
#         print(car.title())

# = 赋值语句
# == 检查是否相等,检查是否相等时区分大小写
#若只是判断值是否相等,可以先进行小写转换操作lower()方法,再进行值的比较
# car = "Audi"
# if car == 'audi':
#     print('true')
# else:
#     print('false')

# != 检查是否不相等,检查两个值不相等的代码效率可能更高
# request_mapping = 'mushroom'
# if request_mapping != 'mushroo':
#     print('true')
# else:
#     print('false')

#数字之间的比较
# num = 10
# if num !=20:
#     print('error')
# else:
#     print('success')

# 检查多个条件
# 1.使用and检查多个条件 该检查项中每个表达式均为true,整个表达式才为true,若有一个不为真,则为false
# age_0 =22
# age_1 =18
# if age_0 >= 21 and age_1>=21:
#     print(True)
# else:
#     print(False)

# 2.使用or检查,该项中一个为真,则整个表达式为true,若有一个不为真,则为True
# age_0 =22
# age_1 =18
# if age_0 >= 21 or age_1>=21:
#     print(True)
# else:
#     print(False)

# 3.检查特定值是否包含在列表中,可以使用关键字in,另一种可以使用遍历搜索比较值
# cars =['audi','bmw','subaru','toyota']
# str = 'bmw'
# str1 = 'mesdi'
# if str in cars:
#     print(True)
# else:
#     print(False)
# if str1 not in cars:
#     print(True)

# 4. if 最简单的if语句
# if something:
#     dosomething
#
# 5.if-else语句
# 条件测试通过执行一个,未通过执行另一个操作
# if something:
#     dosomething
# else:
#     doanotherthing


# 6.if-else-else结构 判断超过两个的情形,多个elseif情形
# age = 88
# if age < 4:
#     print('mianfei')
# elif age <18:
#     print('banjia')
# elif age > 65:
#     print('mianfei')
# else:
#     print('quanjia')

# 7.省略不必要的else,防止无效的恶意攻击
# age = 88
# if age < 4:
#     print('mianfei')
# elif age <18:
#     print('banjia')
# elif age > 65:
#     print('mianfei')

# 8.如果只想执行一个代码块,使用if-elif-else结构,运行多个建议使用一些列独立的if语句
# players = ['michael','harden','james','green','durant','duke']
# str1 ='harden'
# str2='james'
# str3= 'green'
# if str1 in players:
#     print('sueccess1')
# elif str2 in players:
#     print('sueccess2')
# elif str3 in players:
#     print('sueccess3')

# 9.if语句判断列表是否为空
# cars = []
# if cars:
#     for car in cars:
#         print(car)
# else:
#     print('cars is null')

# 10.判断多个列表元素是否重叠
# available_cars = ['bmw','audi','subaru','toyota']
# need_cars = ['audi','skoda']
# for need_car in need_cars:
#     if need_car in available_cars:
#         print('the car is in:'+need_car.title())
#     else:
#         print('you need buy the car:'+need_car.title())
# print('go back')

字典

# 字典形式类似于json格式,key-value存储。与键相关的值可以是数字、字符串、列表乃至字典(可以将任何python对象作为字典中的值)
#访问字典中的值的方式:字典名['键名']
# 添加键值对,字典名['键']=值
# 修改字典中的值:字典名['键']=新值
# bmw ={'color':'red','price':'500000','seat':'5'}
# print(bmw['price'])
# bmw['width']=2
# bmw['height']=2
# bmw['color']='green'
# print(bmw)

#删除键值对(删除将永远消失,如果需要访问则需要重新添加)
# bmw ={'color':'red','price':'500000','seat':'5'}
# del bmw['seat']
# print(bmw)

# 字典较长或列表过长,可以采取按行存属性
# language = {
#     'best_language':'python',
#     'popular_language':'java',
#     'power_lanuage':'c',
#     'outstanding_lanuage': 'javascript'
# }
# print('best language is:'+language['best_language'].title())

# 遍历字典(python不关心键值对的存储顺序,只关注键和值之间的关联关系)
# 遍历时key、value关键字可以自定义,项的数量要一致
# language = {
#     'best_language':'python',
#     'popular_language':'java',
#     'power_lanuage':'c',
#     'outstanding_lanuage': 'javascript',
#     'favorite_language':'python'
# }
# for key,value in language.items():
#     print('Key:'+key)
#     print('Value:'+value)
# 遍历所有的项与值
# for name,yuyan in language.items():
#     print('Name:'+name)
#     print('Value:'+yuyan)
# 遍历所有的键
# for name in language.keys():
#     print(name.title())
# 遍历所有的值
# for lan in language.values():
#     print(lan.title())
# 集合set,集合类似于列表,但每个元素都是独一无二的
# for lan in set(language.values()):
#     print(lan.title())

# 字典列表
# car_0 ={'color':'green','name':'bmw'}
# car_1 ={'color':'yellow','name':'scoda'}
# car_3 ={'color':'red','name':'wma'}
# cars =[car_0,car_1,car_3]
# for car in cars:
#     print(car)
# 在字典中存储列表
# 遍历列表中的列表
# develop_languages ={
#     'know':['python','ruby'],
#     'skilled':['python','java','javaScript'],
#     'professional':['javaScript','java'],
#     'unknow':['ruby']
# }
# for name,language in develop_languages.items():
#     print('\n'+name.title()+' favorite language is:')
#     for lan in language:
#         print('\t'+' language is:' + lan.title())

# 字典中嵌套字典
users={
    'marin':{
        'name':'cheng',
        'age':'18',
        'sex':'male'
    },
    'tonny':{
        'name':'tonny',
        'age':'28',
        'sex':'male'
    },
    'jack':{
        'name':'jack',
        'age':'38',
        'sex':'female'
    }
}
for username,userinfo in users.items():
    print('Username:'+username)
    print(userinfo['name']+" 's age is:"+userinfo['age']+" and sex is:"+userinfo['sex'])
相关标签: Python 语言