• 7 December 2024

Some Python useful samples

args usage

>>> def my_prt(*args):
...     for arg in args:
...         print(f"{arg}")
...
>>> a = ["a","b","c"]
>>> my_prt(*a)
a
b
c
>>> my_prt("x","y","z")
x
y
z

multiple return & one line if

>>> def four_tran(x,y):
...  return x+y , x-y if x>=y else y-x , x*y , x/y if x>=y else y/x
...
>>> result = four_tran(5, 8)
>>> result
(13, 3, 40, 1.6)
>>> type(result)
<class 'tuple'>

lambda function & one line if

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

>>> exponential = lambda x,y=2 : x ** y
>>> exponential(5)
25
>>> exponential(5,3)
125

>>> even_odd = lambda x: f"{x} is even!" if x % 2 == 0 else f"{x} is odd!"
>>> even_odd(5)
'5 is odd!'
>>> even_odd(24)
'24 is even!'

eval and exec usage

>>> a = 10
>>> b = 5
>>> command = "a+b"
>>> exec(command)
>>> c = exec(command)
>>> c
>>> command = "c=a+b"
>>> exec(command)
>>> c
15
>>>
>>> eval(command)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    c = a + b
      ^
SyntaxError: invalid syntax
>>> c = None
>>>
>>> command = "a+b"
>>> eval(command)
15
>>> c
>>> c = eval(command)
>>> c
15

pip reference