Глосарій

Виберіть одне з ключових слів ліворуч ...

Programming in PythonBasics

Час читання: ~35 min

Let's begin by developing some basic vocabulary for the elements of a program. This section is an overview: will develop some of these ideas in greater depth in later sections.

Objects

An object is a fundamental entity that may be manipulated by a program. Objects have types; for example, 5 is an int (short for "integer") and "Hello world!" is a str (short for "string"). Types are important for the computer to keep track of, since objects are stored differently depending on their type.

You can check the type of an object using type. For example, running type("hello") gives str.

Exercise.
Use the code block below to find the type of 1.0. Does 1.0 have the same type as 1?

# replace this text with code and press enter while holding shift to run

(Note: you probably noticed the Loading or None returned message that appeared briefly when you ran the cell. If that message appears for more than 10 seconds or so, it's likely that the cell has run successfully but doesn't have anything to show as a result. We will discuss this in more detail soon.)

Variables

A variable is a name used to refer to an object. We can assign an object (say 41) to a variable (say age) as follows:

age = 41

We say that 41 is the value of the variable age.

Variable names must begin with an underscore or letter and contain only letters, digits, underscores after that. Letters may be uppercase or lowercase, and the case matters. For example extractValues0 is variable name, and stop! is variable name.

The object assigned to a given variable may be changed as many times as desired with further assignments.

Exercise.
Find the value of x at the end of the following block of code.

x = 3
y = x
x = x + 1
x = y

Solution. The value 3 is assigned to x and then also to y on the second line. After the third line, the value of x is 4, since the right-hand side works out to 4 an is then assigned to the variable x. After the fourth line 3 is of x again, since the value of y is still 3 when the fourth line is executed.

Exercise.
Use the code block below to find out what happens when you try to use a variable that hasn't had any object assigned to it: you get a Error.

num_carrots = 4
num_Carrots

Note that when an error occurs in your code, you get a traceback which helps you identify the source of the error.

Functions

A function performs a particular task. For example, print(x) writes a string representation of the value of the variable x to the screen.

Prompting a function to perform its task is referred to as calling the function. Functions are called using parentheses following the function's name, and any objects which are needed by the function are supplied between these parentheses, separated by commas. These objects are called arguments.

Some functions, like print are built into the language and are always available. You may also define your own functions using def:

def print_twice(x):
print(x)
print(x)

print_twice("hey")

def is an example of a keyword: a name with a special meaning in the language. Since it has a special meaning, a keyword may not be used as a variable name.

Note that the lines of code to be executed when the function is called must be indented four spaces relative to def. For example, print_twice("hey") part of the definition of the function in the example above.

A function may perform an action, like print_twice, or it may return an object. For example, after the following code block is run, the object 28 will be assigned to the variable y.

def add_one(x):
return x + 1

y

(Note: we put y by itself on the last line so that we can see the value of y in the output area. If an assignment (like y = 20 + add_one(7)) is the last line in the cell, then no value will be printed, and we will get the Loading or None returned message.)

The variable name x in the above block is called a parameter. Parameters play the same role as dummy variables in the definition of a mathematical function (for example, when the squaring function is defined using the notation fx=x2).

An operator is a special kind of function that can be called in a special way. For example, the multiplication operator * is called using the mathematically familiar infix notation 3 * 5.

Exercise
Arrange the operation descriptions below in order, according the corresponding Python operator in the list +, **, *, //, /. You might need to experiment using the code block below.

division (ordinary real-number division)
integer division (quotient only; no remainder)
multiplication
exponentiation
print(6 + 11)
print(2**5)
print(3 * 4)
print(7//2)
print(7/2)

Statements and expressions

An individual executable unit of code in Python is called a statement. For example, the assignment age = 41 is a statement. Statements may include expressions, which are combinations of values, variables, operators, and function calls that a language interprets and evaluates to a value. For example, 1 + age + abs(3*-4) is an expression which evaluates to (note that abs is the absolute value function, and assume age is set to the value specified earlier in the paragraph).

Exercise
def f(x): return x*x is

2 + 3*f(4) is

y = 13 is

myName = "John" + "Doe" is

an expression
a statement whose execution involves evaluating an expression

Exercises

Exercise
(Try doing this without executing the code.) The expression 1 + 5//3 + 2**3 evaluates to .

Exercise
(Try doing this without executing the code.) The expression 11/2-11//2-3 evaluates to , expressed as a decimal.

Exercise
Find the value of x at the end of the following block of code.

x = 3**2
x = x + 1
x = x + 1
y = x//2
x = y*y
z = 2*x

Exercise
Write a function f which takes a positive integer n as input and returns the $n$th positive odd integer. You should replace the line with the keyword pass in the code block below (the rest of the code, starting from the fourth line, checks that your function works).

Also, note that you have two boxes: the first is for scratch, and the second is for saving your answer. Once you're happy with your code, copy and paste it into the second box.

def f(n):

def test_f():
assert f(3) == 5
assert f(1) == 1
assert f(100) == 199
return "Tests passed!"

test_f()

Exercise
Select the true statements.

The statement balance = 46.04 assigns the value 46.04 to the variable balance.
The object 33 is a variable.
The value of a variable cannot be changed.
Variable names in Python are case-sensitive.
Bruno