python返回变量x的数据类型_Python变量与数据类型
⼀. 变量
类似于初中代数的⽅程变量⼀样,只是在计算机程序中,变量不仅可以是数字,还可以是任意数据类型。变量必须是⼤⼩写英⽂,数字和下划线(_)的组合,并且不能⽤数字开头。
变量命名规则:
变量名只能是字母,数字和下划线的任意组合
变量名第⼀个字符不能是数字
变量名区分⼤⼩写,⼤⼩写字母被认为是两个不同的字符
特殊关键字不能命名为变量名
# 保留关键字,不可以作为变量名
and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for','from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'not','or', 'pass', 'print',
'raise', 'return', 'try','while', 'with', 'yield'
(1)声明变量
#!/usr/bin/env python3
#-*- coding:utf-8-*-
name = "hello"
上述代码声明了⼀个变量,变量名为:name, 变量name的值为"hello"。
变量的作⽤:昵称,其代指内存⾥某个地址中保存的内容。
(2)变量赋值
在Python中,等号= 是赋值语句,可以把任意数据类型赋值给变量,同⼀个变量可以反复赋值,⽽且可以是不同类型的变量。
a = 123 # a 是整数
a = 'abc' # a 是字符串
这种变量本⾝类型不固定的语⾔称之为动态语⾔,与之对应的就是静态语⾔。静态语⾔在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语⾔,赋值语句如下(//表⽰注释):
int a = 123; // a 是整数类型变量
a = "abc"; // 错误:不能把字符串赋值给整型变量
和静态语⾔相⽐,动态语⾔更灵活,就是这个原因。特别注意的是:不要将赋值语句的等号等同于数学的等号!
a = 1
a = a + 1
print(a)
上述代码 a 的结果为 2,因为在程序中,赋值语句先计算右侧的表达式 a + 1,得到结果在赋值给a。最后 a = 2。
理解变量在计算机内存中的表⽰⾮常重要~!
>>> name1 = 'hello'
>>> name2 = 'world'
>>> name3 = name2
>>> id(name1)
2463739724384
>>> id(name2)
2463739724496
>>> id(name3)
2463739724496
# 通过id这个内置函数,我们可以看到变量的内存地址
"""
name2 和 name3 都是'world',看到他们的内存地址都是⼀样的,
说明在name3中并没有在内存中创建新内容⽽是将name3指向了已存在的'world',
name2和name3共同指向⼀个内存地址
"""
>>> name1 = 'hello'
>>> name2 = 'world'
>>> name3 = name2
>>> name2 = 'OK'
# name2 更换内容后,name3会怎样呢?
⼆. 常量
所谓常量就是不能变的变量,⽐如常⽤的数学常数π就是⼀个常量。在Python中,通常⽤全部⼤写的变量名表⽰常量:
BI = 3.14
但事实上 BI 仍然是个变量,Python根本⽆法保证 BI 不会被改变,所以,⽤全部⼤写的变量名表⽰常量只是⼀个习惯上的⽤法,如果你⼀定要改,没⼈能拦得住你。
三. 数据类型
不同的数据,需要定义不同的数据类型。在Python中,能够直接处理的数据类型如下:
(1)整数(int)
Python可以处理任意⼤⼩的整数,当然也包括负整数。
(2)浮点数(float)
浮点数也就是⼩数,之所以成为浮点数,是因为按照科学计数法表⽰时,⼀个浮点数的⼩数点位置是可以变的,⽐如1.23x10九次⽅(输⼊法写不出来呀)和12.3x10⼋次⽅是完全相等。
注意:整数和浮点数在计算机内部存储的⽅式是不同的,整数运算永远是精确的,⽽浮点数运算咋可能会有四舍五⼊的误差。
(3)字符串(string)
字符串是以单引号 ' 或 双引号  " 括起来的内容,⽐如 'abc', "dfg"等等。请注意,单引号或双引号本⾝只是⼀种表⽰⽅式,不是字符串的⼀部分,如果⼀个字符串本⾝也包含单引号或者双引号,我们需要通过转义字符\来标识。
>>> a = 'I\'m \"OK\"!'
>>> print(a)
I'm "OK"!
转义字符 \ 可以转义很多字符,⽐如 \n 标识换⾏, \t 标识制表符, 字符 \ 本⾝也要转义,所以 \\ 就表⽰字符 \ 。
字符串运算符:
+            # 字符串连接
*            # 重复输出字符串,string*2 输出为stringstring
string[ : ]  # 通过索引获取字符串中的字符
in            # 成员运算符-如果字符串中包含给定的字符返回True, 否则为False
not in      # 如果字符串中不包含给定的字符返回True, 否则为False
r/R          # 和转义符相同效果, print( r"\n") 可以直接输出 \n
%            # 格式字符串,格式化输出时使⽤
classstr(basestring):"""str(object='') -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object."""
defcapitalize(self):"""⾸字母变⼤写"""
"""S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized."""
return ""
def center(self, width, fillchar=None):"""内容居中,width:总长度;fillchar:空⽩处填充内容,默认⽆"""
"""S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)"""
return ""
def count(self, sub, start=None, end=None):"""⼦序列个数"""
"""S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation."""
return0def decode(self, encoding=None, errors=None):"""解码"""
"""S.decode([encoding[,errors]]) -> object
Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered ister_error that is
able to handle UnicodeDecodeErrors."""
returnobject()def encode(self, encoding=None, errors=None):"""编码,针对unicode"""
"""S.encode([encoding[,errors]]) -> object
Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
returnobject()def endswith(self, suffix, start=None, end=None):"""是否以 xxx 结束"""
"""S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try."""
returnFalsedef expandtabs(self, tabsize=None):"""将tab转换成空格,默认⼀个tab转换成8个空格""" """S.expandtabs([tabsize]) -> string
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed."""
return ""substring和slice
def find(self, sub, start=None, end=None):"""寻⼦序列位置,如果没到,返回 -1"""
"""S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure."""
return0def format(*args, **kwargs): #known special case of str.format
"""字符串格式化,动态参数,将函数式编程时细说"""
"""S.format(*args, **kwargs) -> string
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}')."""
pass
def index(self, sub, start=None, end=None):"""⼦序列位置,如果没到,报错"""S.index(sub [,start [,end]])->int
Like S.find() butraise ValueError when the substring is notfound."""return 0
def isalnum(self):""" 是否是字母和数字 """
"""S.isalnum()->bool
Return Trueif all characters inS are alphanumericand there is at least one character inS, False otherwise."""return False
def isalpha(self):""" 是否是字母 """
"""S.isalpha()->bool
Return Trueif all characters inS are alphabeticand there is at least one character inS, False otherwise."""return False
def isdigit(self):""" 是否是数字 """
"""S.isdigit()->bool
Return Trueif all characters inS are digitsand there is at least one character inS, False otherwise."""return False
def islower(self):""" 是否⼩写 """
"""S.islower()->bool
Return Trueif all cased characters in S are lowercase and there isat least one cased characterinS, False otherwise."""return False
def isspace(self):"""S.isspace()->bool
Return Trueif all characters inS are whitespaceand there is at least one character inS, False otherwise."""return False
def istitle(self):"""S.istitle()->bool
Return Trueif S is a titlecased string and there isat least one
characterinS, i.e. uppercase characters may only follow uncased
charactersandlowercase characters only cased ones. Return False
otherwise."""return False
def isupper(self):"""S.isupper()->bool
Return Trueif all cased characters in S are uppercase and there isat least one cased characterinS, F
alse otherwise."""return False
def join(self, iterable):""" 连接 """
"""S.join(iterable)->string
Return a string whichis the concatenation of the strings inthe
iterable. The separator between elementsisS."""return ""
def ljust(self, width, fillchar=None):""" 内容左对齐,右侧填充 """
"""S.ljust(width[, fillchar])->string

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。