2.python基础学习-关键字、变量、精度计算、基本数据类型转换、运算符(**,==,is,//,and ,or ,not,in, not in)

修订日期 内容
2021-2-5 初稿
2021-2-7 更新元组tuple,集合set,字典dict相关操作
2021-2-9 1.更新字符串str的相关操作,2.更新变量中全局变量的定义

关键字

关键字也有那些呢,可以使用代码输出python中的关键字

import keyword

print(keyword.kwlist)

[‘False’, ‘None’, ‘True’, ‘peg_parser’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

变量、全局变量

在函数内部使用global 可以变成全局变量

#定义变量
address = '中华人民共和国'
print('地址:', id(address))
print('类型:', type(address))
print('值:', address)

'''
地址: 1636857361488
类型: <class 'str'>
值: 中华人民共和国
'''

def fun6():
    global age
    age = 18

# print(age) 报错
fun6()
print(age)  # 18

基本数据类型

Numbers(数字)

  • int(有符号整型)
var i = 500 #int类型
var f = 23.1 # float 类型
var c = 3e+26J #复数
print(i, f, c) # 500 23.1 3e+26j
  • float(浮点型)

float类型计算时可能会出现小数位不确定的情况,推荐使用decimal

print(1.1+2.2) #-> 3.3000000000000003

# 推荐 引入decimal
from decimal import Decimal
print(Decimal(str(1.1))+Decimal(str(2.2))) #-> 3.3

String(字符串)

详见:7-python基础学习-数据结构-str字符串的常用操作

bool (布尔)

True ->1,False->0

t = True
f = False
print(t, type(t))
print(f, type(f))
print(t+1)
print(f+1)
'''
True <class 'bool'>
False <class 'bool'>
2
1
'''

List(列表)

详见:list列表常用操作

Tuple(元组)

相当与只读的list
详见:6-python基础学习-数据结构-元组tuple&集合set的常用操作

Set(集合)

详见:6-python基础学习-数据结构-元组tuple&集合set的常用操作

Dictionary(字典)

详见:5-python基础学习-数据结构-dict字典的常用操作

数据类型转换str(),int(),float()

在这里插入图片描述

# 数据类型转换 int 与 str 相互转换
var = str(1)
print(var, type) # 1 <class 'type'>

var2 = int('3')
print(var2, type(var2)) # print(var2, type(var2))
print('我今年' + var2 + '岁')  # 运行会类型转换错误
print('我今年' + str(var2) + '岁')  # 我今年3岁

print(int(3.1514))  # 会舍弃小数位,保留整数 3
print(float('3.1415926'))  # 3.1415926

运算符(**,==,is,//,and ,or ,not)

python中有一些java没有的特殊运算符

**: 幂运算

//:相除取整运算

注意如果有一正一负相除则会向下取整

print(2**3, 9//4)  # 8 2
print(-9//4)  # -3
print(9//-4)  # -3

== : 比较的是值,类似与java中的 equals()
is :比较的是地址值,类似与java中对象比较 ==
is not :与is相反

list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)  # True
print(list1 is list2)  # False
print(list1 is not list2)  # True

and,or ,not

and ->对应java中的&&
or -> 对应java中的||
not -> 对应java中取反 !

#  and,or, not
a = 1
b = 2
print(a == 1 and b == 2)  # True
print(a == 1 or b == 1)  # True
print(not a == 2)  # True

in ,not in

in ,not in 类似与java中String的contains

# in ,not in

v = 'Hello World'
print('H' in v, 'llo' in v, 'K' in v)  # True True False
print('H' not in v, 'llo' not in v, 'K' not in v)  # False False True

Guess you like

Origin blog.csdn.net/weixin_48470176/article/details/113715429