编程语言介绍 – Python : Getting Started

适合9-90岁的编程语言- Python介绍。

Python 是目前一门非常实用, 流行的计算机编程语言. 非常适合对编程感兴趣的同学初学入门, 它也是目前许多领域(计算机, 电信, 金融, 游戏,人工智能, 电影, 体育竞技) 广泛使用的计算机编程语言. 它的历史,起源,实用我们会单独分别阐述.

 

这篇入门的介绍, 目的是通过四个简单的程序, 给大家一个宏观的印象: 用 Python 这门计算机编程语言, 如何写程序, 编写好的程序结构是什么样的, 如何运行, 运行的输入输出结果是什么样的. 同时也希望在学完这篇入门, 大家会在脑海里有一个结构框架, 学习并能够自己清晰解释,阐述Python程序的简单结构, 输入, 输出, 变量, 函数, 条件, 控制, 循环, 跳转, 退出, 结束.

What is Python?
https://www.python.org/doc/essays/blurb/

 

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python’s simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program molecularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.

 

Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn’t catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python’s introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.

https://zh.wikipedia.org/wiki/Python

 

Python,是一种广泛使用的高级编程语言,属于通用型编程语言,由Guido van Rossum 创造,第一版发布于 1991 年。作为一种解释型语言,Python 的设计哲学强调代码的可读性和简洁的语法(尤其是使用空格缩进划分代码块,而非使用大括号或者关键词)。相比 C++ 或 Java,Python 让开发者能够用更少的代码表达想法。不管是小型还是大型程序,该语言都试图让程序的结构清晰明了。
与 Scheme、Ruby、Perl、Tcl 等动态类型编程语言一样,Python 拥有动态类型系统和垃圾回收功能,能够自动管理内存使用,并且支持多种编程范式,包括面向对象、命令式、函数式和过程式编程。其本身拥有一个巨大而广泛的标准库。

 

Python 虚拟机本身几乎可以在所有的操作系统中运行。Python 的官方解释器  CPython,用C语言编写,是一个由社群驱动的自由软件,目前由Python软件基金会管理。

1. Hello World

首先,启动命令行terminal. Its current working directory will be your home directory. It’s a good idea to make a directory for the files we’ll be creating in this tutorial, rather then having them loose in

your home directory.

 

You can create a directory called python using the command:

1
mkdir python

You will then need to change into this directory using the command:

1
cd python

The next step is to create an empty file using the command ‘touch’ followed by the filename. In this tutorial, we used the command:

1
touch hello_world.py

The final and most important part of setting up the file is making it executable. This allows us ot run python code inside the source code file hello_world.py. We do this with the command:

1
chmod +x hello_world.py

Now that we have the first source code file set up, we can open it up in vim, or any text editor of your choice. vim is a great editor with syntax highlighting support that should be available on any linux distribution.

1
2
3
4
# # # # #
#!/usr/bin/env python2
print ("Hello World")
# # # # #

