zoukankan      html  css  js  c++  java
  • 《python基础教程》笔记之 基础知识

    • 数字相关

    在Python程序前加上 from __future__ import division 或者在解释器里面直接执行它,或者通过命令行运行Python时使用命令开关-Qnew,会使单斜线不再整除,如

    >>> 1/2
    0.5

    而双斜线实现整除,如

    >>> 1//2
    0

    •  输入

    >>> x = input('x:')

    • 模块

    用import导入模块,然后按照“模块.函数”的格式使用这个模块的函数,如

    >>> import math
    >>> math.floor(23.96)
    23.0

     在使用了“form模块import函数”这种形式的import命令之后,就可以直接使用函数,而不需要模块名作为前缀了,如

    >>> from math import sqrt
    >>> sqrt(9)
    3.0

    CMath模块可以实现处理复数,如

    >>> cmath.sqrt(-9)
    3j

    • 程序

    在IDLE中,file->new file会弹出一个编辑窗口,在里面编辑如下

    name = raw_input("what is your name")
    print 'hello,' + name + '!'

    然后file-save 保存为hell.py,然后F5运行,则在解释器中出现结果,如

    >>> ================================ RESTART ================================
    >>>
    what is your name55
    hello,55!

    或者双击hell.py,则命令行窗口一闪而逝。

    在代码中,#右边的一切都会被忽略,那部分即为注释。

    •  字符串

    反引号、str和repr是将值转换为字符串的三种方式,其中str会把值转换为合理形式的字符串,以便用户理解,而repr会创建一个字符串,以合法的平Python表达式的形式来表示值,如

    tmp = 1000
    print 'hello ' +  `tmp`
    print 'hello ' +  str(tmp)
    print 'hello ' + repr(tmp)

    结果如下
    hello 1000
    hello 1000
    hello 1000

    input会假设用户输入的是合法的Python表达式(或多或少有些与repr函数相反的意思),raw_input会把所有的输入当做原始数据,然后将其放到字符串中,如

    print 'hello ' + raw_input('your name:')
    print 'hello ' + input('your name:')

    结果如下

    your name:55
    hello 55
    your name:55

    Traceback (most recent call last):
      File "E:/work/Code/python/hell.py", line 2, in <module>
        print 'hello ' + input('your name:')
    TypeError: cannot concatenate 'str' and 'int' objects

    如果要书写一个跨多行的长字符串,可以使用三个引号代替普通引号,如

    print '''This is a long string.
    it continues here.
    and it's not over yet.
    "hello world!".
    still here.'''

    结果如下
    This is a long string.
    it continues here.
    and it's not over yet.
    "hello world!".

    普通字符串也可以跨行,如果一行之中最后一个字符是反斜线,那么,换行本身就“转义”了,也就是被忽略了(同时适用于表达式),如

    print 'This is a long string.
    it stop here.'

    结果

    This is a long string.it stop here.

    原始字符串不会吧反斜线当做特殊字符,在元是字符串中输入的每个字符都会与书写的方式保持一致,如

    print r'E:workCodepython' '\'

    结果如下

    E:workCodepython

  • 相关阅读:
    Redux其实很简单(原理篇)
    基于Docker的UI自动化初探
    视觉设计师的进化
    浅谈容器监控和网易云计算基础服务实践
    微服务实践沙龙-上海站
    知物由学 | 见招拆招,Android应用破解及防护秘籍
    6本互联网技术畅销书免费送(数据分析、深度学习、编程语言)!
    Lily-一个埋点管理工具
    ArcGIS 10 许可配置
    How to Programmatically Add/Delete Custom Options in Magento?
  • 原文地址:https://www.cnblogs.com/qiantangbanmu/p/4301547.html
Copyright © 2011-2022 走看看