“第2章 Python语言基本语法元素”的版本间的差异

来自CloudWiki
跳转至: 导航搜索
基本输入输出函数
程序的格式框架
第1行: 第1行:
 
==程序的格式框架==
 
==程序的格式框架==
 +
==缩进==
 +
*python程序是依靠代码块的缩进来体现代码之间的逻辑关系的,缩进结束就表示一个代码块结束了。
 +
*同一个级别的代码块的缩进量必须相同。
 +
*一般而言,以4个空格为基本缩进单位
 +
*'''如果缩进不对齐,程序会报错。'''
 +
 +
==注释==
 +
*以符号#开始,表示本行#之后的内容为注释。
 +
*包含在一对三引号'''...'''或"""..."""之间且不属于任何语句的内容将被解释器认为是注释。
  
 
==语法元素的名称==
 
==语法元素的名称==

2019年11月8日 (五) 01:38的版本

程序的格式框架

缩进

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

注释

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

语法元素的名称

数据类型

字符串类型

字符串是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

print()函数

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

源程序的书写风格

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