【Python基础】--丰富的else语句/简洁的with语句/字典dict{}/集合set{}

本文深入探讨了Python的基础语法,包括条件语句、循环结构、异常处理、文件操作等内容,并详细解析了字典和集合的操作方法及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

丰富的else语句

要么怎样,要么不怎样(if

干完了能怎样,干不完就别想怎样(forwhile循环)

def showMaxFactor(num):
    count = num // 2
    while count > 1:
        print('count = %d' % count)
        if num % count == 0:
            print('%d最大的约数是%d' %(num, count))
            break
        count -= 1
    else:
        print('%d是素数'% num)

num = int(input('请输入一个数:'))
showMaxFactor(num)


没有问题,那就干吧 (异常处理)

try:
    #print(int('abc'))
    print(int('123'))
except ValueError as reason:
    print('出错啦' + str(reason))
else:
    print('没有任何异常')

简洁的with语句

try:
    f = open('data.txt', 'w')
    for each_line in f:
        print(each_line)
except OSError as reason:
    print('出错啦' + str(reason))
finally:
    f.close()

try:
    with open('data.txt', 'w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错啦' + str(reason))

使用with后,自动调用close()

字典dict{}

>>> brand = ['lining', 'nike', 'adidas']
>>> slogan = ['Anything is possible', 'Just do it', 'Impossible is nothing']
>>> print('lining slogan is :', slogan[brand.index('lining')])
lining slogan is : Anything is possible
>>> dict1 = {'lining': 'Anything is possible', 'nike':'Just do it', 'adidas':'Impossible is nothing'}
>>> print('lining slogan is:', dict1['lining'])
lining slogan is: Anything is possible
>>> 

>>> dict1 = {}
>>> dict1.fromkeys((1, 2, 3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1, 2, 3), 'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys((1, 2, 3), 'one', 'two', 'three')
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    dict1.fromkeys((1, 2, 3), 'one', 'two', 'three')
TypeError: fromkeys expected at most 2 arguments, got 4
>>> dict1.fromkeys((1, 2, 3), ('one', 'two', 'three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> 
>>> dict2 = {}
>>> dict2 = dict2.fromkeys(range(5), '赞')
>>> dict2
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
>>> for eachkey in dict2.keys():
	print(eachkey)

	
0
1
2
3
4
>>> 
>>> for eachvalue in dict2.values():
	print(eachvalue)

	
赞
赞
赞
赞
赞
>>> for eachitem in dict2.items():
	print(eachitem)

	
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
>>> print(dict2[4])
赞
>>> print(dict2[5])
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    print(dict2[5])
KeyError: 5
>>> dict2.get(5)
>>> print(dict2.get(5))
None
>>> dict2.get(5, 'haha')
'haha'
>>> dict2.get(4, 'haha')
'赞'
>>> 4 in dict2
True
>>> 5 not in dict2
True
>>> 5 in dict2
False
>>> dict2.clear()
>>> dict2
{}


>>> 
>>> a = {'name':'wuyq'}
>>> b =a
>>> a
{'name': 'wuyq'}
>>> b
{'name': 'wuyq'}
>>> a = {}
>>> a
{}
>>> b
{'name': 'wuyq'}
>>> 
>>> 
>>> a = b
>>> a
{'name': 'wuyq'}
>>> b
{'name': 'wuyq'}
>>> a.clear()
>>> a
{}
>>> b
{}
>>> 


>>> a = {1:'one', 2:'two', 3:'three'}
>>> b = a.copy()
>>> c = a
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
58001288
>>> id(b)
55237704
>>> id(c)
58001288
>>> c[4] = 'four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> 
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem()
(1, 'one')
>>> a
{3: 'three', 4: 'four'}
>>> a.setdefault('xiaobai')
>>> a
{3: 'three', 4: 'four', 'xiaobai': None}
>>> a.setdefault(5, 'five')
'five'
>>> a
{3: 'three', 4: 'four', 'xiaobai': None, 5: 'five'}
>>> 字典没有顺序的概念
KeyboardInterrupt
>>> 
>>> a
{3: 'three', 4: 'four', 'xiaobai': None, 5: 'five'}
>>> b = {'xiaobai':'dog'}
>>> a.update(b)
>>> a
{3: 'three', 4: 'four', 'xiaobai': 'dog', 5: 'five'}
>>> 

集合set{}

数据唯一,不可以重复,不支持下表索引。元素是无序的

>>> num = {}
>>> type(num)
<class 'dict'>
>>> num2 = {1, 2, 3, 4, 5}
>>> type(num2)
<class 'set'>
>>> num2 = {1, 2, 3, 4, 5, 4, 3, 2,1}
>>> num2
{1, 2, 3, 4, 5}
>>> num2[2]
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    num2[2]
TypeError: 'set' object does not support indexing
>>> set1 = set([1, 2, 3, 4])
>>> set1
{1, 2, 3, 4}
>>> 

去掉列表中的重复元素

>>> num1 = [1, 2, 3, 4, 5,0, 5, 3, 1]
>>> num1
[1, 2, 3, 4, 5, 0, 5, 3, 1]
>>> tmp = []
>>> for each in num1:
	if each not in tmp:
		tmp.append(each)

		
>>> tmp
[1, 2, 3, 4, 5, 0]
>>> num1
[1, 2, 3, 4, 5, 0, 5, 3, 1]
>>> num1 = list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5]
>>> 
>>> 
>>> 1 in num2
True
>>> 
>>> '1' in num2
False
>>> 
>>> num2.add(6)
>>> num2
{1, 2, 3, 4, 5, 6}
>>> num2.remove(1)
>>> num2
{2, 3, 4, 5, 6}
>>> 
>>> num3 = frozenset([1, 2, 3])
>>> num3.add(5)
Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    num3.add(5)
AttributeError: 'frozenset' object has no attribute 'add'
>>> 














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值