Here are a few handy tips and tricks, for those who are fairly new to Python.
Generally you'll come across many situations which involve variable assignment, followed by a while loop which performs any number of operations on this variable. For example:
You want to generate random numbers between 1 and 10, and stop when this number is odd, printing the number you get.
myvar = random.randint(1, 10)
while not (myvar % 2) == 1:
..myvar = random.randint(1, 10)
print myvar
This isn't very maintainable code - what if you later decided the range should be 1-100? You would have to edit two sections of your code.
Since Python doesn't support variable assignment within conditional statements, which some would argue is the most elegant solution, the most appropriate method to use here is as follows:
while True:
..myvar = random.randint(1, 10)
..if (myvar % 2) == 1: break
print myvar
When writing conditions, I often see people trying to write:
if myvar == 0:
..
and
if bool(myvar) == True:
..
This is entirely unnecessary. Python takes most datatypes as either true or false to begin with, so it's actually much simpler - and easier to follow - to just use:
if myvar:
..
What counts as False?
When you've only got one line of code to execute after a condition, it's often faster to type it directly after the colon, rather than using a new line and indenting:
if myvar == 5: print 'hello world!'
Obviously, whether you consider this more or less readable is up to you. Hint - this also works perfectly for defining functions.
You might be familiar with seeing these written as follows:
condition ? value-if-true : value-if-false
Many people like to use dictionaries or and/or to simulate ternary operators in Python, but neither of these methods is completely safe from error. Far better to use the built in method:
value-if-true if-condition else value if-false
For example:
'Pi equals 3.15' if math.pi == 3.14 else '3.14 ain't approximate enough'
Popularity: 2%
"if myvar:" may seem more readable but I think it's much better to do "if myvar == 0" / "if !myvar.IsNull()" (However python does null strings), as it makes it easier for other people to read your code, especially if they know another language but not python.
Not being able to assign variables conditional statements sounds awful. I haven't written much python, but I assign variables all the time (in conditional statements) in other languages.
I was initially annoyed that there was no way to assign variables in conditions (well, there is actually a sneaky way using a function, but that's messy) but I'm really glad now. So many of my problems in the past have been to do with writing
if var = 1:
#blah
And not having it flagged as a syntax error by the preparser.