3 Ex01 A good first program
3.1 First program
开始第一个有代码的学习,再次强调 Do not copy! Typing!
# -*- coding: utf-8 -*-
print "Hello World!" #这里是注释.
print "Hello Again." #没有分号(;)结尾,分隔语句.
print "I like typing this."
print "This is fun."
print "Ya! Printing."
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
# -*- coding: utf-8 -*-
这条语句表示我们需要使用Unicode UTF-8, 在编辑时输入中文会导致ASCII码错误,所以我们需要告诉Python, 我们需要使用Unicode UTF-8.
如果你输入代码没有错误,你将看到这样的输出:
3.2 错误处理
当然, 不是每次输入的代码都会是正确的, 如果遇到了错误:
$ python ex/ex1.py
File "ex/ex1.py", line 3
print "I like typing this.
^
SyntaxError: EOL while scanning string literal
- python解释器告诉我们错误的python源文件是ex1.py .
- 错误的地方在第三行 line 3.
- 同时解释器给出了确切的错误位置, 注意那个箭头!!! 他指给你这里错了! 这里是少了一个双引号.
- SyntaxError: EOL while scanning string literal. 这是错误类型,这里是语法错误.
3.3 问题探索
下面给出三个任务, 请自主探索, 如果做不到请学习后面章节.
1. 让你的程序打印一点好玩的东西, 比如: ❤
2. 让程序只在一行内打印.
3. 为什么要在程序开始放置一个#? 这个字符的作用是什么?
# -*- coding: utf-8 -*-
#问题探索1
print " *** *** "
print " ********* *********"
print "************ ************"
print "************* *************"
print "************** **************"
print "*************** ***************"
print " ******* *** *** *******"
print " ****** ***** ******"
print " ****** *** ******"
print " ****** * ******"
print " ****** * ******"
print " **************"
print " **********"
print " ******"
print " ***"
print " *"
# -*- coding: utf-8 -*-
#问题探索2
print "Hello World!", #在语句结尾加了逗号.
print "Hello Again.",
print "I like typing this.",
print "This is fun.",
print "Yay! Printing.",
print "I'd much rather you 'not'.",
print 'I "said" do not touch this.',
# -*- coding: utf-8 -*-
#问题探索3
#号是注释后面一行内容.
print "Hello Python!"