python基础(三)

1.10.2 让脚本像普通程序一样运行(双击运行)

在脚本首行加上#!(pound bang/shebang),在其后加上用于解释脚本的程序的绝对路径

#!/usr/bin/python

加入代码 raw_input("Press<enter>") 才能输出结果

#!urs/bin/python
name = raw_input("What is your name?")
print "Hello." + name + "!"
raw_input("Press<enter>")

1.10.3 注释

井号(#)出现:右边的一切都会被忽略

#打印圆的周长:
print 2 * pi * radius

这里的第一行称为注释——为了让别人更容易理解程序

确保注释说得都是重要的事,而不要重复代码中显而易见的内容。以下为错误示范

# 获得用户名
user_name = raw_input(What is your name?")

 

1.11 字符串

"Hello, world!" 是什么? 是字符串(一串字符)最主要的用法就是表示一些文本

1.11.1 单引号字符串和转义引号

下例中在程序中用的是双引号,但当Python打印出字符串的时候是用单引号括起来的。事实上,他们没有任何区别

>>> "Hello, world!"
'Hello, world!'
>>> "Let's go!"
"Let's go!"
>>> '"Hello, world!"she said'
'"Hello, world!"she said'

在上面的代码中,第一段字符串包含了单引号,这时候就不能用单引号将整个字符串括起来了。如果这么做,解释器会抱怨道

>>> 'Let's go!'
SyntaxError: invalid syntax

在这里字符为'Let",Python 并不知道如何处理后面的s(也就是该行余下的内容)

在第二个字符串中,句子包含了双引号。所以,出于之前的原因,就需要用单引号把字符串括起来 

>>> '"Hello, world!"she said'
'"Hello, world!"she said'

或者,使用反斜线(\)对字符串中的引号进行转义:

>>> 'Let\'s go!'
"Let's go!"

Python 会明白中间的单引号是字符串的一个字符而而不是字符串的结束标记。对双引号也可以使用相同的方式转义。

 

>>> "\"Hello, world!\"she said"
'"Hello, world!"she said'

 

posted @ 2018-03-13 22:16  小朋友的yy  阅读(71)  评论(0)    收藏  举报