Python的一些操作

Python

1 Basic Concepts

  • floats

    • pythonforward slash“/”代表除法, 得到的是float 型的数值。
      e.g. 12/6 输出是 2.0 而并不是 2
    • 两个floats之间的运算得到是float,一个integer和一个float之间得到也是float
  • “//”代表取整 eg. 20//6 结果为3;

  • “%”代表**取余**eg. 1.25%0.5 结果为 0.25。

  • python 中,单引号‘’,和双引号“”在具有同样的作用,好处在于能够在string中更方便的打出单/双引号。而不需要用额外的转义字符。
>>>print(" nihao'ma' ")
nihao'ma'
  • built-in functions指的是那些不用额外导入module便可以使用的函数,如 len() upper() lower()

系统时间的输出

from datetime import datetime
now = datetime.now()

print now.year
print now.month
print now.day

Boolean运算符的顺序

not is evaluated first;
and is evaluated next;
or is evaluated last.

2 Control Structures

  • 条件语句 if…else…
    python 的条件语句很有意思。是通过缩进来确定层次关系。注意 ifelse 语句后面的冒号,else if 在 phthon 里面的表达方式是 elif

for example.

num = 12
if num > 5:
   print("Bigger than 5")
   if num <=47:
      print("Between 5 and 47")

Result:

>>>
Bigger than 5
Between 5 and 47
>>>

3 import module/导入模块/from module import funtion/导入指定函数

python中直接使用函数 sqrt 会失败, 会提示未找到此变量, 需要用以下代码

方法一:导入 math 模块,并使用其中函数.使用函数时,需要加上模块名作为前缀。

import math
result = math.sqrt(10)


方法二:从模块 math 仅导出 sqrt 函数,使用时就不用加上模块名作为前缀了。

# method 2
# 此种方法可以仅导入想要的函数
from math import sqrt
result = sqrt(10)


方法三:从模块 math* 导出所有函数,使用时也不用加前缀了

# method 3
# 此种方法可以导入指定模块的所有函数
from math import *
result = sqrt(10)

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/79186759