python 基础语法

1.查看python版本

python -V

以上命令执行结果如下:

2.标识符

  • 第一个字符必须是字母表中字母或下划线 _ 。
  • 标识符的其他的部分由字母、数字和下划线组成。
  • 标识符对大小写敏感。

3.python保留字

  保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

>>> import keyword
>>> keyword.kwlist
['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']

4.注释

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

# 第一个注释
print ("Hello, Python!")  

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

# 第一个注释
# 第二个注释

'''
第三注释
第四注释
'''

"""
第五注释
第六注释
"""
print ("Hello, Python!") 

5.行与缩进

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

  缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。

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

  以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:

if True:
    print('C')
    print('C#')
else:
    print('python')
   print('java')    # 缩进不一致,会导致运行错误

错误:IndentationError: unindent does not match any outer indentation level

  补充:if else 后的参数可不写"()",单必须写":"

6.多行语句

  Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠(\)来实现多行语句

total = "item_one \
         item_two \
         item_three"

  在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)

total = ['one',
         'two',
         'three'] 

7.等待用户输入

temp = input('\n请输入内容:')
print(temp)

  \n在结果输出前会输出个新的空行

8.同一行显示多条语句

   Python可以在同一行中使用多条语句,语句之间使用分号(;)分割

import sys; x = 'runoob'; sys.stdout.write(x + '\n')
# 输出结果:runoob

9.Print 输出

  print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""

string1 = "one"
string2 = "two"

# 换行输出
print(string1)
print(string2)

# 不换行输出
print(string1,end=" ")
print(string2)

10.import 与 from...import

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

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

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

  从某个模块中导入多个函数,格式为:from turtle import done,deepcopy

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

import turtle
from turtle import done
from turtle import done,deepcopy
from turtle import *

11.命令行参数

  很多程序可以执行一些操作来查看一些基本信息,Python可以使用-h参数查看各参数帮助信息

posted @ 2018-06-02 17:49  没事儿写个bug  阅读(255)  评论(0编辑  收藏  举报