1. Testing Multiple Boolean Statements with Python's in Statement
If you have many different statements to test for, it can be easier to test them out using a list using this simple python trick. This can be done using the in statement and putting all test subjects in a list. For example, instead of:if name== 'ear' or name== 'nose' or name== 'eye'
you can simplify this down by using the in statement:
if name in ['ear', 'nose', 'eye']:
I regularly find myself using this handy python tip.
2. The For, Else Statements
Many of us know how to use the for statement, but you can also use the lesser known else clause after a for statement. The else clause will execute after the for loop is done executing, but will not execute if a break statement was issued. It will eighter execute once (if the for loop did not end with a break) or it will never execute (if the loop had a break). The else statement does not execute after every loop, it executes once the looping is complete. This is often used in "find and exit" situations. For example, instead of writing:
isFound= False
for item in iterable:
if do_something(item):
isFound= True
break
if isFound:
do_something_else()
you would simply write:
for item in iterable:
if do_something(item):
break
else:
do_something_else()
if do_something() returns True, it will cause the loop to break, thus preventing do_something_else() from being executed. If it returned False throughout the whole loop, the break statement would have never been called, causing do_something_else() to run.
if do_something() returns True, it will cause the loop to break, thus preventing do_something_else() from being executed. If it returned False throughout the whole loop, the break statement would have never been called, causing do_something_else() to run.
3. Quick Variable Assignments
There are a wide range of ways to assign values to variables. Although this is a simple python trick, it can come in handy and is good to know. Many different ways assign values to variables include:
>>> d= 1
>>> d= s= 1
>>> d
1
>>> s
1
>>> d= 2; s= 5
>>> d, s= s, d
>>> s
2
>>> d
5
>>> f= (5, 11)
>>> s, d= f
>>> s
5
>>> d
11
Remember to have care when using the d= s= 1 assignment, as it will hold reference to the same data which will cause trouble if you hold objects, lists and other things in them.
Believe it or not, functions can have variable parameters. This helpful python tip means that the parameter does not have to be predefined in order for the function to work correctly. They work by storing all the parameters in a tuple which can be used to look at them in the code. Performing variable functions is very simple but handy python trick:4. Variable Parameters to a function
def foo(*args):
for arg in args:
print(arg)
>>>foo(5, [5, 'string'], None)
5
[5, 'string']
None
Similarly, In order to give names to the parameters, you can use a dict like so:
def foo(**kwargs):
for key, value in kwargs.items():
print(str(key)+ ': '+ str(value))
You will probably see *args and **kwargs used a lot in other code. Like other parameters, you can call them whatever you want; it is a convention to call them that in python. Of course, you can make a mix and match between the tuple args, the dict, and a default on in a function:
def foo(cow, skunk= 2, **kwargs):
print('**kwargs recieved:')
for key, value in kwargs.items():
print(str(key)+ ': '+ str(value))
print()
print('cow is', cow)
print('skunk is', skunk)
>>>foo(5, skunk= 3)
**kwargs recieved:
cow is 5
skunk is 2
>>>foo(spam= 13, foogle= 42, pig= 17)
**kwargs recieved:
foogle: 42
pig: 17
spam is 13
wombat is 2
5. Perhaps The best Python Tricks: Easter Eggs
Although not quite a python tip or trick, the easter eggs are still worth mentioning. A good amount of them exist in python. I will not show what each easter egg does; it will ruin the surprise. I . So go grab IDLE and type these in:
>>>#Are braces to be expected in the future?
>>>from __future__ import braces
(...)>>>#Worth the read, if you know what I mean
>>>import this
(...)
>>>#python is doing a little bragging about its high level capabilities here
>>>import antigravity
(...)
And there you have it. I know I missed alot of python tricks so please do share your own python tricks and tips!
No comments:
Post a Comment