python中变量使用注意事项有哪些_Python 注意事项

1、tuple:元组

a.元组一旦初始化就不可修改。不可修改意味着tuple更安全。如果可能,能用tuple代替list就尽量用tuple;

b.定义只有一个元素的tuple的正确姿势:t = (1,),括号内添加一个逗号,否则会存在歧义;

2、dict:字典

a.获取value值:dict['key'],若key不存在,编译器就会报错KeyError。如何避免.

一是通过 in 判断 key 值是否在dict中

'key' in dict #返回True 或 False

二是通过 dict 的函数get()

dict.get('key') #返回 value 值 或 None

3、生成随机数的几种方式

随机整数:random.randint(a,b):返回随机整数x,a<=x<=b

随机实数:random.random( ):返回0到1之间的浮点数

随机浮点数:random.uniform(a,b):返回指定范围内的浮点数。

随机整数:andom.randrange(start,stop,[,step]):返回一个范围在(start,stop,step)之间的随机整数。

start--指定范围内的开始值,包含在范围内。

stop--指定范围内的结束值,不包含在范围内。

step-- 指定递增基数。

4、全局变量和局部变量使用

#以下代码输出结果为 num:0;说明 get_number 函数未修改全局变量

num = 0 #定义全局变量

defget_number():

num= 100 #定义局部变量,局部变量 num 和全局变量 num 名称相同

returnnumdefprint_one():print('num:', num) #此处 num 表示的为全局变量

test=get_number()

print_one()

#输出结果为 num:100,说明 get_number 修改全局变量的值

num =0defget_number():global num #修改全局变量

num = 100

returnnumdefprint_one():print('num:', num)

test=get_number()

print_one()

输出结果:num:100

如果在函数中需要修改全局变量的值,我们在函数中修改之前需要使用  【global 全局变量名】告诉编译器要修改全局变量的值

5、函数返回值

deftest_tuple(a, b):

quotient= a//b

remainder= a%breturnquotient, remainder

t= test_tuple(9, 4)#quotient, remainder = test_tuple(9, 4)

print(t)

这种书写方式,返回的数据本质上是元组

6、形参用法

#a, b 位置参数#c 默认参数#*args 可变参数--tuple#**kwargs 关键字参数--字典

def test(a, b, c=33, *args, **kwargs):print(a)print(b)print(args)print(kwargs)

test(11, 22, 66, 99, 88, 77, name='Kevin', age=89)

拆包:

#定义数组a,字典b

a = [1, 2, 3]

b= {'age': 20, 'score': 90}#2种调用方式输出结果不同

test(1, 2, 3, a, b)

test(1, 2, 3, *a, **b) #等价于test(1, 2, 3, 1, 2, 3, age=20, score=90)

test(1, 2, 3, a, b)输出结果:1

2

3([1, 2, 3], {'age': 20, 'score': 90})

{}

test(1, 2, 3, *a, **b)输出结果:1

2

3(1, 2, 3)

{'age': 20, 'score': 90}

拆包:

tuple变量前添加*,把tuple拆为单个元素;

dict变量前添加**,把dict拆为key/value键值对;

7、引用

'''引用(牵涉到 = 的地方都是引用)'''

#id() 函数输出变量的内存地址

c = 100d= c #d、c指向同一个内存

print(id(c), c)

c= 20 #此处是重新赋值,c指向一块新的内存地址

print(id(c), c)print(id(d), d)#数组 e、f均发生了变化

e = [1, 2, 3]

f= e #f、e指向同一个内存

print(id(e), e)print(id(f), f)

e.append(20) #操作原有内存存储的值

print(id(e), e)print(id(f), f)

8、Python的数据类型

不可变类型:数字(int、float)、字符串(str)、元组(tuple)

可变类型:数组(list)、字典(dict)

9、匿名函数

#普通函数

deftest(x, y):

x+y#匿名函数

y = lambda x, y: x +yprint('test=', test(1, 2)) #返回结果 test= None

print('y=',y(1, 2)) #返回结果 y= 3

