python前言

python学习

1.什么是BIF?

BIF 就是 Built-in Functions,内置函数

2.python中的变量名不能以数字开头

3.

1
2
3
4
a=1
b='1'
a=b
print(a)

会输出1,没有单引号,因为它用print打印

4. 除了使用反斜杠(\)进行字符转义,还有什么方法可以打印:Let’s go! 这个字符串?

1
2
3
print("Let's go!")  *# 双引号内单引号无需转义*

print('''Let's go!''') *# 三单引号* print("""Let's go!""") *# 三双引号*

5. 如果非要在原始字符串结尾输入反斜杠,可以如何灵活处理?

1
2
3
4
5
6
7
8
9
10
11
*# 在原始字符串外手动转义* 

path = r'C:\Users\Documents''\\' *# 注意两字符串间无空格*

print(path) *# 输出: C:\Users\Documents\

*# 将结尾反斜杠单独用普通字符串拼接*

path = r'C:\Users\Documents' + '\\'

print(path) # 输出: C:\Users\Documents\

6.如果输出格式复杂的空行多空格多的文本怎么办?

三重引号字符串‘’‘ xxx ‘’’

如果希望得到一个跨越多行的字符串,我们就可以使用三重引号字符串,这里的三重引号可以是三个单引号也可以是三个双引号。

>>> str = “””轻轻的我走了,

正如我轻轻的来;

我轻轻的招手,

作别西天的云彩。…

“””

7. Python3 中,一行可以书写多个语句吗?

可以,语句之间用分号隔开即可,不妨试试:

1
print('I love fishc');print('very much!')

8.我们人类思维是习惯于“四舍五入”法,你有什么办法使得 int() 按照“四舍五入”的方式取整吗?

5.4 “四舍五入”结果为:5,int(5.4+0.5) == 5
5.6 “四舍五入”结果为:6,int(5.6+0.5) == 6

9. 取得一个变量的类型,视频中介绍可以使用 type() 和 isinstance(),你更倾向于使用哪个?

建议使用 isinstance(),因为它的返回结果比较直接,另外 type() 其实并没有你想象的那么简单,我们后边会讲到。

🤔 为什么 isinstance()更胜一筹?
1. 继承链检查能力(核心优势)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal:
pass

class Dog(Animal):
pass

dog = Dog()

# type() 的局限性
print(type(dog) == Animal) # False - 只检查精确类型

# isinstance() 的智能检查
print(isinstance(dog, Animal)) # True - 识别继承关系
print(isinstance(dog, (Animal, Dog))) # True - 支持多类型检查
2. 多类型联合检查
1
2
3
4
5
def process_input(value):
if isinstance(value, (int, float, str)):
# 同时检查多种类型
return f"Processing: {value}"
raise TypeError("Invalid type")

10. Python 的 floor 除法现在使用 “//” 实现,那 3.0 // 2.0 您目测会显示什么内容呢?

Python 这里会义无反顾地执行 floor 除法原则,答案是:1.0

11.请用最快速度说出答案:not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9

答案是:4

not or and 的优先级是不同的:not > and > or

我们按照优先级给它们加上括号:(not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)
== 0 or 0 or 4 or 6 or 9
== 4

为什么是 4?提到的“短路逻辑”:3 and 4 == 4,而 3 or 4 == 3。
所以答案是:4

12. 假设有 x = 1,y = 2,z = 3,请问如何快速将三个变量的值互相交换?

x, y, z = z, y, x

13. 猜猜 (x < y and [x] or [y])[0] 实现什么样的功能

即:返回 xy中的较小值(类似 min(x, y)的基础版)


🔍 分步拆解

假设 x = 3, y = 5

    第一步:x < y判断

    1
    3 < 5 → True

    第二步:and [x]

    1
    True and [3] → [3]  # and操作返回最后一个真值

    第三步:or [y]

    1
    [3] or [5] → [3]  # or操作在左值为真时短路返回

    第四步:取列表首元素

    1
    [3][0] → 3

14.请将以下代码修改为三元操作符实现:

1
2
3
4
5
6
7
8
9
x, y, z = 6, 5, 4
if x < y:
small = x
if z < small:
small = z
elif y < z:
small = y
else:
small = z
1
small = x if (x < y and x < z) else (y if y < z else z)

15.断言(assert)

assert这个关键字我们称之为“断言”,当这个关键字后边的条件为假时,程序自动崩溃并抛出AssertionError的异常。当这个关键字后边的条件为真时,程序无影响。

举个例子:

assert 3 > 4

一般来说我们可以用Ta在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert关键字就非常有用了。

16. 下面的循环会打印多少次”I Love you”?

1
2
3
for i in range(0, 10, 2):
print('I Love you')

5 次,因为从 0 开始,到 10 结束,步进为 2。(0 2 4 6 8)