Script Setup & Statements
This lesson covers the best practices to follow when setting up a Python script. You saw that it is good idea to add a shebang statement at the top of your Python scripts. A shebang is useful when working with virtual environments that may contain third party applications.
You also learned how to specify the encoding of your script by adding this line to the top of your script:
# -*- coding: utf-8 -*-
This information is used by the Python parser to interpret the script using the given encoding. If no encoding is specified, ASCII is assumed. It is considered best practice to use UTF-8 since it has the added benefit of character support beyond ASCII-characters.
The last section of the lesson talks about the number of statements you should have on each line. Python supports writing multiple statements on a single line but this is considered bad practice. The pythonic way to write statements is to have each statement on its own line:
Bad
print 'Hello' ; print 'World'
if x == 1: print 'one'
Good
print 'Hello'
print 'World'
if x == 1:
print 'one'
00:00 As you may notice at the top of this file, we have a shebang statement followed by an encoding type. The shebang statement simply says to look in our environment and find the first Python executable in our path.
00:12 This is mainly useful for things like virtual envs which may contain third-party applications.
00:18
The encoding line is simply to tell the user of the script that the encoding of the file is UTF-8. When you don’t provide this, ASCII is assumed. It’s better to be explicit, so providing utf-8
gives you a wider character set and thus providing a more robust script. As you can see here, having one statement per line is the idiom in Python. You are able to do such things as using a semicolon (;
) to delimit between multiple statements on one line.
00:50 This is often considered bad practice. It’s best to keep the statements one per line.
Become a Member to join the conversation.