匿名函数:  lambda 参数: 表达式 ----> 匿名函数后面只能使用表达式,并且默认返回表达式的结果

匿名函数的应用:

#匿名函数的应用1#数组中放的是dict,list是不支持对这种数据结构进行排序的

pl = [{'name':'Kevin', 'age': 20}, {'name':'Ali', 'age': 10}, {'name':'Miss', 'age': 66}]#正确姿势 按照name排序。

pl.sort(key=lambda x:x['name'])print(pl)#匿名函数的应用2

deftest1(a, b, func):

result=func(a, b)returnresult

i= test1(1, 2, lambda x, y: x+y)print(i)#python3 使用 input 输入的内容默认为字符串,使用 eval() 等价于 保持输入的原内容

func_new = input('输入匿名函数:')

func_new=eval(func_new)deftest_input_func(a, b, func_new):

result=func_new(a, b)returnresult

re= test_input_func(11, 22, func_new)print(re)

10、以全局变量作形参

int_a = 12list_a= [12]#使用全局变量当做函数的形参

deftest_global_var(num):

num+=numprint(num)

test_global_var(int_a)

test_global_var(list_a)print(int_a) #12

print(list_a) #[12, 12]

结论:以全局变量作函数的形参,若全局变量为不可变对象则函数内不能修改全局变量的值;若全局变量是可变对象,则函数中操作全局变量可以修改全局变量。

11、字符串常用方法

#字符串常见的操作

test_str = 'hello world hello world'

#find 输出要搜索的字符串的下标索引。-1表示未找到目标字符串

print(test_str.find('zz'))#rfind 从右往左找

print(test_str.rfind('l'))#index 不存在字符会使程序crash;

print(test_str.index('w'))#rindex 从右往左找

print(test_str.rindex('d'))#count 统计某字符出现的次数

print(test_str.count('o'))#replace 替换所有字符串为指定字符串,返回替换后的值;但是,原字符串并未被修改

print(test_str.replace('world', 'WORLD', test_str.count('world'))) #第三个参数表示替换多少个

print(test_str.replace('world', 'ooo'), test_str.count('world'))#split 根据指定字符切割,指定的字符会被损耗掉,返回list;split()默认切除不可见字符(\n\t等)

print(test_str.split(' ')) #切除所有空格 ' '#capitalize 把字符串第一个字符大写

print(test_str.capitalize())#title 把字符串每个单次首字母大写

print(test_str.title())#startwith 检查字符串是否以指定字符开头,是True,否False;endwith检查字符串是否以指定字符结尾

print(test_str.startswith('h'))#lower、upper 把字符串修改为全部小写或全部大写

print(test_str.lower())print(test_str.endswith('l'))#ljust 返回一个字符串左对齐,并使用空格填充至长度width的新字符串;rjust同理

print(test_str.ljust(100))#center 返回一个原字符串居中,并使用空格填充至长度width的新字符串

print(test_str.center(100))#lstrip 删除字符串左边空白字符;rstrip 删除字符串右边空白字符;strip 删除字符串两端空白字符#partition 把字符串以str分割成三部分,str前,str,str后。 mystr.partition(str)

print(test_str.partition('world'))#splitlines() 按照行分割,返回一个包含各行元素的列表list

print('abc\ndef\nopi\nkjh'.splitlines())#isalpha 判断字符串内字符是否为纯字母

print(test_str.isalpha())#isdigit 判断字符串内字符是否为纯数字

print(test_str.isdigit())#isalnum 判断字符串内字符是否都是数字或字母,是则返回YES,否返回NO

print('12abc'.isalnum())#str的每个字符后面插入str,构造出一个新的字符串;或若list中元素都为字符串,则可以构造出一个新字符串

print('a'.join(test_str))

names= ['aaa', 'bbb', 'ccc']print('_'.join(names)) #aaa_bbb_ccc

#删除 \n \t 等,正确方法;或者使用正则表达式

test_string = 'opop\n \t\nopofwe \nfwfwj\tiodj1ojd1'

print(test_string.split())

后续……

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值