The first ‘Hello World’ program is very simple, it has two lines. The very first line begins with a hashbang (the symbol #!) followed by the path to the python interpreter. The program loader uses this line to work out what the rest of the lines need to be interpreted with.

The code that is actually read by the python interpreter is only a single line. What it does is : it is passing the text string (value) to the print function by placing it in brackets immediately after the print function called. “Hell World” is enclosed in double quotation marks to indicate that it is a literal value and should not be interpreted as source code. The print function in python prints any value that gets passed to it from the console.

Save the changes you have just made to the file hello_world.py in vim editor. This is our first program. You can run the “Hello World” program by prefixing its filename with ./

In our case, you’d type:

1
./hello_world.py

And you will see output from your terminal/console.

最好是现场展示。目前还没找到如何在goodgoodstudy.uk Edit Post 模式下编辑code format 和粘贴截屏。

2. Variables and data types 变量和数据类型

A variable is a name in source code that is associated with an area in computer memory that can be used to store data, which is then called upon throughout the code. The data can be one of many types, including:

Integer 整数 Stores whole numbers
Float 浮点数 Stores decimal numbers
Boolean 逻辑 True or False
String 字符串 Stores a collection of characters. “Hello World” is a string

除了以上的主要数据类型,还有一种叫做“序列”的数据类型 。

list 可以包含多种类型的可改变的序列 [4.0, ‘string’, True]
tuple 可以包含多种类型的不可改变的序列 (4.0, ‘string’, True)
dict 一个可改变的由 键值对 组成的序列 {‘key1’: 1.0, 3: False}

List Contains a collection of data in a specific order
Tuple Contains a collection immutable(不可改变的) data in a specific order

A tuple would be used for something like a co-ordinate 坐标点, containing an x and y value stored as a single variable, whereas a list is typically used to store larger collections. The data stored in a tuple is immutable because you are’t able to change values of individual elements in a tuple. However, you can do so in a list.

It will also be useful to know about python’s dictionary type. A dictionary is a mapped data type. It stores data in key-value pairs. This means that you access values stored in the dictionary using that value’s corresponding key, which is different to how you would do it with a list. In a list, you would access an element of the list using that element’s index (a number representing the element’s position in the list).

Let us work on a program to demonstrate how to use variables and different data types. It is worth noting at this point that you don’t always have to specify data types in python.

Create the following code file called variables.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
!/usr/bin/env python2
hello_str="Hello World"

hello_int=21

hello_bool=True

hello_tuple=(21,32)

hello_list=["Hello,", "this", "is", "a", "list"]

hello_list=list()
hello_list.append("Hello,")
hello_list.append("this")
hello_list.append("is")
hello_list.append("a")
hello_list.append("list")

hello_dict={"first_name":"Liam",
"last_name":"Fraser",
"eye_colour":"Blue"}

print(hello_list[4])
hello_list[4]+="!"

print(hello_list[4])

hello_list[4]=hello_list[4] + "!"
print(hello_list[4])

print(str(hello_tuple[0]))

print(hello_dict["first_name"] + " " + hello_dict["last_name"] + " " + "has" + " " + hello_dict["eye_colour"] + " " + "eyes.")

print("{0} {1} has {2} eyes.".format(hello_dict["first_name"],
hello_dict["last_name"],
hello_dict["eye_colour"]))

An interpreted language such python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a complied language such a s C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.

3. Control structures 控制结构

In programming, a control structure is any kind of statement that can change the path that the code execution taken. For example, a control structure that decided to end the program if a number was less than 5 would look like this:

1
2
3
4
5
6
#!/usr/bin/env python3
import sys # used for sys.exit function
int_condition = 5

if int_condition < 5
    print("int_condition was < 6 - continuing")

The path that the code takes will depend on the value of the integer int_condition. The code in the ‘if ‘ block will only be executed if the condition is true. The import statement is used to load the python system library. The python system library provides the exit function, allowing this program to exit, printing an error message. Notice that indentation 缩排 (in this case four spaces per indent) is used to indicate which statement a block of code belongs to. The level of indentation dictates which statement a block of code belongs to. Indentation is mandatory in python. For this reason
, it is essential that you use a consistent indentation style. Four spaces are typically used to represent a single level of indentation in pytho. You can use tabs, but tabs are not well defined consistently in different text editor.

‘if’ statement are probably the most commonly used control structures. Other control structures include:

‘for’ statements, which allow you to iterate over items in collections, or to repeat a piece of code a certain number of times.

‘while’ statements, a loop that continues while the condition is true.

Next we’re going to write a program that accepts user input from the user to demonstrate how control structures work, the source code file is called construct.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python2

import sys

target_int=raw_input("How many integers? ")

try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an integer")

ints = list()

count = 0

while count < target_int:
    new_int = raw_input("Please enter integer {0}:".format(count+1))
    isint=True
    try:
        new_int=int(new_int)

    except:
        print("You must enter an integer")

    if isint == True:
       ints.append(new_int)
    count += 1

print("Using a for loop")
for value in ints:
    print(str(value))

# with a while loop
print("Using a while loop")
total = len(ints)
count = 0
while count < total:
    print(str(ints[count]))
    count += 1

The ‘for’ loop is using a local copy of the current value, which means any changes inside the loop won’t make any changes affecting the list.

On the other hand however, the ‘while’ loop is directly accessing elements in the list, so you could change the list there should you want to do so. We will talk about variable scope in some more detail later on.

The output from the above program is as follows:

Tip: you can define defaults for variables if you want to be able to call the function without passing any variables through at all. You do this by putting an equals sign after the variable name. For example,

1
def modify_string (original = "Default String" )
4. Functions and variable scope 函数和变量域

Functions are used in programming to break processes down into smaller chunks. This often makes code much easier to read. Functions can also be reusable if designed in a certain way. Functions can have variables passed to them. Variables in python are always passed by value, which means that a copy of the variables in passed to the function that is only valid in the scope of the function. Any changes make to the original variable inside the function will be discarded.

Function can also return values, so this isn’t an issue. Functions are defined with the keyword def, followed by the name of the function. Any variables that can be passed through are put in brackets following the function’s name. Multiple variables are separated by commas. The names given to the variables in these brackets are the ones that they will have in the scope of the function, regardless of what the variable that’s passed to the function is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python2
def modify_string(original):
original += " that has been modified."

def modify_string_return(original):
original += " that has been modified."
return original

test_string = "This is a test string"

modify_string(test_string)
print(test_string)

test_string=modify_string_return(test_string)
print(test_string)

Scope is an important thing to get the hang of, otherwise it can get you into same bad habits.

Let us write a quick small program to demonstrate this. It’s going to have a Boolean variable called cont, which will decide if a number will be assigned to a variable in an ‘if’ statement. However, the variable hasn’t been defined anywhere apart from in the scope of the ‘if’ statement. We’ll finish off by trying to print the variable.

1
2
3
4
5
6
7
8
#!/usr/bin/env python2

cont = False

if cont:
var = 1234

print (var)

In the above section of code, the python will convert the integer to a string before printing it. However, it is always a good idea to explicitly convert things to strings – especially when it comes to concatenating strings together. If you try to use the + operator on a string and an integer, there will be an error because it is not explicitly clear what needs to happen. var variable has only been defined in the scope of the ‘if’ statement. This means we will get an error when we try to access variable var

The + operator would usually add two integers together.

If cont is set to Boolean True, then the variable will be created and we can access it just fine. The correct way is to initialize the variable outside of the scope of the ‘if’ statement.

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python2

cont = False
var = 0 # variable var is initialized here

if cont:
var = 1234

if var != 0:
print (var)

The variable var is defined in a wider scope then the ‘if’ statement, and can still be accessed by the ‘if’ statement. Any changes made to var variable inside the ‘if’ statement are changing the variable defined in the large scope. This example does not really do anything useful apart from illustrate the potential problem.

5. Coding style 编程风格

It is worth taking a little time to talk about coding style. It is simple to write tidy code. The key is consistency. For example, you should always name your variables in the same manner. One crucial thing is to use self-documenting identifiers for variables so there is no need to guess what a variable does. The other thing that goes with this is to always comment the source code. This will help anyone else who reads your source code, and yourself in the future.

It is also useful to put a brief summary at the top of a code file describing what the application does, or a part of the application if it is made up of multiple source code files.

6. Summary 小结

This article should have introduced you to the basics of programming in python. Hopefully you are getting used to the syntax, indentation and general look and feel of a python program. The next step is to learn how to come up with a problem that you want to solve, and break it down into small enough steps that you can implement in a programming language.

The real fun of programming is solving problems at one manageable chunk at a time.

Happy coding!

2 thoughts on “编程语言介绍 – Python : Getting Started”

Comments are closed.