python之基本数据类型及for循环

一.运算符

Python语言支持以下类型的运算符:

  • 算术运算符

如:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
print(a + b)
  • 比较运算符

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
if a < b:
    print(True)
else:
    print(False)
  • 赋值运算符

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = a
print(b)
  • 逻辑运算符

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

a = 5
b = 6
if a >4 and b < 10:
    print(True)
else:
    print(False)
  • 成员运算符

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "a"
list = [‘a‘,‘b‘]

if value in list:
    print(True) 

二.数据类型

  1. 数字

int(整形),数字数据类型用于存储数值

Python 支持三种不同的数值类型:

  • 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
  • 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
  • 复数- 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型

class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long

    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.

    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int(‘0b100‘, base=0)
    """
    def bit_length(self):
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int

        Number of bits necessary to represent self in binary.
        >>> bin(37)
        ‘0b100101‘
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回该复数的共轭复数 """
        """ Returns self, the complex conjugate of any int. """
        pass

    def __abs__(self):
        """ 返回绝对值 """
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y):
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y):
        """ 比较两个数大小 """
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y):
        """ 强制生成一个元组 """
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y):
        """ 相除,得到商和余数组成的元组 """
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y):
        """ x.__div__(y) <==> x/y """
        pass

    def __float__(self):
        """ 转换为浮点类型 """
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y):
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, name):
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        """ 内部调用 __new__方法或创建对象时传入参数使用 """
        pass

    def __hash__(self):
        """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
        """ x.__hash__() <==> hash(x) """
        pass

    def __hex__(self):
        """ 返回当前数的 十六进制 表示 """
        """ x.__hex__() <==> hex(x) """
        pass

    def __index__(self):
        """ 用于切片,数字无意义 """
        """ x[y:z] <==> x[y.__index__():z.__index__()] """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long

        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.

        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int(‘0b100‘, base=0)
        # (copied from class doc)
        """
        pass

    def __int__(self):
        """ 转换为整数 """
        """ x.__int__() <==> int(x) """
        pass

    def __invert__(self):
        """ x.__invert__() <==> ~x """
        pass

    def __long__(self):
        """ 转换为长整数 """
        """ x.__long__() <==> long(x) """
        pass

    def __lshift__(self, y):
        """ x.__lshift__(y) <==> x<<y """
        pass

    def __mod__(self, y):
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y):
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self):
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more):
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __nonzero__(self):
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __oct__(self):
        """ 返回改值的 八进制 表示 """
        """ x.__oct__() <==> oct(x) """
        pass

    def __or__(self, y):
        """ x.__or__(y) <==> x|y """
        pass

    def __pos__(self):
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None):
        """ 幂,次方 """
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y):
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y):
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y):
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y):
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self):
        """转化为解释器可读取的形式 """
        """ x.__repr__() <==> repr(x) """
        pass

    def __str__(self):
        """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
        """ x.__str__() <==> str(x) """
        pass

    def __rfloordiv__(self, y):
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rlshift__(self, y):
        """ x.__rlshift__(y) <==> y<<x """
        pass

    def __rmod__(self, y):
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y):
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y):
        """ x.__ror__(y) <==> y|x """
        pass

    def __rpow__(self, x, z=None):
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rrshift__(self, y):
        """ x.__rrshift__(y) <==> y>>x """
        pass

    def __rshift__(self, y):
        """ x.__rshift__(y) <==> x>>y """
        pass

    def __rsub__(self, y):
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y):
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y):
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sub__(self, y):
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y):
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs):
        """ 返回数值被截取为整形的值,在整形中无意义 """
        pass

    def __xor__(self, y):
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虚数,无意义 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 数字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 实属,无意义 """
    """the real part of a complex number"""

int

2.布尔值

真或者假,1或者0

3.字符串

字符串是python中最常见类型,我们通常用单引号(‘‘)或者双引号("")来创建

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "a"
print(value)

字符串常用功能:

  • 移除空白

例;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = " a "
ret = value.strip()
print(ret)
  • 分割

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value.split(‘,‘)
print(ret)
  • 长度

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value.__len__()
print(ret)
  • 索引

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value[0]
print(ret)
  • 切片

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "hello,world"
ret = value[0:6]
print(ret)

字符串内建函数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
capitalize()
将字符串的第一个字符转换为大写
"""
value = " hello,world "
ret = value.capitalize()
print(ret)
"""
center(width, fillchar)
返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格
"""
ret = value.center(30)
print(ret)

"""
count(str, beg= 0,end=len(string))
返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
"""
ret = value.count(‘l‘)
print(ret)
"""
decode(encoding=‘UTF-8‘,errors=‘strict‘)
使用指定编码来解码字符串。默认编码为字符串编码
encode(encoding=‘UTF-8‘,errors=‘strict‘)
以 encoding 指定的编码格式编码字符串

