Python Base——Part 5

Python Base——Part 5

好久不见,今天继续和大家分享关于Python的一些基础知识

本次分享的主要内容包括两个部分:

第一部分:简单if语句;if-elif语句;if-else语句;if-elif-else语句

#在if语句中增加函数,使代码更加简洁
number = 17
if number < 8:
    price = number * 20
elif number <= 12:
    price = number * 18
else:
    price = number * 15
print(f"Your admission cost is ${price}.")

#使用多个elif代码块
if number < 4:
    price = number * 25
elif number < 10:
    price = number * 20
elif age < 16:
    price = number * 15
else:
    price = number * 12
print(f"Your admission cost is ${price}.")

#省略else代码块
if number < 4:
    price = number * 25
elif number < 10:
    price = number * 20
elif age < 16:
    price = number * 15
elif age >= 16:
    price = number * 10
print(f"Your admission cost is ${price}.")

#测试多个条件
add=['mushrooms','cheese','yoghurt']
if 'mushrooms' in add:
    print("Add mushrooms")
elif 'cheese' in add:
    print("Add cheese")
elif 'yoghurt' in add:
    print("Add yoghurt")
#此时输出结果仅有“Add mushrooms”,因为if代码块中的条件通过了就不会再执行下面的内容了
#而如果顾客既想加mushrooms,还想加cheese和yoghurt,那么这个代码不能满足条件
#if-elif-else结构功能强大,但只适合用于一个条件满足的情况:遇到通过了的测试后,Python就会跳过余下的测试
#而当要测试多个条件时,应该使用多个if语句来测试
add=['mushrooms','cheese','yoghurt']
a=[]
if 'mushrooms' in add:
    a.append('mushrooms')
if 'cheese' in add:
    a.append("cheese")
if 'yoghurt' in add:
    a.append("yoghurt")
print(f"Your pizza had added extra {a}.")

第二部分:如何用if语句处理列表;使用if语句检查特殊元素;使用if语句确定列表不是空的;if语句使用多个列表 

#用if语句处理列表
#检查特殊元素
addings=['lemon','carrot','green peppers','cheese','beef']
for adding in addings:
    if adding == "green peppers":
        print("Sorry, we are out of green peppers.")
    else:
        print(f"Add {adding}")

#确定列表不是空的
requests=[]
if requests:
    for request in requests:
        print(f"Adding {request}")
else:
    print("Are you sure you want a plain pizza?")

#使用多个列表
raws=['lemon','carrot','green peppers','cheese','beef']
requests=['chicken','cola','milk','fries','lemon','carrot','cheese','beef']
for request in requests:
    if request in raws:
        print(f"Add {request}")
    else:
        print(f"Sorry, {request} had been sold out.")

第三部分:字典简介;字典形式(键值对),创建字典

#注意:字典是用花括号将键值对括起来。键值对是两个相关联的值。键和值之间用冒号隔开;键值对之间用逗号隔开
alien_0={'color':'green','points':5}
print(alien_0['color'])
#在Python中,字典是一系列键值对。每个键都与一个值相对应
#与键相关联的可以是数、字符串、列表乃至字典
print(alien_0["points"])
new_score=alien_0["points"]
print(f"Congratulations! You earned {new_score} scores.")

#添加键值对
alien_0["x_position"]=8
alien_0["y_position"]=22
print(alien_0)
#要添加键值对,可依次指定字典名、用方括号括起来的键和相关联的值
#字典中元素的排列顺序与添加时的顺序相同

#先创建一个空字典,然后添加键值对
dic={}
dic["name"]="lisa"
dic["age"]=24
dic["sex"]="female"
print(dic)

今天的分享就这么多了。欢迎大家莅临我的另一个草稿箱(公众号:统计小菜椒)

(ps:不开心的话就学Python)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值