03、Python 系列之 永不过时的 hello world

1,194 阅读4分钟

版权声明:本文为博主原创文章,未经博主允许不得转载。

PS:转载请注明出处 作者:TigerChain 地址:http://www.jianshu.com/p/ca811667b21e 本文出自TigerChain简书 Python 系列

教程简介

  • 1、阅读对象

本篇教程适合新手阅读,老手直接略过

  • 2、教程难度

    初级

正文

经过前面的学习,我们成功的搭建了 python 的开发环境,这一节我们就是体验一把 使用 python 写一个 hello world

1、使用命令行输出 hello world

  • 1、打开终端输入 python 就进入了 pyton 的命令行编辑模式
 python //默认使用的是 python2
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
  • 2、输入以下内容
>>> print 'hello world' //直接按回车,就会出现以下内容
hello world
>>>

怎么样,简单吧,比如 Java 如何?比起 C 呢?来看看吧,在 Java 中编写一个 hello world

 class Main{
 	public static void main(String args[]){
 		System.out.print("hello world") ;
 	}
 }

对应 python 只需要一句话就搞定了「代码越少,出错的机率越少,写代码效率越高,不是吗?」

2、在文本编辑器中编写 python 代码,以 .py 结尾

  • 1、打开 atom 新建一个 01、永不过时的HelloWorld.py 输入以下内容
print 'hello word'
  • 2、运行些文件「两种方式」

方式一:

如果你安装了 atom-runner 直接 ctrl+R 就可以看到结果了

hello_python.png

方式二:

在命令行中进到到 01、永不过时的HelloWorld.py 所在目录,运行以下命令

 python 01、永不过时的HelloWorld.py //运行此命令,就会出现下面的结果
hello word

到此为止,hello world 就被我们搞出来了,so easy! 有的哥们说,我靠,我就不想输出 hello world 我想输出 你好,世界「你能把老子杂了???」,这还不简单吗,直接修改就好了。

  • 3、修改代码
print"你好世界"

运行查看结果

python 01、永不过时的HelloWorld.py
  File "01、永不过时的HelloWorld.py", line 1
SyntaxError: Non-ASCII character '\xe4' in file 01、永不过时的HelloWorld.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

what the fk ,什么鬼玩意,直接挂掉了,不要着急,我们看看报错信息大概就知道是和 ASCII 相关的东西,它加一了一个 Non,也就是说,python2 的默认编码是 ASCII,中文肯定不在这个码中。

3、中文编码

我们把以上代码在 python3 环境下运行一下,我们直接

 python3 01、永不过时的HelloWorld.py
你好,世界

我那个去,竟然不报错,并且成功运行了。

PS:Python3.X 源码文件默认使用utf-8编码,所以可以正常解析中文

  • 1、如何在 python2.x 上运行中文呢

只需要在文本最前面添加

#  -*- coding: UTF-8 -*-「推荐使用这个」  或者 #coding=utf-8 

即可,其中 # 是单选注释

  • 2、修改 demo
# -*- coding: UTF-8 -*-
print ("你好,世界")

运行查看结果

 python 01、永不过时的HelloWorld.py
你好,世界

通过上面结果,我们看到中文完美的在 python2.x 上面运行正常了。 到上为止,我们就完成了 hello world 的编写

注释

我们这里顺便说一下 python 里面的注释,注释的作用就是提高代码的可读性,方便别人读你的代码「也方便自己日后回头看,不至于忘记了」

注释的分类

  • 1、单行注释

在 python 中单行注释以 # 开始,右边的内容是对代码的说明,比如

# 我是注释,以下在 python3 中运行没有问题,但是在 python2 中运行就必须在文件首行添加 # -*- coding: UTF-8 -*-
print ("你好,世界")
  • 2、多行注释

我们对每一行进行 # 也可以起到注释多行的作用,但是这样也太蛋疼了吧「虽然 IDE 全选直接 ctrl+/ 就可以搞定,但是看起来还是很乱的」

在 python 中,多行注释使用 ''' ''' 来注释

例如:

''' 我是多行注释,我就是牛 B '''
print 'haha'

再比如:


''' 我是多行注释
    .--,           .--,
     ( (  \.---./  ) )
      '.__/o   o\__.'
         {=  ^  =}
          >  -  <
         /       \
        //       \\
       //|   .   |\\
       "'\       /'"_.-~^`'-.
          \  _  /--'         `
        ___)( )(___
       (((__) (__)))    高山仰止,景行行止.虽不能至,心向往之。
'''

以上就是 python 中的注释

据说每个勤奋努力的人都会点个喜欢