temp = "中文"
#解码,需要指定原来是什么编码
temp_unicode = temp.decode(‘utf-8‘)
#编码,需要指定要编成什么编码
temp_gbk = temp_unicode.encode(‘gbk‘)
print(temp_gbk)
"""
"""
endswith(suffix, beg=0, end=len(string))
检查字符串是否以某字符串结尾如果是,返回 True,否则返回 False.
"""
ret = value.endswith(‘d‘)
print(ret)
"""
expandtabs(tabsize=8)
把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8
"""
ret = value.expandtabs()
print(ret)
"""
find(str, beg=0 end=len(string))
检测 str 是否包含在字符串中 中,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
"""
ret = value.find(‘h‘)
print(ret)

"""
index(str, beg=0, end=len(string))
跟find()方法一样,只不过如果str不在字符串中会报一个异常,使用find方法最佳
"""
"""
isdigit()
如果字符串只包含数字则返回 True 否则返回 False
"""
ret = value.isdigit()
print(ret)

"""
lstrip()
截掉字符串左边的空格
"""
ret = value.lstrip()
print(ret)

"""
rstrip()
删除字符串字符串末尾的空格
"""
ret = value.rstrip()
print(ret)
"""
split(str="", num=string.count(str))
num=string.count(str)) 以 str 为分隔符截取字符串
"""
ret = value.split(‘,‘)
print(ret)

"""
strip([chars])
去除左右空格
"""
ret = value.strip()
print(ret)

"""
title()
返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写
"""
ret = value.title()
print(ret)

python字符串格式化符号:

4.列表

列表中每个位置都分配一个数字,从0开始,依此类推

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 循环
  • 包含

创建列表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = [‘a‘,‘b‘]

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-"""索引"""
list = [‘a‘,‘b‘]
ret = list[0]
print(ret)

  切片

#!/usr/bin/env python
# -*- coding:utf-8 -*-"""切片"""
list = [‘a‘,‘b‘,‘c‘]
ret = list[0:2]
print(ret)

  追加

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
追加
"""
list = [‘a‘,‘b‘,‘c‘]
list.append(‘d‘)
print(list)

删除

#!/usr/bin/env python
# -*- coding:utf-8 -*-"""删除索引1"""
list = [‘a‘,‘b‘,‘c‘]
print(list)
del list[1]
print(list)

长度

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = [‘a‘,‘b‘,‘c‘]
ret=list.__len__()
print(ret)

  循环

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = [‘a‘,‘b‘,‘c‘]

for i in list:
    print(i)

  包含

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = [‘a‘,‘b‘,‘c‘]
list2 = [‘d‘,‘e‘]
total = [list + list2]
print(total)

列表中内置函数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
排序
"""
list = [1,4,2,3,4,5,10,3]
list.sort()
print(list)

"""
list.count(obj)
统计某个元素在列表中出现的次数
"""
ret = list.count(3)
print(ret)

"""
list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
"""
list2 = [100,101,105]
list.extend(list2)
print(list)

"""
list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
"""
list.pop()
print(list)
"""
list.remove(obj)
移除列表中某个值的第一个匹配项
"""
list.remove(1)
print(list)
"""
list.reverse()
反向列表中元素
"""
list.reverse()
print(list)
"""
list.clear()
清空列表
"""
list.clear()
print(list)

5.元组

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号

创建元组

#!/usr/bin/env python
# -*- coding:utf-8 -*-
tup = (‘a‘,‘b‘,‘c‘)

基本操作:

  • 索引
  • 切片
  • 循环
  • 长度
  • 包含
#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = [‘a‘, ‘b‘, ‘c‘]

"""
tuple(seq)
将列表转换为元组
"""
tup = tuple(list)
print(tup)

6.字典

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中

创建字典

person = {"name": "liu", ‘age‘: 18}

键必须是唯一的,值不必

  常用操作:

  • 索引
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic1 = dic["name"]
print(dic1)
  • 新增
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic["address"] = "beijing"
print(dic)
  • 删除
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

dic["address"] = "beijing"
del dic["age"]
print(dic)
  • 键、值、键值对
  • 循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

for key,value in dic.items():
    print(key,value)
  • 长度
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic = {
    "name":"mary","age":20
}

print(len(dic))

字典内建函数

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object‘s
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """

    def clear(self): # real signature unknown; restored from __doc__
        """ 清除内容 """
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ 浅拷贝 """
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根据key获取值,d是默认值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 所有项的列表形式 """
        """ D.items() -> list of D‘s (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 项可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D‘s keys """
        return []

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """ 更新
            {‘name‘:‘alex‘, ‘age‘: 18000}
            [(‘name‘,‘sbsbsb‘),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k in F: D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ 所有的值 """
        """ D.values() -> list of D‘s values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有项,只是将内容保存至view对象中 """
        """ D.viewitems() -> a set-like object providing a view on D‘s items """
        pass

    def viewkeys(self): # real signature unknown; restored from __doc__
        """ D.viewkeys() -> a set-like object providing a view on D‘s keys """
        pass

    def viewvalues(self): # real signature unknown; restored from __doc__
        """ D.viewvalues() -> an object providing a view on D‘s values """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object‘s
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

