Python学习笔记【一】——《python基础教程》::基础知识

第1章 基础知识

1.4. 数字和表达式

  1. 设置python执行普通除法(即浮点除法),程序前添加:from future import division

  2. 整除(即整形数除法)操作符://

    >>>1.0/2.0
    0.5
    >>>1.0//2.0 
    0 
    
  3. 幂运算符:**

    >>>2**3
    8
    

1.7. 获取用户输入

>>>input("The meaning of life: ")
The meaning of life: 42
42

1.9. 模块

定义:导入到Python以增强其功能的扩展。

导入方式函数调用
import 模块模块.函数()
from 模块 import 函数函数()

1.9.1. cmath和负数

模块cmath处理复数

1.9.2. 回到_future_

__future__模块导入将来可能成为python部分的特性

1.10. 保存并执行程序

1.10.2. 让脚本像普通程序一样执行

在python脚本首行添加如下代码:

#!/usr/bin/python2

其中,!后为python程序的绝对路径

1.10.3. 注释

"#"字符之后为注释内容

1.11. 字符串**

1.11.1. 单引号字符串和转义引号

  1. "xxx"与’xxx’均可标识字符串

  2. ""与’'可相互嵌套,但是与自身嵌套解释器会解析错误,例如

    #正确语法
    >>> "hello, 'world'" "hello, 'world'"
    >>> 'hello, "world"' 'hello, "world"'
    #错误语法
    >>> "hello, "world""   
    File "<stdin>", line 1
        "hello, "world""
               		 ^ 
    SyntaxError: invalid syntax
    >>> 'hello, 'world''   
    File "<stdin>", line 1
        'hello, 'world''
                     ^ 
    SyntaxError: invalid syntax
    

    其中,错误语法很好理解,由于解析器需要将""和’'两两配对,当出现自身嵌套的情况时,解析器会将相邻的"或’进行配对,导致错误。

  3. 转义字符 \。

1.11.3. 字符串表示

  1. str():值转换为合理性是字符串;
  2. repr():创建一个字符串,以合法的python形式表示值;
  3. repr(xxx) = `xxx` ,其中 ` 为反引号

1.11.4. input和raw_input的比较

  1. input():假设输入的是合法的python表达式

    #错误语法
    >>> input("what's your name: ")
    what's your name: abc
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
    NameError: name 'abc' is not defined
    #正确语法
    >>> input("what's your name: ")
    what's your name: "abc"
    'abc'
    

    可见,错误语法中,字符串abc未使用python合法格式(使用""或’'括起来),input无法辨认而出错。

  2. raw_input():所有输入作为原始数据,放入字符串中

    >>> raw_input("what's your name: ")
    what's your name: abc
    'abc'
    

1.11.5. 长字符串、原始字符串和Unicode

  1. 长字符串:使用’’‘xxx’’'或""“xxx”"",其中xxx可以换行,可使用 ’ 或 ‘’,不必添加转义字符。

    >>> print '''This is a very long string.
    ... It continues here.
    ... And it's not over yet.
    ... "Hello, world!"
    ... Still here.'''
    This is a very long string.
    It continues here.
    And it's not over yet.
    "Hello, world!"
    Still here.
    #其中,...为python解释器输出表示继续输入,可忽略。
    
  2. 原始字符串
    1)不会将 \ 作为特殊字符处理
    2)用法:r’raw string’
    3)不可用 \ 结尾

  3. Unicode字符串:u’unicode string’

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值