第2章 Python语言基本语法元素

来自CloudWiki
Cloud17讨论 | 贡献2020年1月22日 (三) 09:40的版本 语法元素的名称
跳转至: 导航搜索

程序的格式框架

缩进

  • python程序是依靠代码块的缩进来体现代码之间的逻辑关系的,缩进结束就表示一个代码块结束了。
  • 同一个级别的代码块的缩进量必须相同。
  • 一般而言,以4个空格为基本缩进单位
  • 如果缩进不对齐,程序会报错。

注释

  • 以符号#开始,表示本行#之后的内容为注释。
  • 包含在一对三引号...或"""..."""之间且不属于任何语句的内容将被解释器认为是注释。

语法元素的名称

变量

  • 变量是保存和表示是数据值的一种语法元素
  • 变量的值是可以改变的。
>>> a=100
>>> a=1+1
>>> print(a)

命名

Python采用大写字母、小写字母、数字、下划线和汉字等字符对变量进行命名

如:

 a,b,c , python_is_good ,Hello_world 等

保留字

#引入模块:
import keyword

k= keyword.kwlist
#查看保留字个数
print("python保留字个数:"+str(len(k))+"个")
#列出保留字
print(k)

数据类型

数字类型

>>> s=123
>>> print(s)
123
>>> d= s+b
>>> print(d)
98
>>> d=pow(2,3)
>>> print(d)
8
>>> b = 3.1416
>>> b
3.1416
>>> b = 10e5
>>> b
1000000.0
>>> b= 6.3+a
>>> print(b)
9.4415

字符串类型

字符串是Python里面重要的一种数据类型。

>>> s="对酒当歌,人生几何?"
>>> s[1]
'酒'
>>> s[-1]
'?'
>>> s[3]
'歌'
>>> s[-3]
'几'


可以通过[N:M]格式获取字符串的子串

>>> s ="譬如朝露,去日苦多"
>>> print(s[2:4])
朝露
>>> print(s[-3:-1])
日苦
>>> print(s[2:-2])
朝露,去日
>>> print(s[1:])
如朝露,去日苦多
>>> print(s[:])
譬如朝露,去日苦多

程序的语句元素

表达式

>>> 1024*32
32768
>>> 1024 > 32
True
>>> "对酒当歌,人生几何?" + "譬如朝露,去日苦多"
'对酒当歌,人生几何?譬如朝露,去日苦多'

赋值语句

通过赋值语句,能够对一个变量赋值。

7)

>>> a=1024*32
>>> print(a)
32768
>>> a,b=100,10
>>> x,y="譬如朝露",1024
>>> print(x)
譬如朝露
>>> print(b)
10

引用语句

import turtle
turtle.fd(-200)
turtle.right(90)
turtle.circle(200)

其他语句

分支和循环语句,将在后面重点介绍

基本输入输出函数

input()函数

输入函数。

>>> a=input("请输入一个小数:")
请输入一个小数:123.456
>>> print(a)
123.456

eval()函数

将字符串转换成表达式。

>>> b=eval("1.234")
>>> print(b)
1.234
>>> a=eval("1.2+3.4")
>>> print(a)
4.6

print()函数

>>> print('世界和平')
世界和平
>>> value=123.456
>>> print(value,value)
123.456 123.456
>>> a=24
>>> print(a,end=",")
24,
>>> print(a,end="%")
24%

源程序的书写风格

什么样的Python代码是漂亮的 ?

请先这行代码,然后查看输出:

>>> import this

Python之禅:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!