Programming Statement
Python Parser shares the same syntax with Python in programming statements including
if
, for
, while
,
break
, continue
, and pass
.
if Statement
Python Parser supports the if-else
statement and the
if-elif-else
statement.
x = 10
if x == 0:
print("Zero")
elif x > 0:
print("Positive")
else:
print("Negative")
for Statement
The for
statement is used to iterate over iterable sequences, such
as strings, lists, tuples, dictionaries (dict.items()
), and
sets.
-
Use the
for
statement to iterate over a range:for i in range(3): print(i)
Output:
0
1
2
-
Use the
for
statement to iterate over a string:for item in "ddb": print(item)
Output:
d
d
b
-
Use the
for
statement to iterate over a list:words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w))
Output:
cat 3
window 6
defenestrate 12
-
Use the
for
statement to iterate over a dictionary:dict_1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First','Address':'Beijing'} for key in dict_1: print(key, ":", dict_1[key])
Output:
Name : Zara
Age : 7
Class : First
Address : Beijing
-
Use the
for
statement to iterate over a set:A = {'1','2','star'} for item in A: print(item,end='')
Output:
1
2
star
while Statement
i = 1
while i<=10:
if i == 5:
break
print(i)
i+=1
Output:
1
2
3
4
break Statement and continue Statement
As keywords, break
and continue
can only be used
within loops. The break
statement is used to terminate a loop,
while the continue
statement is used to skip the current iteration
of a loop but continue with the next.
for i in range(1, 6):
if i == 4:
print('finish')
break # Terminate a loop.
print('I am ' + str(i) + ' years old')
Output:
I am 1 years old
I am 2 years old
I am 3 years old
finish
for i in range(1, 6):
if i == 4:
print('finish')
continue # Skip the current iteration of a loop and continue with the next.
print('I am ' + str(i) + ' years old')
Output:
I am 1 years old
I am 2 years old
I am 3 years old
finish
I am 5 years old
pass Statement
The pass
statement is used as a placeholder to keep the output
well-formed.
for letter in 'pear':
if letter == 'a':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Output:
Current Letter : p
Current Letter : e
This is pass block
Current Letter : a
Current Letter : r
Good bye!
Nested Loops
first = [2, 3, 4]
second = [20, 30, 40]
final = []
for i in first:
for j in second:
final.append(i+j)
print(final)
Output: [22, 32, 42, 23, 33, 43, 24, 34, 44]
assert Statement
The assert
statement in DolphinDB supports assert
expression
and assert string, expression
, while the
assert
statement in Python Parser supports assert
expression
and assert expression [, arguments]
.
assert 1==1
assert 1==2, '1 is not equal to 2'
Output: Testing case adhocTesting_"1 is not equal to 2" failed
try-catch Statement
The try-catch
statement in the current version of Python Parser can
only catch all exceptions.
def this_fails():
x = 1/`7
try:
this_fails()
except Exception as e:
print('error occur:' + e)
Output: "error occur:SYSTEM_Operator" : "error occur:Both arguments for ratio must be numbers."
raise Statement
To raise a user-defined exception, DolphinDB uses the throw statement while Python Parser uses the raise
statement with the syntax raise expression
.
def test_exception():
try:
raise "asdf"
except Exception as ex:
assert ex[0]=="USER"
assert ex[1]=="asdf"
assert typestr(ex) == "STRING PAIR"
try:
assert 1 == 112
1 + 2
except Exception as ex:
pass
a = 123
pass
pass
assert ex[0]=="C++"
assert ex[1]=="Testing case adhocTesting failed"
print("test_exception test pass")
test_exception()
Output: test_exception test pass
Comments
The comments in Python are different from those in DolphinDB but the same as those in Python.
Single-line comments start with the hash symbol # as follows:
// This is a comment
print("Hello, World!")
Multiline comments are enclosed with triple quotes (''' or """) as follows:
'''
This is the first comment
This is the second comment
This is the third comment
'''
print("Hello, World!")
Modules
In DolphinDB, module files use file extension ".dos" and stored in "<DolphinDB Home>/modules". In a DolphinDB session, users can reference a module with the "use" keyword.
In Python Parser, module files use file extension ".py" and stored in "<DolphinDB Home>/python" or a user-defined path (defined by sys.path). To use a user-defined path, it is necessary to restart the server before importing modules in Python Parser sessions.
Create a module file mod_test.py in "<DolphinDB Home>/python":
def f():
a = 10
b = 15
return a + b
To import a module, use the import
statement:
import mod_test
mod_test.f()
Output: 16
To import only parts from a module, use the from..import
keyword:
from mod_test import f
f()
Output: 16
To relocate a module, use sys.path to specify the search path for a module:
import sys
sys.path.append("/path/to/module")
To remove a module, use the undef
statement:
undef("mod_test")