300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python入门日记 task 01:变量 运算符 数据类型及位运算

python入门日记 task 01:变量 运算符 数据类型及位运算

时间:2021-09-02 22:27:04

相关推荐

python入门日记  task 01:变量 运算符 数据类型及位运算

一、学习目标:

理论部分

了解python中基本的变量类型,运算符,及数据类型。了解python的位运算

练习部分

3. 课后思考题

4. leetcode练习题

二、知识大纲

三、新知识点记录:

1.位运算符(难点)

(把数字当作二进制数进行运算)

注:了解二进制转换原理,了解相关应用场景。学习时参考阅读

位运算1

位运算2

应用:

1、与运算通常应用的场景是获取某一位的值为1还是0(如判断奇数偶数,统计数值中1的个数);

2、左移右移特性:左移一位相当于乘以2,右移一位相当于除以2;

3、异或特性:任意数和自身异或结果为0;0和任意数异或结果还是其本身。

位运算运用

2.三元运算符

x, y = 4, 5small = x if x < y else yprint(small) # 4

3.其他运算符

letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']if 'A' in letters:print('A' + ' exists')if 'h' not in letters:print('h' + ' not exists')# A exists# h not exists

a = "hello"b = "hello"print(a is b, a == b)# True True

a = ["hello"]b = ["hello"]print(a is b, a == b)# False True

注意:

is, is not 对比的是两个变量的内存地址==, != 对比的是两个变量的

即:

1.假如比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。

2.假如对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。

4.运算符优先级

一元运算符优于二元运算符。如正负号。先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 (1 << (3 + 2)) & 7逻辑运算最后结合

表格来源:

/pc_286/article/details/50111499

5.数字类型进制转换

表格来源:/weixin_43353539/article/details/89444838

6.print函数参数

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str() 方式进行转换为字符串输出;关键字参数sep 是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;关键字参数end 是输出结束时的字符,默认是换行符\n ;关键字参数file 是定义流输出的文件,可以是标准的系统输出sys.stdout ,也可以重定义为别的文件;关键字参数flush 是立即把内容输出到流文件,不作缓存。

【例子】没有参数时,每次输出后都会换行。

shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed without 'end'and 'sep'.")for item in shoplist:print(item)# This is printed without 'end'and 'sep'.# apple# mango# carrot# banana

【例子】每次输出结束都用end 设置的参数& 结尾,并没有默认换行。

shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed with 'end='&''.")for item in shoplist:print(item, end='&')print('hello world')# This is printed with 'end='&''.# apple&mango&carrot&banana&hello world

【例子】item 值与’another string’ 两个值之间用sep 设置的参数& 分割。由于end 参数没有设置,因此默认是输出解释后换行,即end 参数的默认值为\n 。

shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed with 'sep='&''.")for item in shoplist:print(item, 'another string', sep='&')# This is printed with 'sep='&''.# apple&another string# mango&another string# carrot&another string# banana&another string

练习题:

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。尝试使用位运算解决此题。

list_ = [1,1,2,2,3,3,4,5,5]res = 0for i in list_ :res = res ^ iprint(res)

class Solution:def singleNumber(self, nums: List[int]) -> int:# your code hereone=0for num in nums:one=one^numreturn one

本文仅是阅读后的记录、搜集、整理,仅供参考。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。