This chapter is not an extensive tutorial but a basic knowledge of Python. In later chapters, the profound knowledge will be introduced with practical examples.

The programs in this chapter can be tested in all terminals.

Types of variable data

Strings

Python can manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result, such as ‘abc’, “xyz”, etc. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes, such as “I’m OK” contains 6 string: I, ’, m, empty space, O, K and 'abc' contains 3 strings: a, b, c.

e.g.

Booleans

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (important exception: the Boolean operations or and and always return one of their operands.)
Caution: capitalize the first letter in the True and False.

e.g.

import time
while True:
  print(“test”)
  time.sleep(1)

Booleans always used in the condition judgments.
e.g.

if(age >= 18):
  print('adult')
else:
  print("teenager")

Tips:In Python, you should use blank space to indent, not tab.

Integar

To create a new integer variable: a=123, you should save 123 to solid-state memory and a is the indices of 123 (conceptually as pointer in C language. 123s indices is a, so the reference count is 1); b=123, its reference count is 2. Change the value of a, a=1234: change the solid-state memory of 1234. Then 1234s indices is a, the reference count is 1; 123s indices is b, the reference count is 1. When the reference count of 123 is 0 (change the value of a and b, the reference count of 123 is 0, clear the solid-state memory of 123).

The current version of micro-python support plus (+), subtract (-), multiply (*) and divide (/), aliquot divide (//), power (**).

The experiment result in the terminal.

>>>
>>>100+500
600
>>>900+500
400
>>>10*5
50
>>>50/2
25.0
>>>50//2
25
>>>2**4
16

Float

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity.

In short, float is imprecise decimal. And the float operation has error caused by round up.

e.g.

>>>pi=3.14
>>>print(pi)
3.13999
>>>import math
>>>math.pi
3.141593

List

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. Variable l is a list.
e.g.

>>>l=[1,2,3,4]
>>>print(l)
[1,2,3,4]

The built-in function len also applies to lists.
e.g.

>>>len(l)
4

Remember the indices start from 0

>>>l[2]
3
>>>l[0]
1

If you want to replace features, you just need to assign to the position of the corresponding indices.
e.g.

>>>l[1]=9
>>>print(l)
[1,9,3,4]

Lists are a mutable type, i.e. it is possible to change their content. e.g. the position of the indices is 1, and insert x to position i by insert (i, x) and other features move backward. If the length of i is longer than the length of the list, add features in the end. If the length of i is above 0, add them from the start.

e.g.

>>>l.insert(1,6)
>>>print(l)
[1,6,2,3,4]

You can use pop (i) to delete the features of certain location, i is the insert position.

e.g.

>>>l.pop(2)
3
>>>print(l)
[1,2,4]

Tuple

The rules for indices are the same as for lists. However, once a tuple has been created, you can't add elements to a tuple or remove elements from a tuple. When there is only 1 feature in the tuple, we should add a comma.
e.g.

>>>t1=(1,)
>>>t1
(1,)
>>>t2=(1,2,3)
>>>t2
(1,2,3)

Without comma, the definition is no more tuple.
e.g.

>>>t=(1)
>>>t
1

When output two elements together, the result covers all features of two elements.
e.g.

>>>t1=(1,2,3)
>>>t2 = (4,5,6)
>>>print(t1+t2)
(1,2,3,4,5,6)

Dict

Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.

e.g.

>>>d={‘tom’:4, ’jerry’:6, ’seiya’:25}
>>>d[‘jerry’]
6

Besides initially setting, key also can put data to dict.

e.g.

>>>d[‘panda’]=12
>>>d=[‘panda’]
12

When value one key more than once, the later one will cover the preceding, for one key only corresponds to one value.

e.g.

>>>d[‘jack’]=10
>>>d[‘jack’]
10
>>> d[‘jack’]=9
>>> d[‘jack’]
9

pop (key) can delete both value and key from the dictionary.

>>>d.pop(‘seiya’)
25
>>>d
{'tom':4, 'jerry':6, 'jack':9}

Quote

Towards invariable objects (such as int, string, float and number, tuple), a is created as a copy of b. And a and b point to different saving address, independently.

e.g.

a=”I am ouki”
b=a
print(b)
a=”hello DFRobot”
print(b)

Towards variable objects (such as dictionary, list), a is created as a indices of b, sharing common storage address, dependently.

Fundamental grammar

Semicolon and colon

A little different from other languages, you need not end a line with semicolon. But it’s okay if you add it.

For conditions and functions, a colon should follow along. Without colon, error occurs as below.

Loop

For

for is applies to projects of all serials, such as a list or a string.

The grammar format of for is as below:

for iterating_var in sequence:  
  statements(s)

e.g.

for i in range(5):
  print(i)

while

while is used for execute programs. Which means under certain condition, it executes some program to deal with same tasks repeatedly.

Fundamental format:

  while condition of judgement:
        execution sentences.

e.g.

>>>i=9
>>>while(i>0):
. . .    print(i)
. . .    i-=1

The execution sentence could be a sentence or block statement.

The judgment condition could be all expressions, true for nonzero, non-null. When the judgment is false, the loop ends.

Function

The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.

e.g.

>>>def  my_abs(x):
. . .     if  x>=0:
. . .        return  x
. . .     else:
. . .        return  -x
. . .
>>>my_abs(5)
5
>>>my_abs(-6)
6

Press return twice back to >>> in the end of the definition of the function.

e.g.

>>>def  add(a,b):
. . .      retrun a+b
. . .
>>>add(4,2)
6

lambda

Lambda expression can quickly return to a function object and reduce numbers of functions effectively.

Format: lambda argument list; execute statement

e.g.

>>>sum=lambda x,y:x+y
>>>sum(3,5)
8
>>>

results matching ""

    No results matching ""