How to write Python code?
Python is a popular programming language widely used in data science, scientific research, machine learning, robotics and Web development due to its emphasis on code readability and extensive libraries.
Before we learn to write Python code, we need to learn how Python code is executed.
Python code can be executed in a .py or .wpy file or in the Python intrepreter.
Executing a command or clicking on the file will cause a Python file to execute its program.
Writing a command in the Python interpreter and clicking "enter" will execute the command and display the result.
In order to use the Python interpreter or execute a file, you must have Python installed on your computer. Instructions for installing Python on your machine are available online.
Python uses significant indentation
In most programming languages, code indentation is meaningless and the programmer can organize his lines of code how he sees fit. In Python, the indentation is said to be significant because it represents the logical flow of the code. Code blocks are indented to show that they are part of the scope of a previous statement. A decrease in indentation signifies the end of a block of code.
In the Python interpreter, the 3 greater-than signs are called the prompt. The recommended indentation is 4 spaces.
if id3 > 0:
id3 = math.sqrt(id2)
else :
id4 = id1 * 2
How to write Python variables?
Python uses variables or identifiers to name its objects.
- The first character of a name can be any unicode letter, including the underscore _
- The following characters of a name can be any unicode letter, the underscore character _ or a number.
This means that spaces and hyphens are not allowed in a Python variable name.
Python identifiers are case sensitive: myVar is not the same as myvar.
What naming style should you use for Python variables?
It's important to be consistent in the naming style you use and to follow as much as possible name style conventions to make your code easier for others to read. This is the recommended naming style for Python code:
- UPPERCASE or UPPER_CASE for constants
- TitleCase for classes
- Camel case with first character in upper case for exceptions: AnExceptionError
- CamelCase for functions and methods
- Snake case for module names: a_module_name
- Lower case or snake case all other identifiers: lowercase or snake_case
NB_ITEMS = 12 # UPPER_CASE
class MyClass : # TitleCase
def myFunction() : # camelCase
number_of_months = 12 # snake case or lower case
To avoid confusion do not use these characters as identifiers: l, o and I.
Some identifier formats are used by Python, to avoid conflict do not use those formats:
_xxx : format of an identifier used within Python core code.
__xxx : format of a class attribute.
___xxx___ : reserved name.
What are Python version 3 reserved names?
and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
What is an expression in a programming language like Python?
An expression is a portion of code that the Python interpreter can execute to obtain a value. Expressions can be simple or complex. They are made of a combination of literals or values (numbers, true or false), variables and operators.
Examples of Python expressions:
id1 = 15.3
id2 = getId2(id1)
if id3 > 0:
id3 = math.sqrt(id2)
else :
id4 = id1 * 2
Which standard data types can we use in Python?
- int: the integer type
- bool: the boolean type (true or false)
The int type is the integer type. It is limited in size by the computer's memory. Whole numbers are decimals by default.
What arithmetic operations can we use in Python?
- Addition
>>> 20 + 3
23
- Subtraction:
>>> 20 - 3
17
- Multiplication
>>> 20 * 3
6
- Division with a decimal result
Convert the type of one argument to Float (decimal).
>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
- Division with integer result
>>> 20 / 3
6
- Modulo (The remainder of a division):
>>> 20 % 3
2
- Absolute value
>>> abs(3 -20)
17
How can we use the boolean type in Python?
The boolean type has two possible value: True,False
The result of operations using comparison operators produces a boolean value:
>>> 3 > 2
True
>>> 2 <= 8 < 15
False
What are the logical operators used in Python?
Python uses these logical operators:
- and: both expressions must be true for the result to be true
>>> (5 > 3) and (3 < 1)
False
- or: at least one expression must be true
>>> (5 > 3) or (3 < 1)
True
- not: changes a boolean value to its opposite
>>> not(5 > 3)
False
How do we evaluate logical expressions with short-circuit evaluation
Short-circuit evaluation means that when we use "and" to compare values, the first expression evaluating to False makes the result false. No need to evaluate the remaining expressions.
In this example, only (5 < 3) is evaluated.
>>> (5 < 3) and (3 > 1) and (2 > 1)
False
Short-circuit evaluation means that when we use "or" to compare values, the first expression evaluating to True makes the result True. No need to evaluate the remaining expressions.
In this example, only (1 < 3) is evaluated.
>>> (1 < 3) or (3 < 1) or (2 < 1)
True
How do we evaluate comparisons between True or False expressions in programming?
- True and True: True
- True and False: False
- True or True: True
- True or False: True
- False or False: False
- False and False: False
What is a unary operator?
A unary operator is an operator which takes one expression to produce a result.
Python uses the unary operator "not" to change boolean values to their opposite.
>>> not(True)
False
How do we ensure that an expression has a boolean value in Python?
To ensure that an expression has a boolean value use bool(expression)
>>> bool(1)
True
>>> bool(0)
False
How is the Float variable type used in Python?
A Float type represents decimal values in computing. In Python the Float type is written with a decimal point or with character "e" meaning exponential to the power of 10.
2.23
-1.6e-19
6.05678
The float data type is used with the same operators as the integer data type. The precision of a Float value is limited, which means that, when doing calculations, the accuracy of a result is limited by the capabilities of the machine.
Maths operations with the Float data type can be done using the maths module.
>>> import maths
>>> print(math.sin(math.pi/4))
0.7071067811865475
>>> print(math.degrees(math.pi))
180.0
>>> print(math.factorial(9))
362880
>>> print(math.log(1024, 2))
10.0
How is the complex type used in Python?
Complex types are written in cartesian notation with two floats. The imaginary part is suffixed with j. Complex type operations require the cmath module
>>> import cmath
>>> print(1j)
1j
>>> print((2+3j) + (4-7j))
6 - 4j
>>> print(cmath.rect(1., cmath.pi/4))
(0.7071067811865476+0.7071067811865475j)
How does variable assignment work in Python?
In computer programming, variables are used to carry values in various data types. For instance, a variable x can be assigned the integer value 1 or the boolean value True.
We assign a value to a variable using the equal sign.
>>> x = 1
>>> x = True
When we assign a new value to a variable, the former value is lost and deleted from memory by the garbage collector.
When we assign an expression to a variable the expression is evaluated to a value. Any variable is given its current value.
>>> a = 1
>>> b = 2
>>> a = b + a
3
>>> a = b + a
5
Do not assign a value while evaluating an expression in Python
When you assign a value the internal state of the program is modified, but the value cannot be assigned while also evaluating an expression, so Python throws an error.
>>> c = True
>>> s = (c = True) and True
File "<stdin>", line 1
s = (c = True) and True
^
SyntaxError : invalid syntax
Different ways to do variable assignments in Python
Type the following examples to remember variable assignments:
>>> v = 4 # simple assignment
>>> v += 2 # add 2 and assign result to v
>>> v
6
>>> c = d = 8 # right to left assignment
>>> c
8
>>> d
8
>>> e, f= 2.7, 5 # multiple assignments
>>> e
2.7
>>> g,h,i= ['G', 'H', 'I'] # assign the members of a list to individual variables
>>> g
'G'
>>> h
'H'
>>> i
'I'
>>> a = 19
>>> a, b = a + 2, a + 3 # multiple assignment with expression evaluation
>>> a,b
(21, 22)
In a future post on Python programming for beginners, I will write about using Python strings.
Rate This Post
Rate The Educational Value
Rate The Ease of Understanding and Presentation
Interesting or Boring? Rate the Entertainment Value
Navigate Thread:
Contributor's Box
Founder, lead software engineer, technical writer, and mentor at Boostlane.
I research ways to use artificial intelligence in information management and connect learners with mentors.
My ambition is to contribute to innovation and wealth creation by building a useful information-management platform, sharing knowledge, and helping people develop new skills.