python系列-基础

基本数据类型

  • 整型
  • 浮点型
  • 字符串型
  • 布尔型
  • 复数型

python3整型只有int,支持二进制;字符串可以用'",如'hello'"hello";复数形如3+5j

类型检查

可以使用type函数对变量类型进行检查

a = 10
b = 12.3
c = 3 + 5j
d = "hello python"
e = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

类型转换

  • int(): 转换整型,可以指定进制
  • float():转换浮点型
  • str(): 转换字符串,可以指定编码
  • chr(): 将整数转换成该编码对应的字符串(一个字符)
  • ord(): 将字符串(一个字符)转换呈对应的编码(整数)

运算符

运算符 描述
[] [:] 下标,切片
** 指数
& | ^ ~ + - 按位与,按位或,按位异或,按位取反,正负号
* / % // 乘,除,模,整除
+ - 加,减
>> << 右移,左移
<= > < >= 小于等于,大于,小于,大于等于
== != 等于,不等于
is is not 身份运算符
in not int 身份运算符
not or and 逻辑运算符

分支结构

if elifelse 进行

海伦公式

a = float(input('a='))
b = float(input('b='))
c = float(input('c='))

if a + b > c and a + c > b and b + c > a:
    print("len: %f" %(a+b+c))
else:
    print("不能构成三角形")

循环结构

for-in循环

对容器进行迭代,优先使用for-in循环

sum = 0
for x int range(101) :
    sum += x
print(sum)

range函数使用方法:

  • range(101):0-100整数,取不到101
  • range(1,101):1-100整数,左闭右开
  • range(1,101,2):1-100的奇数,其中2是步长
  • range(100,0,-2):100-1的偶数,其中-2是步长

while循环

不知道具体循环次数,优先使用while循环,用一个bool值控制while循环。可以使用break提前跳出当前循环

import random

answer = random.randint(1,100)
counter = 0
while True:
    counter += 1
    number = int(input('请输入:'))
    if number < answer:
        print('大一点')
    elif number > answer:
        print('小一点')
    else:
        print('猜对了')

print('猜了%d次' %counter)
if counter > 7:
    print('智商余额明显不足')

函数和模块

函数

将一种特定的功能代码封装到一起,组成一个函数,只需要在用的时候调用这个函数就可以了。定义函数用def关键字,用return返回一个结果

def fac(num):
    result = 1
    for n in range(1, num+1):
        result *= n
    
    return result

n = int(input("n = "))
m = int(input("m = "))
print(fac(m) // fac(n) // fac(m-n))

python函数的特点:

  • 可以有默认值
  • 支持使用可变参数
  • 不支持函数重载
  • 在参数前面加*表示该参数是一个可变参数
def add(*args):
    total = 0
    for val in args:
        total += val
    return total

print(add())
print(add(1))
print(add(1,2,3))

模块

python每个文件名就代表了一个模块,在不同的模块可以有相同名称的函数,使用import关键字可以导入模块
module1.py

def foo():
    print("hello module 1")

module2.py

def foo():
    print("hello module 2")

test.py

import module1 as m1
import module2 as m2

m1.foo()
m2.foo()

参考文献

python一百天

你可能感兴趣的:(python系列-基础)