Skip to content

Lesson 2. Python Basics

Variables, Expressions and Statements (变量、表达式与语句)

Values and Data Types (数值和数据类型)

A value is hard to explain but one of fundamental things, like a letter or a number. Values belong to different data types:

Data Type Examples Type in Python
Integer 2 int
Float 0.4 float
String 'hello' str
Tuple (1, 2) tuple
List [1, 2, 3] list
Dictionary {"a": 1, "b": 2} dict

You can use type(value) to get the type of the value.

>>> type(2)
<class 'int'>
>>> type("Hello, world")
<class 'str'>
>>> type("2.2")
<class 'float'>
>>> type( (1, 2, 3) )
<class 'tuple'>
>>> type ( [1, 2, 3] )
<class 'list'>
>>> type ( { "a": 1, "b": 2 } )
<class 'dict'>

Variables

A variable is a name that refers to a value. And the value that a variable holds could be changed. We use an assignment statement (赋值语句) to create new variables and gives them values:

my_name = "Toggor"  # The "my_name" variable holds a string value which is "Toggor"
my_years = 34       # The "my_years" variable holds an integer value which is 34
my_height = 6.7     # The "my_height" variable holds a float value which is 6.7

In the assignment statement, = is called "assignment operator". Note: the operator (操作符) should not be confused with an equals sign. Assignment operators link a name, on the left hand side of the operator, with a value, on the right hand side. This is why you will get an error if you enter:

>>>23 = n

Variable Naming Rule (变量命名规则)

  • You can use letters, numbers and the underscore character _.
  • Variables' names must begin with a letter or the underscore character. For example, "7abc" is an illegal variable name.
  • Variables' names are case-sensitive(大小写敏感), which means "Abc" and "abc" are different variables.
  • Keywords(关键字) define the language’s rules and structure, and they cannot be used as variable names.

Examples

  • Legal varible names: TheiaAcademy, theia_academy, _student2020, a_very_very_long_variable_name
  • Ilegal varible names: 2020student (Begin with a digit.) Thiea Academy (Space is not allowed.), abc$ ($ is not allowed.)

Statements

A statement is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.

a = 1   # We assign 1 to a variable "a".
print(a) # We print the value that variable "a" holds on the screen.
b = a / 3  # We evaluate the expression "a/3" and assign the result to a variable "b"

We are familiar with the built-in(内置) output function print(), and now we will learn the usage of input function input()

name = input("Please input your name: ")
print("Your name is:", name)
years = int(input("Please input your age: "))
print("You are", years, "years old")

Expression

An expression is a combination of values, variables, and operators(操作符).

Operators and operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands(操作数). The following are all legal Python expressions whose meaning is more or less clear:

20+32   hour-1   hour*60+minute   minute/60   5**2   (5+9)*(15-7)

We have learned common operators in the lesson 1, and in this lesson we will learn some operations on string. For strings:

  • the + operator represents concatenation(连接), which means joining the two operands by linking them end-to-end:

    fruit = "banana"
    baked_good = " nut bread"
    print(fruit + baked_good)
    
  • The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a string; the other has to be an integer.

Comments(注释)

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they are marked with the # symbol:

percentage = (minute * 100) / 60
# compute the percentage of the hour that has elapsed
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

percentage = (minute * 100) / 60     # caution: integer division

Everything from the # to the end of the line is ignored — it has no effect on the program. The message is intended for the programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising behavior of integer division.

Function(函数)

We could used a function to wrap a sequence of statements. The syntax of a function definetion (函数定义) is:

def function_name(parameter_list...):
    STATEMENTS

You can make up any names you want for the functions you create, except that you can’t use a name that is a Python keyword. The list of parameters specifies what information, if any, you have to provide in order to use the new function.

There can be any number of statements inside the function, but they have to be indented from the def. In the examples in this book, we will use the standard indentation of four spaces. Function definitions are the first of several compound statements we will see, all of which have the same pattern:

  • A header, which begins with a keyword and ends with a colon.
  • A body consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header.

