python基础 任务3

1. dict字典

a. 定义

      字典由多个键与其对应的值构成的键-值对组成(键值对也称为项)。每个键和值之间用‘:’隔开,项之间用‘,’隔开,整个字典由{ }括起来。

b. 创建

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d)

c. 字典的方法

#判断是否在字典中
print('Bob' in d)

#取键对应的值
print(d.get('Bob'))

#删除键及其对应的值
d.pop('Bob')
print(d)

           

2. 集合

a. 特性

       setdict类似,也是一组key的集合,但不存储value

       由于key不能重复,所以,在set中,没有重复的key。

b. 创建

s=set([1,2,3])  #创建set
print(s)

c. 方法

s.add(4)#增
print(s)

s.remove(4) #删
print(s)

s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print( s1 & s2)  #交集
print(s1 | s2) #并集

3. 判断语句(要求掌握多条件判断)

name= input("What's your name?")
if name=='Bob':
   print ('Hello,Bob!')
else:
   print('Hello,stranger!')

#多条件判断
num=int(input('Enter a number:'))  #注意字符串转换为整型
if num>0:
   print('The number is positive')
elif num<0:
   print('The number is negative')
else:
   print('The number is zero')

4. 三目表达式

#三目表达式
#条件为真时的结果 if 判断的条件 else 条件为假时的结果
x=int(input('Enter first num: '))
y=int(input('Enter second num(不能和第一个数相等): '))
print('较大的数为:',x if(x>y) else y)

#一般的写法
x=int(input('Enter first num: '))
y=int(input('Enter second num: '))
if x>y:
    print("较大的数为:",x)
elif x<y:
    print('较大的数为:',y)
else:
    print('两数相等')

5. 循环语句

a. while

#while 
n=0
while n<10:
    n=n+1
    print(n)

b. for循环

#for循环
names=['Michael','Bob','Tracy']
for name in names:
    print(name)

sum=0
for x in [1,2,3,3]:
    sum=sum+x
print(sum)

c. 跳出循环

#break  提前结束循环
n=1
while n<=100:
    if n>10:  #当n=11时,执行break语句
        break
    print(n)
    n=n+1
print('End')

#continue 跳出当前循环,直接开始下一次循环
n=0
while n<10:
    n=n+1
    if n%2==0:  #如果n是偶数,执行continue语句
        continue  #continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)

参考资料:

[1] https://skyelan.github.io/2019/04/04/Python_Base/PythonBase3/                                [2]https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431676242561226b32a9ec624505bb8f723d0027b3e7000

[3]《Python基础教程》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值