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

来自CloudWiki
Cloud17讨论 | 贡献2019年10月5日 (六) 08:50的版本 程序的语句元素
跳转至: 导航搜索

程序的格式框架

语法元素的名称

数据类型

字符串类型

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

6)

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


程序的语句元素

表达式

>>> 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()函数

输入函数。

8)

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

eval()函数

将字符串转换成表达式。

9)

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

源程序的书写风格

>>> import this
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!