python_training_1

Control flow tools contains the usage of logical syntax and operators such as While, If, For and Break, Continue and Pass actions.

If statement is straightforward. You will notice that an if…elif…elif sequences is a subtitute for the switch or case statements found in other languages.
An example is

x = int(input(“Please enter an integer: “))
Please enter an integer: 42
if x < 0:
… x = 0
… print(‘Negative changed to zero’)
… elif x == 0:
… print(‘Zero’)
… elif x == 1:
… print(‘Single’)
… else:
… print(‘More’)

The for statement is a tool to iterate over a range of values. for example
words = [‘cat’, ‘window’,’defenestrate’]
for w in words:
print(w, len(w))

Break means stalled, halted, take a pause. But what is continue and pass? The continue statement borrowed from C, continues with the next iteration of the loop.
for num in range(2, 10):
if num % 2 == 0:
print(“found an even number”, num)
continue
print(“found a number”, num)
while pass does nothing. it’s commonly used for creating minical classes.
class MyEmptyClass:
pass

Coding style can be explained at this stage as I will be moving onto functions, which is an essetial element of almost all programing. When you start to write codes on your own, what kind of habitual style you take matters a lot for readability and ultimately productivity.
For Python, PEP 8 is the utmost style guide that engineers adhere to.
“here are the most important points extracted for you:

•Use 4-space indentation, and no tabs.

4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.

•Wrap lines so that they don’t exceed 79 characters.

This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

•Use blank lines to separate functions and classes, and larger blocks of code inside functions.

•When possible, put comments on a line of their own.

•Use docstrings.

•Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).

•Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).

•Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.”

•Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.