dict

三.for循环

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串,格式如下

for value in seq:
    do xx

#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    print(i)

也可以break,continue

#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    if i == 5:
        break
    print(i)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

list = [1,2,5,7]
for i in list:
    if i == 5:
        continue
    print(i)

2.enumrate

为可迭代的对象添加序号

#!/usr/bin/env python
# -*- coding:utf-8 -*-

li = [11,22,33]
for k,v in enumerate(li, 1):
    print(k,v)

3.range和xrange

指定范围,生成指定的数字

#!/usr/bin/env python
# -*- coding:utf-8 -*-

for i in range(10):
    print(i)
时间: 2024-10-21 14:33:10

python之基本数据类型及for循环的相关文章

小Y的Python学习日志--数据类型(if 循环)

#本文仅为个人学习过程的整理和记录,如有从他人博客.网站摘录的内容,本人会明确标明,如有涉及侵权,请联系本人,本人会在第一时间删除.  以下的资料整理来自(1)廖雪峰的Python教程 http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000 (2)简明Python教程 http://woodpecker.org.cn/abyteofpython_cn/chinese/ 1. 流程控制 (

Python之基本数据类型

Python之数据类型 int 整数 在python3中所有的整数都是int类型.但在python2中如果数据量比较大,会使用long类型 而python3中不存在long类型 + - * / //取整 %取余 **幂运算 # 可进行的操作 .bit_length() # 计算整数在内存中占用的二进制码的长度 num = 13456845 print(num.bit_length()) # 补充点 二进制 十进制和二进制相互转化 十进制转化成二进制:除二取余,倒序排列 二进制转十进制的转换原理:

python基础之数据类型补充(基础五)

第七章 python基础之数据类型补充(基础五) 7.1 数据类型补充 字符串str,整型int,列表list,元组tuple,字典dict. 7.1.1 字符串str类型补充 s1 = str(123) #类型字符串 s.capitalize() 首字母大写 s = "alex wusir" s1 = s.capitalize() #首字母大写:Alex wusir print(s1) s.title() 每个单词首字母大写 s = "alex wusir" s1

Python之基本数据类型及内置方法

Python之基本数据类型及内置方法 数字类型 整型 1.作用 年龄/id 2.定义方式 x = 10 3.使用方法 + - * / % // ** < <= > >= == != 4.有序or无序 有索引的就有序,无索引的就无序 压根就没有有序无序一说 5. 可变or不可变 值变id不变叫可变,值不变id变叫不可变 整型不可变 x = 10 print(id(x)) x += 1 print(id(x)) 浮点型 1.作用 薪资 2.定义方式 x = 10.1 3.使用方法 +

Python自习室——002 数据类型

python内建数据类型主要有数值.字符.列表.字典.元组.

python基础之数据类型

1.数据类型 python中的数据类型 python使用对象模型来存储数据,每一个数据类型都有一个内置的类,每新建一个数据,实际就是在初始化生成一个对象,即所有数据都是对象. 2.字符串 2.1定义定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,''或""或''' '''中间包含的内容称之为字符串特性:1.只能存放一个值2.不可变3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序 2.2字符串常用操作 msg='hello'移除空白 msg.strip()分割

小Y的Python学习日志--数据类型

#本文仅为个人学习过程的整理和记录,如有从他人博客.网站摘录的内容,本人会明确标明,如有涉及侵权,请联系本人,本人会在第一时间删除. 一下的资料整理来自(1)廖雪峰的Python教程 http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000 (2)简明Python教程 http://woodpecker.org.cn/abyteofpython_cn/chinese/ 四.Python数据

python学习笔记七:条件&循环语句

1.print/import更多信息 print打印多个表达式,使用逗号隔开 >>> print 'Age:',42 Age: 42   #注意个结果之间有一个空格符 import:从模块导入函数 import 模块 from 模块 import 函数 from 模块 import * 如果两个模块都有open函数的时候, 1)使用下面方法使用: module1.open()... module2.open()... 2)语句末尾增加as子句 >>> import ma

Python变量和数据类型

一.Python中的数据类型主要有以下五种 (1).整数 (2).浮点数 (3).字符串 :用''或""括起来的任意文本 (4).布尔值 :只有True和False两种值(注意两个都是大写),布尔值可以用and .or和not运算:Python把0.空字符串''和None看成 False,其他数值和非空字符串都看成 True: (5).空值:Python里的一个特殊值,用None来表示,但None不能理解为0,因为0是有意义的,而None是   一个特殊的空值; 二.Python中如何