百行代码入门Python - Chapter 1

以下代码均用Python 3.5.2编写。
一下代码建立在一个名为HelloWorld.py的主程序中,当然名字是次要的,随便取一个,只要不和本文中的其它文件重名即可。读懂以下示例代码即可入门Python:

#Basics
print("Hello World")
example_dict={"liaobin":20, "yujing":18, "jiansheng":16}
print(example_dict["yujing"])

#if elif else Structure
if example_dict["liaobin"]>20:
    example_dict["yujing"]=example_dict["yujing"]+1
    print("Yujing + 1")
elif example_dict["liaobin"]<20:
    example_dict["yujing"]=example_dict["yujing"]-1
    print("Yujing - 1")
else:
    print("Nothing happened")

#for in Loop
for i in [1,2, [3,4],"life"]:
    print(i)

for i in range(3):
    print(i, "Hello for")

#while Loop
while i<5:
    print(i, "Hello while")
    i = i+1

#Function Definitation
def square_sum(a,b):
    """Return the square sum of two parameters"""
    a=a**2
    b=b**2
    return a+b

print(square_sum(1,2))
print(square_sum(b=2,a=1))

#package and unpackage
def package_position(*all_parameters):
    print(type(all_parameters))
    print(all_parameters[0])
    print(all_parameters[-1])

package_position(1,4,6)

def package_keyword(**all_parameters):
    print(type(all_parameters))
    print(all_parameters)

package_keyword(a=1,b=3,c=5)

def unpackage(a,b,c):
    print(a)
    print(b)
    print(c)

pkg_tuple=(5,6,7)
pkg_dict={"a":5,"b":6,"c":7}
unpackage(*pkg_tuple)
unpackage(*pkg_dict)
unpackage(**pkg_dict)

#Module
from first import laugh

for i in range(2):
    laugh()

一下代码在一个名为first.py的文件中,注意保存到与主文件相同的目录下

#Module
def laugh():
    print("Ha")

def big_laugh():
    print("HaHaHa")

按照代码分段从头开始看将后面的注释掉,即可体会其中原理。

上一篇:Fundamental of Computer Graphics (third edition) Chapter 5 Exercises


下一篇:百行代码入门Python - Chapter 6