In a function definition, the keyword in the header is def, which is followed by the name of the function and a list of parameters enclosed in parentheses. The parameter list may be empty, or it may contain any number of parameters. In either case, the parentheses are required.

The first couple of functions we are going to write have no parameters, so the syntax looks like this:

def new_line():
  print()         # a print function with no arguments prints a new line

This function is named new_line. The empty parentheses indicate that it has no parameters. Its body contains only a single statement, which outputs a newline character. (That’s what happens when you use a print command without any arguments.)

Defining a new function does not make the function run. To do that we need a function call. Function calls contain the name of the function being executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition. Our first examples have an empty parameter list, so the function calls do not take any arguments. Notice, however, that the parentheses are required in the function call:

print("First Line.")
new_line()
print("Second Line.")

The output of this program is:

First line.

Second line.

The extra space between the two lines is a result of the new_line() function call. What if we wanted more space between the lines? We could call the same function repeatedly:

print("First Line.")
new_line()
new_line()
new_line()
print("Second Line.")

Or we could write a new function named three_lines that prints three new lines:

def three_lines():
    new_line()
    new_line()
    new_line()

print("First Line.")
three_lines()
print("Second Line.")

This function contains three statements, all of which are indented by four spaces. Since the next statement is not indented, Python knows that it is not part of the function. You should notice a few things about this program:

  • You can call the same procedure repeatedly. In fact, it is quite common and useful to do so.
  • You can have one function call another function; in this case three_lines calls new_line.

So far, it may not be clear why it is worth the trouble to create all of these new functions. Actually, there are a lot of reasons, but this example demonstrates two:

  • Creating a new function gives you an opportunity to name a group of statements. Functions can simplify a program by hiding a complex computation behind a single command and by using English words in place of arcane code.
  • Creating a new function can make a program smaller by eliminating repetitive code. For example, a short way to print nine consecutive new lines is to call three_lines three times.

Pulling together the code fragments from the previous section into a script named lesson2.py, the whole program looks like this:

def new_line():
  print()

def three_lines():
  new_line()
  new_line()
  new_line()

print("First Line.")
three_lines()
print("Second Line.")

This program contains two function definitions: new_line and three_lines. Function definitions get executed just like other statements, but the effect is to create the new function. The statements inside the function do not get executed until the function is called, and the function definition generates no output.

As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.

Tasks

Task 1

Using the internet search engines, find all keywords in Python 3.

Task 2

  1. Record what happens when you print an assignment statement:

    >>> print (n = 7)
    

    How about this?

      >>> print (7 + 5)
    
    Or this?

    >>> print (5.2, "this", 4 - 2, "that", 5/2.0)
    

    Can you think of a general rule for what can follow the print function? What does the print function return?

  2. Try the following in the interpreter and record what happens:

    >>> x = input()
    >>> type(x)
    
    >>> y = input("Please input a number: ")
    >>> result = y + 2
    

    What happened? Could you explain the result?

    >>> x = float(input("Please input a number: "))
    >>> y = float(input("Please input another number: "))
    >>> print(x, "+", y, "=", x+y)
    

Task 3

  1. Using Visual Studio Code editor, create a Python script named task2_1.py. Write a function in this file called nine_lines that uses three_lines to print nine blank lines. Now add a function named clear_screen that prints out twenty-five blank lines. The last line of your program should be a call to clear_screen.

  2. Move the last line of task2_1.py to the top of the program, so the function call to clear_screen appears before the function definition. Run the program and record what error message you get. Can you state a rule about function definitions and function calls which describes where they can appear relative to each other in a program?

  3. Starting with a working version of task2_1.py, move the definition of new_line after the definition of three_lines. Record what happens when you run this program. Now move the definition of new_line below a call to three_lines(). Explain how this is an example of the rule you stated in the previous exercise.