q vs python: If/else
(Series) A side-by-side comparison of q/kdb+ and python for qbies (q newbies).
This cheat sheet is a list of code snippets that do the same thing in q and python -- something I wished existed when I first came to q/KDB+ from python. Note that in both languages, the code shown is sometimes not the most elegant or succinct; that's on purpose because I wanted to show the same constructs in both languages. For a comprehensive intro to q, check out Q for Mortals.
Note q code snippets are edited to have line breaks for readability (my opinion; ymmv). Multiline statements do not work at the prompt, but they do work in scripts. See docs.
Versions: q (3.6), python (3.7)
If*
q)name:`bob
q)x:0
q)if[name=`bob;
x:x+1; / run this
x+:1; / run this too
x:x*10 / also this
];
q)x
20
|
>>> name = 'bob'
>>> x = 0
>>> if name == 'bob':
... x = x + 1
... x += 1
... x = x * 10
>>> x
20
|
If/else*
q)func:{[name]
y:0;
x:$[name=`foo;
0;
name=`bar;
[
y:9;
1
]
name=`baz;
2
/else
3
];
:x+y;
};
q)func `foo
0
q)func `bar
10
q)func[`baz] / square brackets optional
2
q)func[`qux]
3
|
>>> def func(name):
... y = 0
... if name == 'foo':
... x = 0
... elif name == 'bar':
... y = 9
... x = 1
... elif name == 'baz':
... x = 2
... else:
... x = 3
... return x + y
>>> func('foo')
0
>>> func('bar')
10
>>> func('baz')
2
>>> func('qux')
3
|