第二节 python 运算符与基本类型

运算符与基本类型

*************************************************2018 -10-3  day10-1

重点注释与文件的方式存储指令。

编程语言
高级
低级

Python种类
JavaPython
cPython *****
pypy

字节码 和 机器码

Python程序:
1.
终端:
C:\python35\python.exe D:\1.py
解释器:
C:\python35\python.exe

2. 文件形
#/usr/bin/u/ubv/a python

python 1.py

./1.py 加权限

3. 编码
#/usr/bin/u/ubv/a python
# -*- coding:utf-8 -*-    python 2编译出错
补充:

字节,位
unicode utf8 gbk
utf8: python 3
gbk :python 2

 

4. print("sdf")

5. inp = input('>>>')

PS:
>>> hello
inp = "hello"


>>> 10
inp = "10"

# 如果将字符串转换成数字 new_inp = int(inp)

inp * 10 =?????

6. 变量名

字母
数字
下划线

要求:
不能数字开头
不能使用关键字
建议不要用python内置的。。。。

7. 条件语句
1. 基本
2. 嵌套
3. if elif else ...

8. while循环
while 条件:
....

print('...')

补充:
a. while else
b. continue break
continue ,终止当前循环,开始下一次循环
break ,终止所有循环

用户登陆(三次机会重试)
count = 0
while count < 3:
user = input('>>>')
pwd = input('>>>')
if user == 'alex' and pwd == '123':
print('欢迎登陆')
print('..........')
break
else:
print('用户名或者密码错误')
count = count + 1

今日内容:

python开发IDE: pycharm、eclipse  IDE集成开发环境(IDE,Integrated Development Environment )

# 专业版
# 不要汉化

1、运算符
结果是值
算数运算
a = 10 * 10
赋值运算
a = a + 1 a+=1

结果是布尔值
比较运算
a = 1 > 5
逻辑运算
a = 1>6 or 1==1
成员运算
a = "蚊" in "郑建文"

2、基本数据类型


数字 int ,所有的功能,都放在int里
a1 = 123
>>> ord('b') >>> chr(100) >>> unichr(100) num='123'

v=int(num,base=16) print(v)以16进制的形式转化

test='alex'

test.center(self,with,fillchar=None) 看到self都忽略掉,带等号的可以忽略

with不能省

test.center(20)

Ex:test.count('a',2,5)从第几个开始找,到第几个

设置宽度,内容居中,并选择填充符号,只支持一个字符


- int
将字符串转换为数字
a = "123"
print(type(a),a)

b = int(a)
print(type(b),b)

num = "0011"
v = int(num, base=16)
print(v)
- bit_lenght
# 当前数字的二进制,至少用n位表示
r = age.bit_length()

字符串 str
s1 = "asdf"
s2 = "asdffas"

# test = "aLex"
# 首字母大写
# v = test.capitalize()
# print(v)

# 所有变小写,casefold更牛逼,很多未知的对相应变小写
# v1 = test.casefold()
# print(v1)
# v2 = test.lower()
# print(v2)

# 设置宽度,并将内容居中
# 20 代指总长度
# * 空白未知填充,一个字符,可有可无
# v = test.center(20,"中")
# print(v)

# 去字符串中寻找,寻找子序列的出现次数
# test = "aLexalexr"
# v = test.count('ex')
# print(v)

# test = "aLexalexr"
# v = test.count('ex',5,6)
# print(v)

# 欠
# encode
# decode

# 以什么什么结尾
# 以什么什么开始
# test = "alex"
# v = test.endswith('ex')
# v = test.startswith('ex')
# print(v)

# 欠
# test = "12345678\t9"
# v = test.expandtabs(6)
# print(v,len(v))

# 从开始往后找,找到第一个之后,获取其未知
# > 或 >=
# test = "alexalex"
# 未找到 -1
# v = test.find('ex')
# print(v)

# index找不到,报错 忽略
# test = "alexalex"
# v = test.index('8')
# print(v)


# 格式化,将一个字符串中的占位符替换为指定的值{}占位符
# test = 'i am {name}, age {a}'
# print(test)
# v = test.format(name='alex',a=19)
# print(v)

# test = 'i am {0}, age {1}'
# print(test)
# v = test.format('alex',19)
# print(v)

# 格式化,传入的值 {"name": 'alex', "a": 19}
# test = 'i am {name}, age {a}'
# v1 = test.format(name='df',a=10)
# v2 = test.format_map({"name": 'alex', "a": 19}) 字典的型式

# 字符串中是否只包含 字母和数字
# test = "123"
# v = test.isalnum()
# print(v)

列表 list
...
元祖 tuple
...
字典 dict
...

布尔值 bool
...

pcharm 网上求code,第一次可以用到2019-3-7

到时候,可以用pycharm Server解释器

pycharm 的项目可以名字 可以用 F:\Propy\Day10\py_3

直接在py_3 F:\Propy\Day10\py_3上右击—>>NEW>>创建文件夹 NEW>>(一个文件要19M)—>>python file—>>

设置背景颜色 —>>setting->>editor->>color scheme  字体

设置背景颜色 —>>setting->>输入mouse chang for size 就是可以按住滚轮调整字体

设置行号—>>show line number

整体注释 Ctrl + ?

*************************************************2018 -10-3  day10-4

not 非

v= user =='alex' and pwd=='12' or,由前面 到后,有真则继续如果是假的,就马上都是假的。

补充:

先计算括号内

执行顺序

从前到后

结果

True OR ->>True

True And ->>继续走

False OR->>继续走

False AND->>False

