python需注意点

注意一:python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {}。缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数
例如:

if True:
    print ("True")
else:
    print ("False")

错误示范:

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

注意二:print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=“”

x='a'  #"a"也行
y="b"
print(x)
print(y)
print("-------------")
print(x,end="")#end=""中间可空可不空都可以
print(y,end=" ")
print()

运行结果:

a
b
-------------
ab 

注意三:import 与 from…import
在 python 用 import 或者 from…import 来导入相应的模块

导入 格式
将整个模块(somemodule)导入 import somemodule
从某个模块中导入某个函数 from somemodule import somefunction
从某个模块中导入多个函数 from somemodule import firstfunc, secondfunc, thirdfunc
将某个模块中的全部函数导入 from somemodule import *

注意四:python的赋值

a=1
b=2
c=3
print(a,b,c)

print("------------")

a=b=c=4
print(a,b,c)

print("------------")

a,b,c=5,6,"hello"
print(a,b,c)

运行结果:

1 2 3
------------
4 4 4
------------
5 6 hello

注意五:数值的计算

>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余
2
>>> 2 ** 5 # 乘方
32

注意六:多行语句

  1. 使用反斜杠 \ 来实现多行语句。
total = item_one + \
        item_two + \
        item_three
  1. 在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 \。
total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

注意七:bool类型

a=True
b=False
# 比较运算符
print(2<3)
print(2==3)
print("-----------------------------")
# 逻辑运算符
print(a and b)
print(a or b)
print(not a)
print("-----------------------------")
# 类型转换
print(int(a))
print(float(b))
print(str(a))

运行结果:

True
False
-----------------------------
False
True
False
-----------------------------
1
0.0
True

猜你喜欢

转载自blog.csdn.net/qq_45499204/article/details/131343077
今日推荐