当前位置: 首页 > news >正文

Python3学习第四天

文章目录

  • Python3 基础语法
    • 注释
      • 单行注释
      • 多行注释
    • 行与缩进
    • 数字(Number)类型
    • 字符串(String)
    • python保留字
    • 空行
    • 等待用户输入
    • 同一行显示多条语句
    • import 与 from...import
      • 导入 sys 模块
      • 导入 sys 模块的 argv,path 成员
    • 命令行参数

Python3 基础语法

注释

单行注释

Python中单行注释以 # 开头,实例如下

#!/usr/bin/python3
 
# 第一个注释
print ("Hello, Python!") # 第二个注释

多行注释

多行注释可以用多个#号,还有 '''"""

#!/usr/bin/python3
 
# 第一个注释
# 第二个注释
 
'''
第三注释
第四注释
'''
 
"""
第五注释
第六注释
"""
print ("Hello, Python!")

行与缩进

python最具特色的就是使用缩进来表示代码块,不需要使用大括号{}

if True:
    print ("True")
else:
    print ("False")

数字(Number)类型

python中数字有四种类型:整数、布尔型、浮点数和复数。

类型类型中文说明
int整数只有一种整数类型 int,表示为长整型,没有 python2 中的 Long
bool布尔如 True
float浮点数如 1.23、3E-2
complex复数如 1 + 2j、 1.1 + 2.2j

字符串(String)

python中单引号和双引号使用完全相同。
使用三引号('''""")可以指定一个多行字符串。
转义符 '\'
反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n"\n会显示,并不是换行。
按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
字符串可以用 + 运算符连接在一起,用 * 运算符重复。
Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
Python中的字符串不能改变。
Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
字符串的截取的语法格式如下:变量[头下标:尾下标:步长]

word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
#!/usr/bin/python3
 
str='Runoob'
 
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第五个的字符
print(str[2:])             # 输出从第三个开始后的所有字符
print(str * 2)             # 输出字符串两次
print(str + '你好')        # 连接字符串
 
print('------------------------------')
 
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

点击运行
在这里插入图片描述

python保留字

#python保留字

import keyword
keyword.kwlist
python保留字
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。

等待用户输入

input("\n\n按下 enter 键后退出。")

在这里插入图片描述

同一行显示多条语句

import sys; x = '你好python3'; sys.stdout.write(x + '\n')

结果你好python3

import 与 from…import

在 python 用 import 或者 from...import 来导入相应的模块。

将整个模块(somemodule)导入,格式为: import somemodule

从某个模块中导入某个函数,格式为: from somemodule import somefunction

从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为: from somemodule import *

导入 sys 模块

import sys
print('================Python import mode==========================')
print ('命令行参数为:')
for i in sys.argv:
    print (i)
print ('\n python 路径为',sys.path)

导入 sys 模块的 argv,path 成员

from sys import argv,path  #  导入特定的成员
 
print('===python from import===')
print('path:',path) # 因为已经导入path成员,所以此处引用时不需要加sys.path

命令行参数

$ python -h

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I     : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O     : remove assert and __debug__-dependent statements; add .opt-1 before
         .pyc extension; also PYTHONOPTIMIZE=x
-OO    : do -O changes and also discard docstrings; add .opt-2 before
         .pyc extension
-q     : don't print version and copyright messages on interactive startup
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-u     : force the stdout and stderr streams to be unbuffered;
         this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version)
         when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:
    control how Python invalidates hash-based .pyc files
file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ':'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>:<exec_prefix>).
               The default module search path uses <prefix>/lib/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
   to seed the hashes of str, bytes and datetime objects.  It can also be
   set to an integer in the range [0,4294967295] to get hash values with a
   predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
   on Python memory allocators. Use PYTHONMALLOC=debug to install debug
   hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
   coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
   locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
   debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.

我们在使用脚本形式执行 Python 时,可以接收命令行输入的参数,具体使用可以参照 Python 3 命令行参数。

相关文章:

  • 解决中国大学MOOC遮挡字幕问题
  • Deepin_wine安装超星阅读器及解决乱码问题
  • linux为文件创建软链接
  • 判断回文数
  • 两数相加_详解
  • 第N高的薪水
  • 合并两个有序链表(merge-two-sorted-lists)
  • 移除元素remove-element
  • 删除排序数组中的重复项Remove Duplicates from Sorted Array
  • 字符串转换整数 (string-to-integer-atoi)
  • 最长公共前缀(longest-common-prefix)
  • 罗马数字转整数(roman-to-integer)
  • 删除链表的倒数第N个节点(remove-nth-node-from-end-of-list)
  • 为什么说合数它一定能够被某个素数整除?
  • 实现 strStr()采用kmp算法
  • .pyc 想到的一些问题
  • 【347天】每日项目总结系列085(2018.01.18)
  • CSS中外联样式表代表的含义
  • Fabric架构演变之路
  • FastReport在线报表设计器工作原理
  • gcc介绍及安装
  • happypack两次报错的问题
  • IndexedDB
  • MD5加密原理解析及OC版原理实现
  • Node 版本管理
  • node学习系列之简单文件上传
  • python 装饰器(一)
  • Python实现BT种子转化为磁力链接【实战】
  • Vue.js-Day01
  • vue从创建到完整的饿了么(11)组件的使用(svg图标及watch的简单使用)
  • WebSocket使用
  • Yeoman_Bower_Grunt
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 关于List、List?、ListObject的区别
  • 聊聊directory traversal attack
  • 免费小说阅读小程序
  • 前端 CSS : 5# 纯 CSS 实现24小时超市
  • 浅谈JavaScript的面向对象和它的封装、继承、多态
  • 入口文件开始,分析Vue源码实现
  • 使用SAX解析XML
  • #!/usr/bin/python与#!/usr/bin/env python的区别
  • #define,static,const,三种常量的区别
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • (4)logging(日志模块)
  • (4)事件处理——(6)给.ready()回调函数传递一个参数(Passing an argument to the .ready() callback)...
  • (Mac上)使用Python进行matplotlib 画图时,中文显示不出来
  • (八)Spring源码解析:Spring MVC
  • (三)Hyperledger Fabric 1.1安装部署-chaincode测试
  • (译)计算距离、方位和更多经纬度之间的点
  • (转载)虚函数剖析
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .Net 6.0 处理跨域的方式
  • .NET Conf 2023 回顾 – 庆祝社区、创新和 .NET 8 的发布
  • .NET Framework .NET Core与 .NET 的区别
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例