Python 2里因长度变化还有Long 类型而python 3里只int类型

a=111

int  float在python里输入,然后左键双击 所有的功能都出来了

str='alex'字符串

列表 list有自己的魔法

元组tuple

字典 dict

布尔值 bool

 

1、算数运算:

2、比较运算:

3、赋值运算:

4、逻辑运算:

5、成员运算:

基本数据类型

1、数字

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
  int
2、布尔值
  真或假
  1 或 0
3、字符串
"hello world"
字符串常用功能:
  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
复制代码
class str(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.
    """
    def capitalize(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.
        """
        return 0

    def 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 with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    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
        codecs.register_error that is able to handle UnicodeEncodeErrors.
        """
        return object()

    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.
        """
        return False

    def 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 ""

    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.
        """
        return 0

    def 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() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和数字 """
        """
        S.isalnum() -> bool
        
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self):  
        """ 是否是字母 """
        """
        S.isalpha() -> bool
        
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdigit(self):  
        """ 是否是数字 """
        """
        S.isdigit() -> bool
        
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def islower(self):  
        """ 是否小写 """
        """
        S.islower() -> bool
        
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isspace(self):  
        """
        S.isspace() -> bool
        
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self):  
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        S.isupper() -> bool
        
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable):  
        """ 连接 """
        """
        S.join(iterable) -> string
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None):  
        """ 内容左对齐,右侧填充 """
        """
        S.ljust(width[, fillchar]) -> string
        
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 变小写 """
        """
        S.lower() -> string
        
        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左侧空白 """
        """
        S.lstrip([chars]) -> string or unicode
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        S.partition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

    def replace(self, old, new, count=None):  
        """ 替换 """
        """
        S.replace(old, new[, count]) -> string
        
        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None):  
        """
        S.rfind(sub [,start [,end]]) -> int
        
        Return the highest 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.
        """
        return 0

    def rindex(self, sub, start=None, end=None):  
        """
        S.rindex(sub [,start [,end]]) -> int
        
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None):  
        """
        S.rjust(width[, fillchar]) -> string
        
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def rpartition(self, sep):  
        """
        S.rpartition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string, starting at the end of the string and working
        to the front.  If maxsplit is given, at most maxsplit splits are
        done. If sep is not specified or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割, maxsplit最多分割几次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
        """
        return []

    def splitlines(self, keepends=False):  
        """ 根据换行分割 """
        """
        S.splitlines(keepends=False) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None):  
        """ 是否起始 """
        """
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None):  
        """ 移除两段空白 """
        """
        S.strip([chars]) -> string or unicode
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大写变小写,小写变大写 """
        """
        S.swapcase() -> string
        
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string
        
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

    def translate(self, table, deletechars=None):  
        """
        转换,需要先做一个对应表,最后一个表示删除字符集合
        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)
        str = "this is string example....wow!!!"
        print str.translate(trantab, 'xm')
        """

        """
        S.translate(table [,deletechars]) -> string
        
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string
        
        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
        """
        S.zfill(width) -> string
        
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width.  The string S is never truncated.
        """
        return ""

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

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

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

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

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

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

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

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

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

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

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

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

    def __hash__(self):  
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, string=''): # known special case of str.__init__
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

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

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

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

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        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 __ne__(self, y):  
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

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

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

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __str__(self):  
        """ x.__str__() <==> str(x) """
        pass
复制代码
4、列表
创建列表:
1
2
3
name_list  =  [ 'alex' 'seven' 'eric' ]
name_list =  list ([ 'alex' 'seven' 'eric' ])

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含
  list
5、元祖
创建元祖:
1
2
3
ages  =  ( 11 22 33 44 55 )
ages  =  tuple (( 11 22 33 44 55 ))
基本操作:
  • 索引
  • 切片
  • 循环
  • 长度
  • 包含
  tuple
6、字典(无序)
创建字典:
1
2
3
person  =  { "name" "mr.wu" 'age' 18 }
person  =  dict ({ "name" "mr.wu" 'age' 18 })

常用操作:

  • 索引
  • 新增
  • 删除
  • 键、值、键值对
  • 循环
  • 长度
  dict
PS:循环,range,continue 和 break

其他

1、for循环
用户按照顺序循环可迭代对象中的内容,
PS:break、continue
1
2
3
li  =  [ 11 , 22 , 33 , 44 ]
for  item  in  li:
     print  item
2、enumrate
为可迭代的对象添加序号
1
2
3
li  =  [ 11 , 22 , 33 ]
for  k,v  in  enumerate (li,  1 ):
     print (k,v)
3、range和xrange
指定范围,生成指定的数字
1
2
3
4
5
6
7
8
print  range ( 1 10 )
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
print  range ( 1 10 2 )
# 结果:[1, 3, 5, 7, 9]
 
print  range ( 30 0 - 2 )
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]  

练习题

一、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
三、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
 
四、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
1
2
3
4
5
6
goods  =  [
     { "name" "电脑" "price" 1999 },
     { "name" "鼠标" "price" 10 },
     { "name" "游艇" "price" 20 },
     { "name" "美女" "price" 998 },
]

 五、用户交互,显示省市县三级联动的选择

1
2
3
4
5
6
7
8
9
10
11
12
13
dic  =  {
     "河北" : {
         "石家庄" : [ "鹿泉" "藁城" "元氏" ],
         "邯郸" : [ "永年" "涉县" "磁县" ],
     }
     "河南" : {
         ...
     }
     "山西" : {
         ...
     }
 
}

转载于:https://www.cnblogs.com/zhangjiancun/p/9739332.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值